<?php
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }
require_once '../config.php';
require_once '../includes/canteen_helpers.php';

// Only admin/headteacher can complete setup
canteen_require_role(['admin', 'headteacher']);

$conn = getDBConnection();

// Already completed?
$settings = canteen_get_settings();
if (!empty($settings['setup_completed'])) {
    $conn->close();
    header('Location: setup.php');
    exit;
}

// Handle wizard POST saves
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $step = (int) ($_POST['step'] ?? 0);

    if ($step === 2) {
        // Save default session preferences (just mark step done via session)
        $_SESSION['onboarding_step2_done'] = true;
        echo json_encode(['success' => true]);
        exit;
    }

    if ($step === 3) {
        // Save verification method choices
        $qr_enabled      = isset($_POST['qr_enabled'])      ? 1 : 0;
        $manual_fallback = isset($_POST['manual_fallback'])  ? 1 : 0;
        $stmt = $conn->prepare(
            "UPDATE canteen_settings SET qr_enabled = ?, manual_id_fallback = ? WHERE school_id = 1"
        );
        $stmt->bind_param('ii', $qr_enabled, $manual_fallback);
        $stmt->execute();
        $stmt->close();
        unset($_SESSION['canteen_settings'], $_SESSION['canteen_settings_ts']);
        echo json_encode(['success' => true]);
        exit;
    }

    if ($step === 5) {
        // Mark setup complete
        $now = date('Y-m-d H:i:s');
        $stmt = $conn->prepare(
            "UPDATE canteen_settings SET setup_completed = 1, setup_completed_at = ? WHERE school_id = 1"
        );
        $stmt->bind_param('s', $now);
        $stmt->execute();
        $stmt->close();
        unset($_SESSION['canteen_settings'], $_SESSION['canteen_settings_ts']);
        logActivity($conn, (int)$_SESSION['user_id'], 'canteen_onboarding_complete', 'Canteen module setup completed');
        $conn->close();
        echo json_encode(['success' => true, 'redirect' => 'setup.php']);
        exit;
    }
}

// Load classes for session defaults
$classes = [];
$cRes = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
while ($r = $cRes->fetch_assoc()) $classes[] = $r['class_name'];

$conn->close();

// Scanner URL (share with canteen device)
$scanner_url = rtrim(BASE_URL, '/') . '/canteen/scanner.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canteen Setup Wizard — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
    <style>
        body { background: linear-gradient(135deg, #0f172a 0%, #1e3a5f 100%); min-height: 100vh; display: flex; align-items: center; justify-content: center; padding: 2rem 1rem; }
        .wizard-card { background: #fff; border-radius: 20px; box-shadow: 0 25px 60px rgba(0,0,0,.35); max-width: 680px; width: 100%; overflow: hidden; }
        .wizard-header { background: linear-gradient(135deg, #1e3a5f, #1e40af); padding: 2rem 2.5rem 1.5rem; color: #fff; }
        .wizard-header h2 { font-size: 1.5rem; font-weight: 700; margin: 0; }
        .wizard-header p { font-size: .9rem; opacity: .8; margin: .25rem 0 0; }
        .progress-steps { display: flex; gap: .5rem; margin-top: 1.25rem; }
        .step-dot { flex: 1; height: 4px; border-radius: 2px; background: rgba(255,255,255,.25); transition: background .3s; }
        .step-dot.done { background: #4ade80; }
        .step-dot.active { background: #fff; }
        .wizard-body { padding: 2rem 2.5rem; }
        .step-panel { display: none; }
        .step-panel.active { display: block; }
        .step-icon { width: 60px; height: 60px; border-radius: 16px; display: flex; align-items: center; justify-content: center; font-size: 1.5rem; margin-bottom: 1rem; }
        .step-icon.green  { background: #dcfce7; color: #16a34a; }
        .step-icon.blue   { background: #dbeafe; color: #1d4ed8; }
        .step-icon.amber  { background: #fef3c7; color: #b45309; }
        .step-icon.purple { background: #f3e8ff; color: #7c3aed; }
        .step-icon.emerald{ background: #d1fae5; color: #059669; }
        .wizard-nav { display: flex; justify-content: space-between; align-items: center; padding: 1.25rem 2.5rem 2rem; border-top: 1px solid #f1f5f9; }
        .method-card { border: 2px solid #e2e8f0; border-radius: 12px; padding: 1rem; cursor: pointer; transition: all .2s; }
        .method-card:hover { border-color: #93c5fd; background: #f0f9ff; }
        .method-card.selected { border-color: #1d4ed8; background: #eff6ff; }
        .method-card input[type="checkbox"] { display: none; }
        .check-indicator { width: 22px; height: 22px; border-radius: 50%; border: 2px solid #cbd5e1; display: flex; align-items: center; justify-content: center; font-size: .7rem; }
        .method-card.selected .check-indicator { background: #1d4ed8; border-color: #1d4ed8; color: #fff; }
        .feature-list li { padding: .3rem 0; font-size: .9rem; }
        #step4Qr { display: flex; justify-content: center; margin: 1rem 0; }
    </style>
</head>
<body>

<div class="wizard-card">
    <div class="wizard-header">
        <div class="d-flex align-items-center gap-2 mb-1">
            <i class="fas fa-utensils"></i>
            <span style="font-size:.8rem;opacity:.7;text-transform:uppercase;letter-spacing:.1em">Canteen Module</span>
        </div>
        <h2>Setup Wizard</h2>
        <p id="stepSubtitle">Welcome to EduTrack Canteen</p>
        <div class="progress-steps">
            <div class="step-dot active" id="dot1"></div>
            <div class="step-dot" id="dot2"></div>
            <div class="step-dot" id="dot3"></div>
            <div class="step-dot" id="dot4"></div>
            <div class="step-dot" id="dot5"></div>
        </div>
    </div>

    <div class="wizard-body">

        <!-- Step 1 — Welcome -->
        <div class="step-panel active" id="panel1">
            <div class="step-icon green"><i class="fas fa-utensils"></i></div>
            <h4 class="fw-bold mb-1">Welcome to the Canteen Module</h4>
            <p class="text-muted mb-3">This wizard takes 2 minutes to get your canteen running. Here's what this module does:</p>
            <ul class="feature-list list-unstyled">
                <li><i class="fas fa-check-circle text-success me-2"></i><strong>Eliminates Queue 1</strong> — Cashiers scan student QR to collect fees in seconds, not minutes</li>
                <li><i class="fas fa-check-circle text-success me-2"></i><strong>Eliminates Queue 2</strong> — Canteen window scans a daily pass QR instead of manual lookup</li>
                <li><i class="fas fa-check-circle text-success me-2"></i><strong>Cook's Dashboard</strong> — Live meal count updates so the cook knows exactly how many to prepare</li>
                <li><i class="fas fa-check-circle text-success me-2"></i><strong>Parent Notifications</strong> — Parents see meal confirmation on the parent portal</li>
                <li><i class="fas fa-check-circle text-success me-2"></i><strong>Works offline</strong> — Scanner caches today's passes, so internet outages don't stop service</li>
            </ul>
        </div>

        <!-- Step 2 — Create Meal Sessions -->
        <div class="step-panel" id="panel2">
            <div class="step-icon blue"><i class="fas fa-calendar-plus"></i></div>
            <h4 class="fw-bold mb-1">Create Meal Sessions</h4>
            <p class="text-muted mb-3">Choose which meals your school runs. You can configure exact times and prices in Session Setup later.</p>
            <div class="row g-2">
                <div class="col-4">
                    <div class="method-card selected" onclick="toggleMethod(this)" data-value="breakfast">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <i class="fas fa-coffee text-warning fs-4"></i>
                            <div class="check-indicator"><i class="fas fa-check"></i></div>
                        </div>
                        <div class="fw-semibold">Breakfast</div>
                        <div class="text-muted" style="font-size:.78rem">Typical 6:30–7:30am</div>
                        <input type="checkbox" name="sessions[]" value="breakfast" checked>
                    </div>
                </div>
                <div class="col-4">
                    <div class="method-card selected" onclick="toggleMethod(this)" data-value="lunch">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <i class="fas fa-utensils text-success fs-4"></i>
                            <div class="check-indicator"><i class="fas fa-check"></i></div>
                        </div>
                        <div class="fw-semibold">Lunch</div>
                        <div class="text-muted" style="font-size:.78rem">Typical 12:00–1:00pm</div>
                        <input type="checkbox" name="sessions[]" value="lunch" checked>
                    </div>
                </div>
                <div class="col-4">
                    <div class="method-card" onclick="toggleMethod(this)" data-value="supper">
                        <div class="d-flex justify-content-between align-items-start mb-2">
                            <i class="fas fa-moon text-primary fs-4"></i>
                            <div class="check-indicator"><i class="fas fa-check"></i></div>
                        </div>
                        <div class="fw-semibold">Supper</div>
                        <div class="text-muted" style="font-size:.78rem">Boarding schools only</div>
                        <input type="checkbox" name="sessions[]" value="supper">
                    </div>
                </div>
            </div>
            <p class="text-muted small mt-2"><i class="fas fa-info-circle me-1"></i>Session times, prices, and classes are set in <strong>Session Setup</strong> after this wizard.</p>
        </div>

        <!-- Step 3 — Verification Method -->
        <div class="step-panel" id="panel3">
            <div class="step-icon amber"><i class="fas fa-shield-alt"></i></div>
            <h4 class="fw-bold mb-1">Choose Verification Method</h4>
            <p class="text-muted mb-3">How students prove they've paid at the canteen window:</p>
            <div class="d-flex flex-column gap-2">
                <div class="method-card selected" onclick="toggleMethod(this)" data-value="qr">
                    <div class="d-flex gap-3 align-items-start">
                        <i class="fas fa-qrcode text-success fs-3"></i>
                        <div class="flex-grow-1">
                            <div class="fw-semibold">QR Code <span class="badge bg-success ms-1" style="font-size:.65rem">Recommended</span></div>
                            <div class="text-muted small">Parent shows daily QR pass on their phone. Free, works immediately — no hardware needed.</div>
                        </div>
                        <div class="check-indicator ms-2"><i class="fas fa-check"></i></div>
                    </div>
                    <input type="checkbox" name="qr_enabled" value="1" checked>
                </div>
                <div class="method-card selected" onclick="toggleMethod(this)" data-value="manual">
                    <div class="d-flex gap-3 align-items-start">
                        <i class="fas fa-keyboard text-secondary fs-3"></i>
                        <div class="flex-grow-1">
                            <div class="fw-semibold">Manual ID Fallback <span class="badge bg-secondary ms-1" style="font-size:.65rem">Permanent safety net</span></div>
                            <div class="text-muted small">Staff can type the 5-digit student ID when QR scanning fails. Recommended to keep on.</div>
                        </div>
                        <div class="check-indicator ms-2"><i class="fas fa-check"></i></div>
                    </div>
                    <input type="checkbox" name="manual_fallback" value="1" checked>
                </div>
                <div class="method-card" onclick="toggleMethod(this)" data-value="biometrics">
                    <div class="d-flex gap-3 align-items-start">
                        <i class="fas fa-fingerprint text-purple fs-3" style="color:#7c3aed"></i>
                        <div class="flex-grow-1">
                            <div class="fw-semibold">Biometrics <span class="badge bg-secondary ms-1" style="font-size:.65rem">Optional upgrade</span></div>
                            <div class="text-muted small">Fingerprint (GHS 280–500 scanner) or facial recognition (GHS 80–260 webcam). Configure in Settings after setup.</div>
                        </div>
                        <div class="check-indicator ms-2"><i class="fas fa-check"></i></div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Step 4 — Open Scanner -->
        <div class="step-panel" id="panel4">
            <div class="step-icon purple"><i class="fas fa-qrcode"></i></div>
            <h4 class="fw-bold mb-1">Open the Scanner</h4>
            <p class="text-muted mb-3">Share this link with the person at your canteen window. They open it on any device — phone, tablet, or computer.</p>
            <div class="d-flex align-items-center gap-2 mb-3">
                <input type="text" class="form-control form-control-sm" id="scannerUrl"
                       value="<?php echo htmlspecialchars($scanner_url); ?>" readonly>
                <button class="btn btn-outline-secondary btn-sm" onclick="copyUrl()">
                    <i class="fas fa-copy"></i>
                </button>
            </div>
            <div class="text-center mb-2">
                <p class="text-muted small mb-2">Or scan this QR code with the canteen device:</p>
                <div id="step4Qr"></div>
            </div>
            <div class="alert alert-light border d-flex gap-2 py-2 mt-2" style="font-size:.82rem">
                <i class="fas fa-lock text-muted mt-1"></i>
                <div>The scanner requires a 4-digit PIN. Set it in <strong>Canteen → Settings → General</strong> before handing to canteen staff.</div>
            </div>
        </div>

        <!-- Step 5 — Done -->
        <div class="step-panel" id="panel5">
            <div class="step-icon emerald"><i class="fas fa-check"></i></div>
            <h4 class="fw-bold mb-1">You're all set!</h4>
            <p class="text-muted mb-3">The Canteen Module is ready. Here's your quick-start checklist:</p>
            <div class="d-flex flex-column gap-2">
                <div class="d-flex gap-2 align-items-center p-2 rounded" style="background:#f0fdf4">
                    <i class="fas fa-circle-check text-success"></i>
                    <span style="font-size:.88rem">Go to <a href="setup.php" class="fw-semibold">Canteen → Session Setup</a> and create today's sessions</span>
                </div>
                <div class="d-flex gap-2 align-items-center p-2 rounded" style="background:#eff6ff">
                    <i class="fas fa-circle-check text-primary"></i>
                    <span style="font-size:.88rem">Open <a href="settings.php" class="fw-semibold">Settings</a> to set Scanner PIN and Cook PIN</span>
                </div>
                <div class="d-flex gap-2 align-items-center p-2 rounded" style="background:#fef9c3">
                    <i class="fas fa-circle-check text-warning"></i>
                    <span style="font-size:.88rem">Share the <a href="scanner.php" target="_blank" class="fw-semibold">Scanner URL</a> with your canteen staff</span>
                </div>
                <div class="d-flex gap-2 align-items-center p-2 rounded" style="background:#faf5ff">
                    <i class="fas fa-circle-check" style="color:#7c3aed"></i>
                    <span style="font-size:.88rem">Collect a feeding fee on <a href="../fees_express.php" class="fw-semibold">Express Collection</a> to create the first QR pass</span>
                </div>
            </div>
        </div>

    </div><!-- /wizard-body -->

    <div class="wizard-nav">
        <button class="btn btn-outline-secondary btn-sm" id="btnBack" onclick="goStep(-1)" style="display:none">
            <i class="fas fa-arrow-left me-1"></i>Back
        </button>
        <div class="text-muted small" id="stepCounter">Step 1 of 5</div>
        <button class="btn btn-primary" id="btnNext" onclick="goStep(1)">
            Next <i class="fas fa-arrow-right ms-1"></i>
        </button>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
<script>
let currentStep = 1;
const totalSteps = 5;

const subtitles = [
    'What this module does',
    'Which meal sessions do you run?',
    'How should students verify at the window?',
    'Share the scanner with canteen staff',
    'Setup complete — next steps'
];

function goStep(dir) {
    const newStep = currentStep + dir;
    if (newStep < 1 || newStep > totalSteps) return;

    // Save current step data before advancing
    if (dir > 0) saveStep(currentStep);

    // Update dots
    for (let i = 1; i <= totalSteps; i++) {
        const dot = document.getElementById('dot' + i);
        dot.className = 'step-dot' + (i < newStep ? ' done' : i === newStep ? ' active' : '');
    }

    // Show correct panel
    document.querySelectorAll('.step-panel').forEach(p => p.classList.remove('active'));
    document.getElementById('panel' + newStep).classList.add('active');

    document.getElementById('stepCounter').textContent = 'Step ' + newStep + ' of ' + totalSteps;
    document.getElementById('stepSubtitle').textContent = subtitles[newStep - 1];
    document.getElementById('btnBack').style.display = newStep > 1 ? '' : 'none';

    const btnNext = document.getElementById('btnNext');
    if (newStep === totalSteps) {
        btnNext.innerHTML = '<i class="fas fa-check me-1"></i>Finish';
        btnNext.onclick = finishSetup;
    } else {
        btnNext.innerHTML = 'Next <i class="fas fa-arrow-right ms-1"></i>';
        btnNext.onclick = () => goStep(1);
    }

    // Generate QR on step 4
    if (newStep === 4 && !document.querySelector('#step4Qr canvas')) {
        new QRCode(document.getElementById('step4Qr'), {
            text: document.getElementById('scannerUrl').value,
            width: 160, height: 160,
            colorDark: '#1e293b', colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.M
        });
    }

    currentStep = newStep;
}

function saveStep(step) {
    const data = { step };
    if (step === 3) {
        const qrCard = document.querySelector('[data-value="qr"]');
        const manCard = document.querySelector('[data-value="manual"]');
        data.qr_enabled = qrCard && qrCard.classList.contains('selected') ? 1 : 0;
        data.manual_fallback = manCard && manCard.classList.contains('selected') ? 1 : 0;
    }
    $.post('', data); // silent save — step data
}

function finishSetup() {
    $.post('', { step: 5 }, function(r) {
        if (r.success) window.location.href = r.redirect || 'setup.php';
    }, 'json');
}

function toggleMethod(card) {
    card.classList.toggle('selected');
    const cb = card.querySelector('input[type="checkbox"]');
    if (cb) cb.checked = card.classList.contains('selected');
}

function copyUrl() {
    const input = document.getElementById('scannerUrl');
    input.select();
    navigator.clipboard.writeText(input.value).then(() => {
        const btn = input.nextElementSibling;
        btn.innerHTML = '<i class="fas fa-check text-success"></i>';
        setTimeout(() => btn.innerHTML = '<i class="fas fa-copy"></i>', 1500);
    });
}
</script>
</body>
</html>
