<?php
// Filename: admin_classes.php
require 'config.php';
requireLogin();

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'timetable_coord', 'principal', 'assistant_hem', 'assistant']))) {
    header("Location: dashboard.php"); exit;
}

$msg = ''; $msg_type = '';

// 2. HANDLE ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    $name = trim($_POST['class_name']);
    $level = intval($_POST['form_level']);
    $floor = intval($_POST['floor_level'] ?? 0); // CORRECTED COLUMN NAME
    $teacher_id = !empty($_POST['class_teacher_id']) ? $_POST['class_teacher_id'] : null;

    if ($action === 'save') {
        $cid = $_POST['class_id'] ?? '';
        
        if ($cid) {
            // Update
            try {
                // FIXED: Changed class_floor -> floor_level
                $stmt = $pdo->prepare("UPDATE classes SET class_name=?, form_level=?, floor_level=?, class_teacher_id=? WHERE id=?");
                $stmt->execute([$name, $level, $floor, $teacher_id, $cid]);
                $msg = "Class updated successfully."; $msg_type = "success";
            } catch (Exception $e) { $msg = "Error updating: " . $e->getMessage(); $msg_type = "danger"; }
        } else {
            // Add New
            $qr_token = bin2hex(random_bytes(16));
            try {
                // FIXED: Changed class_floor -> floor_level
                $stmt = $pdo->prepare("INSERT INTO classes (class_name, form_level, floor_level, class_teacher_id, qr_token) VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$name, $level, $floor, $teacher_id, $qr_token]);
                $msg = "Class added successfully."; $msg_type = "success";
            } catch (Exception $e) { $msg = "Error adding: " . $e->getMessage(); $msg_type = "danger"; }
        }
    }
    elseif ($action === 'delete') {
        $cid = $_POST['class_id'];
        $check = $pdo->prepare("SELECT COUNT(*) FROM students WHERE class_id = ?");
        $check->execute([$cid]);
        if ($check->fetchColumn() > 0) {
            $msg = "Cannot delete: Class has students enrolled."; $msg_type = "danger";
        } else {
            $pdo->prepare("DELETE FROM classes WHERE id = ?")->execute([$cid]);
            $msg = "Class deleted."; $msg_type = "warning";
        }
    }
    elseif ($action === 'reset_qr') {
        $cid = $_POST['class_id'];
        $new_token = bin2hex(random_bytes(16));
        $pdo->prepare("UPDATE classes SET qr_token = ? WHERE id = ?")->execute([$new_token, $cid]);
        $msg = "QR Token refreshed."; $msg_type = "success";
    }
}

// 3. FETCH DATA
$sql = "SELECT c.*, u.full_name as teacher_name, 
        (SELECT COUNT(*) FROM students s WHERE s.class_id = c.id) as student_count 
        FROM classes c 
        LEFT JOIN users u ON c.class_teacher_id = u.id 
        ORDER BY c.form_level ASC, c.class_name ASC";
$classes = $pdo->query($sql)->fetchAll();

$teachers = $pdo->query("SELECT id, full_name FROM users WHERE role LIKE '%teacher%' ORDER BY full_name")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Classes</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css">

    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; ... }
		body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 90px; }

        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; text-align: center; }
        .floating-card { background: white; margin: -60px 20px 20px 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }

        .class-item { background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; border: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; transition: transform 0.2s; }
        .class-item:active { transform: scale(0.98); background: #f8fafc; }
        
        .level-badge { width: 45px; height: 45px; border-radius: 12px; background: #e0f2fe; color: #0284c7; font-weight: 800; font-size: 1.1rem; display: flex; flex-direction: column; align-items: center; justify-content: center; margin-right: 15px; line-height: 1; }
        .level-sub { font-size: 0.6rem; font-weight: 600; opacity: 0.7; text-transform: uppercase; }

        .teacher-badge { font-size: 0.75rem; background: #f3e8ff; color: #7c3aed; padding: 3px 8px; border-radius: 6px; font-weight: 600; }
        
        .form-control, .form-select { border-radius: 12px; padding: 10px; border: 1px solid #e2e8f0; background-color: #f8fafc; font-size: 0.9rem; }
        .form-control:focus, .form-select:focus { border-color: #8B5CF6; background: white; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1); }
        .form-label { font-size: 0.75rem; font-weight: 700; color: #64748b; margin-bottom: 4px; text-transform: uppercase; }

     /*   .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 18px 30px; display: flex; justify-content: space-between; border-radius: 30px 30px 0 0; box-shadow: 0 -5px 20px rgba(0,0,0,0.05); z-index: 100; }
        .nav-btn { display: flex; flex-direction: column; align-items: center; color: #94a3b8; text-decoration: none; font-size: 0.7rem; font-weight: 600; }
        .nav-btn.active { color: #8B5CF6; }
        .nav-btn i { font-size: 1.4rem; margin-bottom: 4px; } */
    </style>
</head>
<body>

    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="admin_dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Classes</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Academic Structure</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>

        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="fw-bold text-dark m-0">Total Classes: <?= count($classes) ?></h6>
            <button class="btn btn-sm btn-primary rounded-pill fw-bold px-3" onclick="openAdd()">
                <i class="bi bi-plus-lg me-1"></i> Add New
            </button>
        </div>

        <input type="text" id="searchInput" class="form-control mb-3 fw-bold" placeholder="Search class..." onkeyup="filterClasses()">
    </div>

    <div class="px-3 pb-4">
        <div id="classList">
            <?php foreach($classes as $c): ?>
            <div class="class-item" data-name="<?= strtolower($c['class_name']) ?>">
                <div class="d-flex align-items-center flex-grow-1" onclick='openEdit(<?= json_encode($c) ?>)' style="cursor:pointer;">
                    <div class="level-badge">
                        <?= $c['form_level'] ?>
                        <span class="level-sub">LVL <?= $c['floor_level'] ?? 'G' ?></span>
                    </div>
                    <div>
                        <div class="fw-bold text-dark"><?= htmlspecialchars($c['class_name']) ?></div>
                        <div class="d-flex align-items-center gap-2 mt-1">
                            <span class="teacher-badge text-truncate" style="max-width: 120px;">
                                <i class="bi bi-person-fill me-1"></i><?= htmlspecialchars($c['teacher_name'] ?? 'No Teacher') ?>
                            </span>
                            <span class="small text-muted fw-bold">
                                <i class="bi bi-people me-1"></i><?= $c['student_count'] ?>
                            </span>
                        </div>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn btn-light btn-sm rounded-circle text-muted" type="button" data-bs-toggle="dropdown">
                        <i class="bi bi-three-dots-vertical"></i>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end border-0 shadow rounded-4">
                        <li><a class="dropdown-item small fw-bold" href="#" onclick='openEdit(<?= json_encode($c) ?>)'><i class="bi bi-pencil me-2 text-primary"></i> Edit Details</a></li>
                        <li>
                            <form method="POST" onsubmit="return confirm('Refresh QR Token? Old codes will stop working.')">
                                <input type="hidden" name="action" value="reset_qr">
                                <input type="hidden" name="class_id" value="<?= $c['id'] ?>">
                                <button class="dropdown-item small fw-bold"><i class="bi bi-qr-code me-2 text-dark"></i> Reset QR</button>
                            </form>
                        </li>
                        <li><hr class="dropdown-divider"></li>
                        <li>
                            <form method="POST" onsubmit="return confirm('Delete this class?')">
                                <input type="hidden" name="action" value="delete">
                                <input type="hidden" name="class_id" value="<?= $c['id'] ?>">
                                <button class="dropdown-item small fw-bold text-danger"><i class="bi bi-trash me-2"></i> Delete</button>
                            </form>
                        </li>
                    </ul>
                </div>
            </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="modal fade" id="classModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold" id="modalTitle">Add Class</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="save">
                    <input type="hidden" name="class_id" id="inp_id">
                    
                    <div class="modal-body p-4">
                        <div class="row g-3">
                            <div class="col-8">
                                <label class="form-label text-muted">Class Name</label>
                                <input type="text" name="class_name" id="inp_name" class="form-control" placeholder="e.g. Cemerlang" required>
                            </div>
                            <div class="col-4">
                                <label class="form-label text-muted">Form</label>
                                <select name="form_level" id="inp_level" class="form-select text-center fw-bold">
                                    <?php for($i=1; $i<=6; $i++): ?><option value="<?=$i?>"><?=$i?></option><?php endfor; ?>
                                </select>
                            </div>
                            
                            <div class="col-12">
                                <label class="form-label text-muted">Location / Floor Level</label>
                                <div class="bg-light p-2 rounded-3 border d-flex gap-2 justify-content-center">
                                    <?php 
                                    $floors = [0=>'Ground', 1=>'Level 1', 2=>'Level 2', 3=>'Level 3', 4=>'Level 4'];
                                    foreach($floors as $val => $txt): ?>
                                    <div class="form-check form-check-inline m-0">
                                        <input class="form-check-input" type="radio" name="floor_level" id="fl_<?=$val?>" value="<?=$val?>" <?= $val==0?'checked':'' ?>>
                                        <label class="form-check-label small" for="fl_<?=$val?>"><?=$val==0?'G':$val?></label>
                                    </div>
                                    <?php endforeach; ?>
                                </div>
                                <div class="form-text small text-center mt-1">Used for Smart Relief (Mobility Check)</div>
                            </div>

                            <div class="col-12">
                                <label class="form-label text-muted">Class Teacher</label>
                                <select name="class_teacher_id" id="inp_teacher" class="form-select">
                                    <option value="">-- No Teacher Assigned --</option>
                                    <?php foreach($teachers as $t): ?>
                                        <option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['full_name']) ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer border-0 pt-0">
                        <button type="button" class="btn btn-light text-muted fw-bold rounded-pill" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" class="btn btn-primary fw-bold rounded-pill px-4 flex-grow-1">Save Class</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php include 'menu.php'; ?>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const modal = new bootstrap.Modal(document.getElementById('classModal'));

        function openAdd() {
            document.getElementById('modalTitle').innerText = "Add New Class";
            document.getElementById('inp_id').value = "";
            document.getElementById('inp_name').value = "";
            document.getElementById('inp_level').value = "1";
            document.getElementById('inp_teacher').value = "";
            // Default floor 0
            document.getElementById('fl_0').checked = true;
            modal.show();
        }

        function openEdit(c) {
            document.getElementById('modalTitle').innerText = "Edit Class";
            document.getElementById('inp_id').value = c.id;
            document.getElementById('inp_name').value = c.class_name;
            document.getElementById('inp_level').value = c.form_level;
            document.getElementById('inp_teacher').value = c.class_teacher_id || "";
            
            // Set Floor (Handle mismatch names from old DB vs new JS)
            const floor = c.floor_level || 0; 
            const floorRadio = document.getElementById('fl_' + floor);
            if(floorRadio) floorRadio.checked = true;

            modal.show();
        }

        function filterClasses() {
            const term = document.getElementById('searchInput').value.toLowerCase();
            const items = document.querySelectorAll('.class-item');
            items.forEach(item => {
                const name = item.getAttribute('data-name');
                if(name.includes(term)) item.style.display = 'flex';
                else item.style.display = 'none';
            });
        }
    </script>
</body>
</html>