<?php
/**
 * Canteen Cook Dashboard — PIN-only access, no EduTrack login required.
 * Auto-refreshes every cook_dashboard_refresh_seconds seconds.
 */
if (session_status() === PHP_SESSION_NONE) session_start();
require_once '../config.php';
require_once '../includes/canteen_helpers.php';

canteen_require_active();

$is_cook = !empty($_SESSION['canteen_cook_authenticated']);
$is_role = !empty($_SESSION['user_id']);

// ── PIN authentication ────────────────────────────────────────────────────────
$pin_error = '';
if (!$is_cook && !$is_role) {
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['cook_pin'])) {
        $pin      = trim((string)$_POST['cook_pin']);
        $conn_tmp = getDBConnection();
        $settings = canteen_get_settings();
        $hash     = $settings['cook_pin_hash'] ?? '';

        if ($hash === '' || $hash === null) {
            $pin_error = 'No PIN configured. Ask an administrator to set one in Canteen → Settings.';
        } elseif (!preg_match('/^\d{4,8}$/', $pin) || !password_verify($pin, $hash)) {
            $pin_error = 'Incorrect PIN. Try again.';
            logActivity($conn_tmp, 0, 'canteen_cook_pin_fail',
                'Failed cook dashboard PIN from ' . ($_SERVER['REMOTE_ADDR'] ?? ''));
        } else {
            $_SESSION['canteen_cook_authenticated'] = true;
            $_SESSION['canteen_cook_auth_time']     = time();
            $is_cook = true;
        }
        $conn_tmp->close();
    }
}

// ── Cook session expiry (12 hours) ────────────────────────────────────────────
if ($is_cook && isset($_SESSION['canteen_cook_auth_time'])) {
    if (time() - $_SESSION['canteen_cook_auth_time'] > 43200) {
        unset($_SESSION['canteen_cook_authenticated'], $_SESSION['canteen_cook_auth_time']);
        $is_cook = false;
    }
}

// ── Logout ────────────────────────────────────────────────────────────────────
if (isset($_GET['logout'])) {
    unset($_SESSION['canteen_cook_authenticated'], $_SESSION['canteen_cook_auth_time']);
    header('Location: cook_dashboard.php');
    exit;
}

$settings        = canteen_get_settings();
$refresh_seconds = (int)($settings['cook_dashboard_refresh_seconds'] ?? 30);
if ($refresh_seconds < 10) $refresh_seconds = 30;

$school_name = defined('SCHOOL_NAME') ? SCHOOL_NAME : 'School Canteen';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="theme-color" content="#14532d">
    <title>Cook Dashboard — <?= htmlspecialchars($school_name) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <style>
        *, *::before, *::after { box-sizing: border-box; }
        body {
            background: #0d1117; color: #e6edf3;
            font-family: 'Segoe UI', sans-serif;
            min-height: 100dvh;
        }

        /* ── PIN Gate ─────────────────────────────────────────────────────────── */
        .pin-wrap {
            min-height: 100dvh; display: flex;
            align-items: center; justify-content: center; padding: 1.5rem;
        }
        .pin-card {
            background: #161b22; border-radius: 20px;
            padding: 2.5rem 2rem; max-width: 380px; width: 100%;
            box-shadow: 0 20px 60px rgba(0,0,0,.5); text-align: center;
        }
        .pin-icon {
            width: 80px; height: 80px; border-radius: 50%; margin: 0 auto 1.5rem;
            background: linear-gradient(135deg, #16a34a, #14532d);
            display: flex; align-items: center; justify-content: center;
            font-size: 2rem; color: #fff;
        }
        .pin-input {
            letter-spacing: .5em; font-size: 2rem; font-weight: 700;
            text-align: center; background: rgba(255,255,255,.08);
            border: 2px solid rgba(255,255,255,.15); border-radius: 12px;
            color: #fff; padding: .75rem; width: 100%; margin-bottom: 1rem;
        }
        .pin-input:focus { outline: none; border-color: #16a34a; }
        .btn-unlock {
            background: linear-gradient(135deg, #16a34a, #14532d);
            border: none; color: #fff; padding: .85rem 2rem;
            font-size: 1.1rem; font-weight: 600; border-radius: 12px; width: 100%;
        }
        .numpad { display: grid; grid-template-columns: repeat(3,1fr); gap: .75rem; margin-top: 1.5rem; }
        .numpad-btn {
            background: rgba(255,255,255,.07); border: none; border-radius: 12px;
            padding: 1rem; font-size: 1.4rem; font-weight: 600; color: #e6edf3;
            cursor: pointer; transition: background .15s;
        }
        .numpad-btn:hover, .numpad-btn:active { background: rgba(22,163,74,.25); }
        .numpad-btn.del { font-size: 1rem; color: #f87171; }

        /* ── Dashboard ───────────────────────────────────────────────────────── */
        .dash-header {
            background: #161b22; border-bottom: 1px solid rgba(255,255,255,.08);
            padding: .75rem 1.25rem; display: flex; align-items: center; gap: .75rem;
            position: sticky; top: 0; z-index: 50;
        }
        .dash-header .school { font-weight: 700; font-size: 1rem; flex: 1; }
        .dash-header .refresh-timer { font-size: .75rem; color: #8b949e; }
        .dash-header a { color: #8b949e; font-size: .85rem; text-decoration: none; }

        .dash-body { padding: 1rem; max-width: 960px; margin: 0 auto; }

        .session-tabs { display: flex; gap: .5rem; margin-bottom: 1rem; overflow-x: auto; }
        .session-tab {
            background: rgba(255,255,255,.07); border: 1px solid rgba(255,255,255,.1);
            border-radius: 20px; padding: .4rem 1rem; font-size: .85rem;
            cursor: pointer; white-space: nowrap; transition: all .15s;
        }
        .session-tab.active { background: #16a34a; border-color: #16a34a; color: #fff; }

        /* Big number */
        .big-card {
            background: #161b22; border-radius: 16px; padding: 1.5rem;
            margin-bottom: 1rem; border: 1px solid rgba(255,255,255,.07);
        }
        .big-number {
            font-size: 5rem; font-weight: 800; line-height: 1;
            background: linear-gradient(135deg, #16a34a, #4ade80);
            -webkit-background-clip: text; -webkit-text-fill-color: transparent;
        }
        .big-label { font-size: 1rem; color: #8b949e; margin-top: .25rem; }
        .progress-outer {
            height: 14px; background: rgba(255,255,255,.1); border-radius: 7px;
            margin: 1rem 0 .5rem; overflow: hidden;
        }
        .progress-inner {
            height: 100%; border-radius: 7px;
            background: linear-gradient(90deg, #16a34a, #4ade80);
            transition: width .6s ease;
        }
        .projected-line { font-size: .85rem; color: #8b949e; }

        /* Class table */
        .class-table { width: 100%; border-collapse: separate; border-spacing: 0 4px; }
        .class-table th {
            font-size: .75rem; text-transform: uppercase; letter-spacing: .05em;
            color: #8b949e; padding: .5rem .75rem; text-align: left;
        }
        .class-table td { padding: .6rem .75rem; background: #161b22; font-size: .9rem; }
        .class-table tr td:first-child { border-radius: 8px 0 0 8px; }
        .class-table tr td:last-child { border-radius: 0 8px 8px 0; }
        .row-success td { background: rgba(22,163,74,.15); }
        .row-warning td { background: rgba(234,179,8,.1); }
        .row-danger td  { background: rgba(239,68,68,.12); }
        .pct-pill {
            display: inline-block; padding: 2px 8px; border-radius: 20px; font-size: .75rem; font-weight: 600;
        }
        .pill-success { background: rgba(22,163,74,.25); color: #4ade80; }
        .pill-warning { background: rgba(234,179,8,.2); color: #fbbf24; }
        .pill-danger  { background: rgba(239,68,68,.2);  color: #f87171; }

        /* Arrival rate bars */
        .interval-chart { display: flex; align-items: flex-end; gap: 4px; height: 80px; margin-top: .5rem; }
        .interval-bar {
            flex: 1; background: rgba(22,163,74,.5); border-radius: 3px 3px 0 0;
            position: relative; min-height: 4px; transition: height .4s ease;
        }
        .interval-bar:hover { background: #16a34a; }
        .interval-bar .bar-label {
            position: absolute; bottom: -20px; left: 50%; transform: translateX(-50%);
            font-size: .6rem; color: #8b949e; white-space: nowrap;
        }
        .interval-bar .bar-count {
            position: absolute; top: -18px; left: 50%; transform: translateX(-50%);
            font-size: .65rem; color: #4ade80; white-space: nowrap;
        }
        .interval-wrap { margin-bottom: 28px; }

        .section-title {
            font-size: .7rem; text-transform: uppercase; letter-spacing: .1em;
            color: #8b949e; margin-bottom: .75rem; font-weight: 600;
        }

        .last-updated { font-size: .72rem; color: #484f58; text-align: right; margin-top: 1rem; }
    </style>
</head>
<body>

<?php if (!$is_cook && !$is_role): ?>
<!-- ── PIN Gate ──────────────────────────────────────────────────────────────── -->
<div class="pin-wrap">
    <div class="pin-card">
        <div class="pin-icon"><i class="fas fa-utensils"></i></div>
        <h4 class="fw-bold mb-1">Cook Dashboard</h4>
        <p style="color:#8b949e;font-size:.9rem;margin-bottom:1.5rem">
            <?= htmlspecialchars($school_name) ?>
        </p>

        <?php if ($pin_error): ?>
        <div class="alert alert-danger py-2 mb-3 text-start" style="background:rgba(239,68,68,.15);border-color:rgba(239,68,68,.3);color:#f87171;border-radius:10px">
            <?= htmlspecialchars($pin_error) ?>
        </div>
        <?php endif; ?>

        <form method="post" id="pinForm" autocomplete="off">
            <input type="password" name="cook_pin" id="pinInput" class="pin-input"
                   maxlength="8" inputmode="numeric" pattern="\d{4,8}"
                   placeholder="• • • •" required>
            <button type="submit" class="btn-unlock">
                <i class="fas fa-unlock me-2"></i>Enter Dashboard
            </button>
        </form>

        <div class="numpad">
            <?php for ($d = 1; $d <= 9; $d++): ?>
            <button type="button" class="numpad-btn" data-digit="<?= $d ?>"><?= $d ?></button>
            <?php endfor; ?>
            <button type="button" class="numpad-btn del" data-action="clear">CLR</button>
            <button type="button" class="numpad-btn" data-digit="0">0</button>
            <button type="button" class="numpad-btn del" data-action="del"><i class="fas fa-backspace"></i></button>
        </div>

        <?php if ($is_role): ?>
        <p class="mt-3 mb-0" style="color:#8b949e;font-size:.8rem">
            <a href="../dashboard.php" style="color:#4ade80">Back to EduTrack</a>
        </p>
        <?php endif; ?>
    </div>
</div>

<script>
(function(){
    const input = document.getElementById('pinInput');
    document.querySelector('.numpad').addEventListener('click', function(e){
        const btn = e.target.closest('[data-digit],[data-action]');
        if (!btn) return;
        if (btn.dataset.digit !== undefined && input.value.length < 8)
            input.value += btn.dataset.digit;
        else if (btn.dataset.action === 'del')
            input.value = input.value.slice(0,-1);
        else if (btn.dataset.action === 'clear')
            input.value = '';
        if (input.value.length >= 4 && /^\d+$/.test(input.value))
            setTimeout(() => document.getElementById('pinForm').submit(), 300);
    });
})();
</script>
</body>
</html>
<?php exit; ?>
<?php endif; ?>

<!-- ── Dashboard ──────────────────────────────────────────────────────────────── -->
<div class="dash-header">
    <i class="fas fa-utensils text-success"></i>
    <div class="school"><?= htmlspecialchars($school_name) ?> — Cook Dashboard</div>
    <div class="refresh-timer" id="refreshTimer">Refreshing in <span id="countdown"><?= $refresh_seconds ?></span>s</div>
    <?php if ($is_role): ?>
    <a href="../dashboard.php"><i class="fas fa-arrow-left me-1"></i>EduTrack</a>
    <?php else: ?>
    <a href="?logout=1"><i class="fas fa-lock me-1"></i>Lock</a>
    <?php endif; ?>
</div>

<div class="dash-body">
    <!-- Session tabs -->
    <div class="session-tabs" id="sessionTabs"></div>

    <!-- Big number card -->
    <div class="big-card" id="bigCard">
        <div style="display:flex;align-items:flex-end;gap:1rem;flex-wrap:wrap">
            <div>
                <div class="big-number" id="bigNumber">—</div>
                <div class="big-label" id="bigLabel">Loading…</div>
            </div>
            <div style="flex:1;min-width:160px">
                <div class="progress-outer">
                    <div class="progress-inner" id="progressBar" style="width:0%"></div>
                </div>
                <div class="projected-line" id="projectedLine"></div>
            </div>
        </div>
    </div>

    <!-- Per-class table -->
    <div class="big-card">
        <div class="section-title">Per-Class Breakdown</div>
        <div style="overflow-x:auto">
            <table class="class-table" id="classTable">
                <thead>
                    <tr>
                        <th>Class</th>
                        <th>Enrolled</th>
                        <th>Confirmed</th>
                        <th>Expected</th>
                        <th>% Done</th>
                    </tr>
                </thead>
                <tbody id="classTableBody">
                    <tr><td colspan="5" style="text-align:center;color:#8b949e;padding:2rem">Loading…</td></tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- Arrival rate chart -->
    <div class="big-card">
        <div class="section-title">Arrival Rate (15-min intervals)</div>
        <div class="interval-wrap">
            <div class="interval-chart" id="intervalChart">
                <div style="color:#8b949e;font-size:.85rem;width:100%;text-align:center;padding:1rem">
                    No scan data yet
                </div>
            </div>
        </div>
    </div>

    <div class="last-updated" id="lastUpdated"></div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/js/bootstrap.bundle.min.js"></script>
<script>
(function(){
    'use strict';

    const STATS_URL      = '../ajax/canteen_dashboard_stats.php';
    const REFRESH_SECS   = <?= (int)$refresh_seconds ?>;

    let sessions         = [];
    let activeSessionIdx = 0;
    let countdown        = REFRESH_SECS;
    let countdownInterval;

    // ── Fetch stats ─────────────────────────────────────────────────────────────
    function fetchStats() {
        fetch(STATS_URL, { credentials: 'same-origin' })
            .then(r => r.json())
            .then(data => {
                if (!data.success) return;
                sessions = data.sessions || [];
                renderTabs();
                renderSession();
                document.getElementById('lastUpdated').textContent =
                    'Last updated: ' + data.generated;
                resetCountdown();
            })
            .catch(err => console.warn('[CookDash]', err));
    }

    // ── Tabs ─────────────────────────────────────────────────────────────────────
    function renderTabs() {
        const tabs = document.getElementById('sessionTabs');
        if (!tabs) return;
        tabs.innerHTML = '';
        if (sessions.length === 0) {
            tabs.innerHTML = '<span style="color:#8b949e;font-size:.85rem;padding:.4rem">No sessions today</span>';
            return;
        }
        sessions.forEach(function(s, i) {
            const btn = document.createElement('button');
            btn.className = 'session-tab' + (i === activeSessionIdx ? ' active' : '');
            btn.textContent = s.session_name + ' ' + s.start_time + '–' + s.end_time;
            btn.dataset.idx = i;
            btn.addEventListener('click', function() {
                activeSessionIdx = parseInt(this.dataset.idx, 10);
                document.querySelectorAll('.session-tab').forEach(function(t, j) {
                    t.classList.toggle('active', j === activeSessionIdx);
                });
                renderSession();
            });
            tabs.appendChild(btn);
        });
    }

    // ── Session detail ────────────────────────────────────────────────────────────
    function renderSession() {
        if (!sessions.length) { renderEmpty(); return; }
        const s = sessions[Math.min(activeSessionIdx, sessions.length - 1)];
        if (!s) return;

        // Big number
        document.getElementById('bigNumber').textContent = s.confirmed;
        document.getElementById('bigLabel').textContent  =
            'confirmed  of ' + s.enrolled + ' enrolled';
        document.getElementById('progressBar').style.width = s.pct + '%';
        document.getElementById('projectedLine').textContent =
            'Projected total by end of session: ' + s.projected +
            ' · Session ' + s.elapsed_pct + '% elapsed';

        // Class table
        const tbody = document.getElementById('classTableBody');
        if (!s.classes || s.classes.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center;color:#8b949e">No class data</td></tr>';
        } else {
            tbody.innerHTML = s.classes.map(function(c) {
                const pillClass = c.pct >= 80 ? 'pill-success' : (c.pct >= 40 ? 'pill-warning' : 'pill-danger');
                return '<tr class="row-' + c.row_class + '">' +
                    '<td><strong>' + esc(c.class_name) + '</strong></td>' +
                    '<td>' + c.enrolled + '</td>' +
                    '<td>' + c.confirmed + '</td>' +
                    '<td>' + c.expected + '</td>' +
                    '<td><span class="pct-pill ' + pillClass + '">' + c.pct + '%</span></td>' +
                    '</tr>';
            }).join('');
        }

        // Interval chart
        renderIntervals(s.intervals, s.max_slot_count);
    }

    function renderEmpty() {
        document.getElementById('bigNumber').textContent  = '—';
        document.getElementById('bigLabel').textContent   = 'No sessions today';
        document.getElementById('progressBar').style.width = '0%';
        document.getElementById('projectedLine').textContent = '';
        document.getElementById('classTableBody').innerHTML =
            '<tr><td colspan="5" style="text-align:center;color:#8b949e;padding:2rem">No sessions scheduled</td></tr>';
        document.getElementById('intervalChart').innerHTML =
            '<div style="color:#8b949e;font-size:.85rem;width:100%;text-align:center;padding:1rem">No data</div>';
    }

    function renderIntervals(intervals, maxCount) {
        const chart = document.getElementById('intervalChart');
        if (!intervals || intervals.length === 0) {
            chart.innerHTML = '<div style="color:#8b949e;font-size:.85rem;width:100%;text-align:center;padding:1rem">No scans yet in this session</div>';
            return;
        }
        const chartHeight = 80;
        chart.innerHTML = intervals.map(function(iv) {
            const barH = Math.max(4, Math.round((iv.count / maxCount) * chartHeight));
            return '<div class="interval-bar" style="height:' + barH + 'px" title="' + iv.label + ': ' + iv.count + '">' +
                '<span class="bar-count">' + iv.count + '</span>' +
                '<span class="bar-label">' + iv.label + '</span>' +
                '</div>';
        }).join('');
    }

    function esc(s) {
        return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
    }

    // ── Countdown ─────────────────────────────────────────────────────────────────
    function resetCountdown() {
        countdown = REFRESH_SECS;
        clearInterval(countdownInterval);
        countdownInterval = setInterval(function() {
            countdown--;
            const el = document.getElementById('countdown');
            if (el) el.textContent = countdown;
            if (countdown <= 0) { clearInterval(countdownInterval); fetchStats(); }
        }, 1000);
    }

    // ── Boot ──────────────────────────────────────────────────────────────────────
    fetchStats();
})();
</script>
</body>
</html>
