<?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_check.php';
canteen_require_role(['admin', 'headteacher']);

$conn = getDBConnection();

// ── Data for page ─────────────────────────────────────────────────────────────
$classes = [];
$res = $conn->query("SELECT class_name FROM classes WHERE is_active = 1 ORDER BY class_name");
while ($row = $res->fetch_assoc()) $classes[] = $row['class_name'];

// Sessions this week (Mon–Sun)
$week_start = date('Y-m-d', strtotime('monday this week'));
$week_end   = date('Y-m-d', strtotime('sunday this week'));

$sess_stmt = $conn->prepare(
    "SELECT cs.*,
            COUNT(ce.id)                                      AS total_entitlements,
            SUM(ce.status = 'confirmed')                      AS confirmed_count
     FROM canteen_sessions cs
     LEFT JOIN canteen_entitlements ce ON ce.session_id = cs.id
     WHERE cs.school_id = 1 AND cs.session_date BETWEEN ? AND ?
     GROUP BY cs.id
     ORDER BY cs.session_date ASC, cs.start_time ASC"
);
$sess_stmt->bind_param('ss', $week_start, $week_end);
$sess_stmt->execute();
$sessions = $sess_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$sess_stmt->close();

$status_badge = [
    'scheduled' => 'bg-primary',
    'active'    => 'bg-success',
    'closed'    => 'bg-secondary',
    'cancelled' => 'bg-danger',
];
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Canteen Session Setup — 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">
    <link rel="stylesheet" href="../css/style.css">
    <style>
        .session-row td { vertical-align: middle; }
        .class-tags { display: flex; flex-wrap: wrap; gap: .25rem; }
        .class-tag { background: #e2e8f0; border-radius: 4px; padding: 1px 6px; font-size: .75rem; }
        .enrolled-bar { height: 6px; border-radius: 3px; background: #e2e8f0; overflow: hidden; }
        .enrolled-bar-fill { height: 100%; background: #22c55e; border-radius: 3px; }
        .quick-btn { font-size: .85rem; }
    </style>
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar">
        <?php echo buildSidebar('canteen/setup.php'); ?>
    </nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right">
                <div class="dropdown">
                    <button class="btn btn-link dropdown-toggle" type="button" data-bs-toggle="dropdown">
                        <i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="../settings.php"><i class="fas fa-cog me-2"></i>Settings</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i>Logout</a></li>
                    </ul>
                </div>
            </div>
        </header>
        <main class="content">
            <div class="content-header">
                <div class="d-flex justify-content-between align-items-center flex-wrap gap-2">
                    <div>
                        <h2 class="mb-0"><i class="fas fa-calendar-plus me-2"></i>Canteen Session Setup</h2>
                        <p class="text-muted small mb-0">Create and manage daily meal sessions</p>
                    </div>
                    <div class="d-flex gap-2 flex-wrap">
                        <!-- Quick actions -->
                        <button class="btn btn-success quick-btn" id="btn-quick-setup">
                            <i class="fas fa-bolt me-1"></i>Quick Setup Today
                        </button>
                        <button class="btn btn-outline-secondary quick-btn" id="btn-dup-yesterday">
                            <i class="fas fa-copy me-1"></i>Duplicate Yesterday
                        </button>
                        <button class="btn btn-outline-secondary quick-btn" id="btn-copy-week">
                            <i class="fas fa-calendar-week me-1"></i>Copy Last Week
                        </button>
                        <button class="btn btn-primary quick-btn" data-bs-toggle="modal" data-bs-target="#createSessionModal">
                            <i class="fas fa-plus me-1"></i>New Session
                        </button>
                    </div>
                </div>
            </div>

            <!-- Feedback alert -->
            <div id="setup-alert" class="d-none mb-3"></div>

            <!-- This week's sessions -->
            <div class="card">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="fas fa-calendar me-2"></i>This Week's Sessions
                        <span class="text-muted small fw-normal ms-2">
                            <?php echo date('d M', strtotime($week_start)); ?> –
                            <?php echo date('d M Y', strtotime($week_end)); ?>
                        </span>
                    </h5>
                    <span class="badge bg-secondary"><?php echo count($sessions); ?> session(s)</span>
                </div>
                <div class="card-body p-0">
                    <?php if (empty($sessions)): ?>
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-calendar-times fa-2x mb-2 d-block"></i>
                        No sessions this week yet.
                        <a href="#" data-bs-toggle="modal" data-bs-target="#createSessionModal">Create one</a>
                        or use <strong>Quick Setup Today</strong>.
                    </div>
                    <?php else: ?>
                    <div class="table-responsive">
                        <table class="table table-hover mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th>Session</th>
                                    <th>Date</th>
                                    <th>Time</th>
                                    <th>Classes</th>
                                    <th>Enrolled / Confirmed</th>
                                    <th>Status</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="sessions-tbody">
                            <?php foreach ($sessions as $s):
                                $enrolled   = (int)($s['total_enrolled'] ?: $s['total_entitlements'] ?: 0);
                                $confirmed  = (int)($s['confirmed_count'] ?? 0);
                                $pct        = $enrolled > 0 ? round($confirmed / $enrolled * 100) : 0;
                                $cls_list   = json_decode($s['classes_enrolled'] ?? '[]', true) ?: [];
                                $badge_cls  = $status_badge[$s['status']] ?? 'bg-secondary';
                            ?>
                            <tr class="session-row" data-id="<?php echo $s['id']; ?>">
                                <td><strong><?php echo htmlspecialchars($s['session_name']); ?></strong></td>
                                <td><?php echo date('D, d M', strtotime($s['session_date'])); ?></td>
                                <td class="text-muted small">
                                    <?php echo $s['start_time'] ? date('g:ia', strtotime($s['start_time'])) : '—'; ?>
                                    <?php echo $s['end_time']   ? '–' . date('g:ia', strtotime($s['end_time'])) : ''; ?>
                                </td>
                                <td>
                                    <div class="class-tags">
                                        <?php foreach ($cls_list as $c): ?>
                                        <span class="class-tag"><?php echo htmlspecialchars($c); ?></span>
                                        <?php endforeach; ?>
                                    </div>
                                </td>
                                <td style="min-width:120px;">
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="small"><?php echo $confirmed; ?>/<?php echo $enrolled; ?></span>
                                        <div class="enrolled-bar flex-grow-1">
                                            <div class="enrolled-bar-fill" style="width:<?php echo $pct; ?>%"></div>
                                        </div>
                                        <span class="small text-muted"><?php echo $pct; ?>%</span>
                                    </div>
                                </td>
                                <td>
                                    <span class="badge <?php echo $badge_cls; ?>">
                                        <?php echo ucfirst($s['status']); ?>
                                    </span>
                                </td>
                                <td>
                                    <div class="dropdown">
                                        <button class="btn btn-sm btn-outline-secondary dropdown-toggle"
                                                data-bs-toggle="dropdown">Actions</button>
                                        <ul class="dropdown-menu dropdown-menu-end">
                                            <li><button class="dropdown-item btn-status"
                                                data-id="<?php echo $s['id']; ?>" data-status="active">
                                                <i class="fas fa-play text-success me-2"></i>Set Active</button></li>
                                            <li><button class="dropdown-item btn-status"
                                                data-id="<?php echo $s['id']; ?>" data-status="closed">
                                                <i class="fas fa-stop text-secondary me-2"></i>Close</button></li>
                                            <li><hr class="dropdown-divider"></li>
                                            <li><button class="dropdown-item btn-status text-danger"
                                                data-id="<?php echo $s['id']; ?>" data-status="cancelled">
                                                <i class="fas fa-ban me-2"></i>Cancel</button></li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                    <?php endif; ?>
                </div>
            </div>

        </main>
    </div>
</div>

<!-- ── Create Session Modal ───────────────────────────────────────────────── -->
<div class="modal fade" id="createSessionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title"><i class="fas fa-plus me-2"></i>New Canteen Session</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label class="form-label fw-semibold">Session Name *</label>
                    <div class="d-flex gap-2 mb-2">
                        <button type="button" class="btn btn-sm btn-outline-secondary preset-name" data-name="Breakfast">Breakfast</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary preset-name" data-name="Lunch">Lunch</button>
                        <button type="button" class="btn btn-sm btn-outline-secondary preset-name" data-name="Supper">Supper</button>
                    </div>
                    <input type="text" id="f-session-name" class="form-control" placeholder="Or type custom name" required>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-12">
                        <label class="form-label fw-semibold">Date *</label>
                        <input type="date" id="f-session-date" class="form-control"
                               value="<?php echo date('Y-m-d'); ?>" required>
                    </div>
                </div>
                <div class="row g-2 mb-3">
                    <div class="col-6">
                        <label class="form-label">Start Time</label>
                        <input type="time" id="f-start-time" class="form-control">
                    </div>
                    <div class="col-6">
                        <label class="form-label">End Time</label>
                        <input type="time" id="f-end-time" class="form-control">
                    </div>
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold">Price per Meal (GHS)</label>
                    <input type="number" id="f-price" class="form-control" value="0" min="0" step="0.01">
                </div>
                <div class="mb-3">
                    <label class="form-label fw-semibold">Classes *</label>
                    <div class="d-flex justify-content-between mb-1">
                        <span class="text-muted small">Select classes enrolled in this session</span>
                        <button type="button" class="btn btn-link btn-sm p-0" id="btn-select-all-classes">Select All</button>
                    </div>
                    <div class="border rounded p-2" style="max-height:160px;overflow-y:auto;" id="classes-checklist">
                        <?php foreach ($classes as $cls): ?>
                        <div class="form-check">
                            <input class="form-check-input class-checkbox" type="checkbox"
                                   value="<?php echo htmlspecialchars($cls); ?>"
                                   id="cls-<?php echo htmlspecialchars($cls); ?>" checked>
                            <label class="form-check-label" for="cls-<?php echo htmlspecialchars($cls); ?>">
                                <?php echo htmlspecialchars($cls); ?>
                            </label>
                        </div>
                        <?php endforeach; ?>
                        <?php if (empty($classes)): ?>
                        <p class="text-muted small mb-0">No active classes found.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" id="btn-create-session">
                    <i class="fas fa-save me-1"></i>Create Session
                </button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
'use strict';
(function () {

function showAlert(msg, type) {
    var el = document.getElementById('setup-alert');
    el.className = 'alert alert-' + type + ' alert-dismissible fade show';
    el.innerHTML = msg + '<button type="button" class="btn-close" data-bs-dismiss="alert"></button>';
    el.classList.remove('d-none');
    el.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}

function post(action, extra) {
    var fd = new FormData();
    fd.append('action', action);
    if (extra) Object.entries(extra).forEach(([k, v]) => fd.append(k, v));
    return fetch('../ajax/canteen_setup_save.php', {
        method: 'POST', credentials: 'same-origin', body: fd
    }).then(r => r.json());
}

// ── Preset name buttons ────────────────────────────────────────────────────
document.querySelectorAll('.preset-name').forEach(btn => {
    btn.addEventListener('click', () => {
        document.getElementById('f-session-name').value = btn.dataset.name;
        // Auto-fill times
        const times = { Breakfast: ['07:00','08:00'], Lunch: ['12:00','13:00'], Supper: ['17:00','18:00'] };
        const t = times[btn.dataset.name];
        if (t) {
            document.getElementById('f-start-time').value = t[0];
            document.getElementById('f-end-time').value   = t[1];
        }
    });
});

// ── Select all classes ─────────────────────────────────────────────────────
document.getElementById('btn-select-all-classes').addEventListener('click', () => {
    document.querySelectorAll('.class-checkbox').forEach(cb => cb.checked = true);
});

// ── Create session ─────────────────────────────────────────────────────────
document.getElementById('btn-create-session').addEventListener('click', function () {
    var name  = document.getElementById('f-session-name').value.trim();
    var date  = document.getElementById('f-session-date').value;
    var start = document.getElementById('f-start-time').value;
    var end   = document.getElementById('f-end-time').value;
    var price = document.getElementById('f-price').value;
    var classes = Array.from(document.querySelectorAll('.class-checkbox:checked')).map(cb => cb.value);

    if (!name || !date || classes.length === 0) {
        showAlert('<i class="fas fa-exclamation-triangle me-2"></i>Session name, date and at least one class are required.', 'warning');
        return;
    }

    this.disabled = true;
    this.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Creating…';

    var fd = new FormData();
    fd.append('action', 'create_session');
    fd.append('session_name', name);
    fd.append('session_date', date);
    fd.append('start_time', start);
    fd.append('end_time', end);
    fd.append('price', price);
    classes.forEach(c => fd.append('classes[]', c));

    fetch('../ajax/canteen_setup_save.php', { method:'POST', credentials:'same-origin', body:fd })
        .then(r => r.json())
        .then(data => {
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-save me-1"></i>Create Session';
            if (data.success) {
                bootstrap.Modal.getInstance(document.getElementById('createSessionModal')).hide();
                showAlert('<i class="fas fa-check-circle me-2"></i>' + data.message, 'success');
                setTimeout(() => location.reload(), 1500);
            } else {
                showAlert('<i class="fas fa-times-circle me-2"></i>' + data.message, 'danger');
            }
        })
        .catch(() => {
            this.disabled = false;
            this.innerHTML = '<i class="fas fa-save me-1"></i>Create Session';
            showAlert('Network error — please try again.', 'danger');
        });
});

// ── Quick setup ────────────────────────────────────────────────────────────
document.getElementById('btn-quick-setup').addEventListener('click', function () {
    if (!confirm('Create Breakfast + Lunch sessions for today for all active classes?')) return;
    this.disabled = true;
    post('quick_setup').then(data => {
        this.disabled = false;
        showAlert((data.success ? '<i class="fas fa-check-circle me-2"></i>' : '<i class="fas fa-exclamation-triangle me-2"></i>') + data.message,
            data.success ? 'success' : 'warning');
        if (data.success && data.created > 0) setTimeout(() => location.reload(), 1500);
    }).catch(() => { this.disabled = false; });
});

// ── Duplicate yesterday ────────────────────────────────────────────────────
document.getElementById('btn-dup-yesterday').addEventListener('click', function () {
    this.disabled = true;
    post('duplicate_yesterday').then(data => {
        this.disabled = false;
        showAlert((data.success ? '<i class="fas fa-check-circle me-2"></i>' : '<i class="fas fa-exclamation-triangle me-2"></i>') + data.message,
            data.success ? 'success' : 'warning');
        if (data.success && data.created > 0) setTimeout(() => location.reload(), 1500);
    }).catch(() => { this.disabled = false; });
});

// ── Copy last week ─────────────────────────────────────────────────────────
document.getElementById('btn-copy-week').addEventListener('click', function () {
    this.disabled = true;
    post('copy_last_week').then(data => {
        this.disabled = false;
        showAlert((data.success ? '<i class="fas fa-check-circle me-2"></i>' : '<i class="fas fa-exclamation-triangle me-2"></i>') + data.message,
            data.success ? 'success' : 'warning');
        if (data.success && data.created > 0) setTimeout(() => location.reload(), 1500);
    }).catch(() => { this.disabled = false; });
});

// ── Status change ──────────────────────────────────────────────────────────
document.querySelectorAll('.btn-status').forEach(btn => {
    btn.addEventListener('click', function () {
        var id     = this.dataset.id;
        var status = this.dataset.status;
        post('update_status', { session_id: id, status: status }).then(data => {
            showAlert((data.success ? '<i class="fas fa-check-circle me-2"></i>' : '<i class="fas fa-times-circle me-2"></i>') + data.message,
                data.success ? 'success' : 'danger');
            if (data.success) setTimeout(() => location.reload(), 1200);
        });
    });
});

})();
</script>
</body>
</html>
