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

$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$is_privileged = !empty(array_intersect($user_roles, ['admin', 'principal', 'assistant', 'timetable_coord']));

$sys_mode = getSetting('system_mode', 'live'); 
$reason_list_raw = getSetting('student_absence_reasons', 'Sick,Family Matter,Late,Truancy,Other');
$infraction_list_raw = getSetting('infraction_list', 'Disruptive Behavior,Late,Truancy,Improper Uniform,Fighting,Vandalism,Other');

$reason_list = array_map('trim', explode(',', $reason_list_raw));
$infractions = array_map('trim', explode(',', $infraction_list_raw));

/**
 * --- STAGE 1: SESSION SELECTION ---
 * If no timetable_id is provided, show the search/selection interface.
 */
if (!isset($_GET['timetable_id'])) {
    if ($sys_mode !== 'manual' && !$is_privileged) {
        die("<!DOCTYPE html><html lang='en'><body class='bg-light d-flex align-items-center justify-content-center vh-100'><div class='text-center'><h3>Access Denied</h3><p><a href='dashboard.php'>Back to Dashboard</a></p></div></body></html>");
    }

    $today = date('Y-m-d');
    $day_num = date('N', strtotime($today));
    $now = date('H:i:s');
    $selected_date = $_GET['date'] ?? $today;
    $selected_class = $_GET['class_id'] ?? '';
    
    $classes = $pdo->query("SELECT id, class_name FROM classes ORDER BY form_level, class_name")->fetchAll();
    $slots = [];
    if ($selected_class) {
        $sel_day = date('N', strtotime($selected_date));
        $stmt = $pdo->prepare("SELECT t.*, u.full_name as teacher_name, (SELECT COUNT(*) FROM student_attendance sa WHERE sa.timetable_id = t.id AND sa.date = ?) as record_count FROM timetable t LEFT JOIN users u ON t.teacher_id = u.id WHERE t.class_id = ? AND t.day_of_week = ? ORDER BY t.start_time ASC");
        $stmt->execute([$selected_date, $selected_class, $sel_day]);
        $slots = $stmt->fetchAll();
    }

    $active_classes = [];
    if ($sys_mode === 'manual' && empty($selected_class)) {
        $stmt = $pdo->prepare("SELECT t.id, t.subject, t.start_time, t.end_time, c.class_name, u.full_name as teacher_name FROM timetable t JOIN classes c ON t.class_id = c.id JOIN users u ON t.teacher_id = u.id WHERE t.day_of_week = ? AND ? BETWEEN t.start_time AND t.end_time ORDER BY c.class_name");
        $stmt->execute([$day_num, $now]);
        $active_classes = $stmt->fetchAll();
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Find Session</title>
    <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() ?>; --bg-color: #f8f9fd; }
        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; }
        .slot-item { display: flex; align-items: center; padding: 15px; background: white; border-radius: 16px; margin-bottom: 10px; border: 1px solid #f1f5f9; text-decoration: none; color: #333; transition: 0.2s; }
        .status-dot { width: 10px; height: 10px; border-radius: 50%; display: inline-block; margin-right: 5px; }
        .bg-success { background-color: #10b981 !important; }
        .bg-warning { background-color: #f59e0b !important; }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Attendance Manager</div>
            <div style="width: 24px;"></div>
        </div>
    </div>
    <div class="floating-card">
        <form method="GET">
            <div class="mb-3">
                <label class="form-label small fw-bold text-muted text-uppercase">Select Date</label>
                <input type="date" name="date" class="form-control rounded-4 border-0 bg-light fw-bold" value="<?= htmlspecialchars($selected_date) ?>" onchange="this.form.submit()">
            </div>
            <div class="mb-1">
                <label class="form-label small fw-bold text-muted text-uppercase">Select Class</label>
                <select name="class_id" class="form-select rounded-4 border-0 bg-light fw-bold" onchange="this.form.submit()">
                    <option value="">Choose Class...</option>
                    <?php foreach($classes as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= $selected_class == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['class_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </form>
    </div>
    <div class="px-3">
        <?php if(!empty($slots)): ?>
            <?php foreach($slots as $s): $is_rec = $s['record_count'] > 0; $color = $is_rec ? 'bg-success' : 'bg-warning'; ?>
                <a href="?timetable_id=<?= $s['id'] ?>" class="slot-item">
                    <div class="me-3 text-center" style="min-width: 50px;">
                        <div class="fw-bold text-dark lh-1"><?= substr($s['start_time'],0,5) ?></div>
                        <div class="small text-muted" style="font-size:0.65rem;">START</div>
                    </div>
                    <div class="flex-grow-1 border-start ps-3">
                        <div class="fw-bold text-dark"><?= htmlspecialchars($s['subject']) ?></div>
                        <div class="small text-muted"><?= htmlspecialchars($s['teacher_name']) ?></div>
                    </div>
                    <div><span class="status-dot <?= $color ?>"></span></div>
                </a>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    <?php include 'menu.php'; ?>
</body>
</html>
<?php exit; } 

/**
 * --- STAGE 2: ACTIVE SESSION (ATTENDANCE & DISCIPLINE) ---
 */
$tid = $_GET['timetable_id'];
$date = date('Y-m-d'); 
$msg = ''; $msg_type = '';

$stmt = $pdo->prepare("SELECT t.*, c.class_name, c.id as class_id, c.class_teacher_id, u.full_name as teacher_name, s.id as subject_id, s.type as subject_type FROM timetable t JOIN classes c ON t.class_id = c.id LEFT JOIN users u ON t.teacher_id = u.id LEFT JOIN subjects s ON t.subject = s.subject_name WHERE t.id = ?");
$stmt->execute([$tid]);
$slot = $stmt->fetch();
if (!$slot) die("Slot not found.");

// Fetch Students
if ($slot['subject_type'] === 'elective' && $slot['subject_id']) {
    $stmt = $pdo->prepare("SELECT s.id, s.full_name, (SELECT status FROM student_attendance sa WHERE sa.student_id = s.id AND sa.timetable_id = ? AND sa.date = ? LIMIT 1) as local_status, (SELECT reason FROM student_attendance sa WHERE sa.student_id = s.id AND sa.timetable_id = ? AND sa.date = ? LIMIT 1) as local_reason FROM students s JOIN student_electives se ON s.id = se.student_id WHERE s.class_id = ? AND se.subject_id = ? ORDER BY s.full_name ASC");
    $stmt->execute([$tid, $date, $tid, $date, $slot['class_id'], $slot['subject_id']]);
} else {
    $stmt = $pdo->prepare("SELECT s.id, s.full_name, (SELECT status FROM student_attendance sa WHERE sa.student_id = s.id AND sa.timetable_id = ? AND sa.date = ? LIMIT 1) as local_status, (SELECT reason FROM student_attendance sa WHERE sa.student_id = s.id AND sa.timetable_id = ? AND sa.date = ? LIMIT 1) as local_reason FROM students s WHERE s.class_id = ? ORDER BY s.full_name ASC");
    $stmt->execute([$tid, $date, $tid, $date, $slot['class_id']]);
}
$students = $stmt->fetchAll();

/**
 * --- HANDLE ATTENDANCE SUBMISSION ---
 */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'save_attendance') {
    try {
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM student_attendance WHERE timetable_id = ? AND date = ?")->execute([$tid, $date]);
        $ins = $pdo->prepare("INSERT INTO student_attendance (student_id, timetable_id, date, status, reason, recorded_by) VALUES (?, ?, ?, ?, ?, ?)");
        
        $absent_ids = $_POST['absent'] ?? []; 
        $reasons = $_POST['reason'] ?? [];
        
        foreach ($students as $s) {
            $is_absent = in_array($s['id'], $absent_ids);
            $reason = $is_absent ? ($reasons[$s['id']] ?? 'Unknown') : null;
            $ins->execute([$s['id'], $tid, $date, $is_absent ? 'absent' : 'present', $reason, $uid]);

            // TRIGGER: WonderPush to Class Teacher for each absence
            if ($is_absent && !empty($slot['class_teacher_id']) && $slot['class_teacher_id'] != $uid) {
                sendPushNotification(
                    $slot['class_teacher_id'], 
                    "Absent Alert: " . $s['full_name'], 
                    "Student marked absent in {$slot['class_name']} ({$slot['subject']}). Reason: $reason"
                );
            }
        }
        $pdo->prepare("INSERT IGNORE INTO attendance_logs (timetable_id, user_id, class_id, scan_time, status) VALUES (?, ?, ?, NOW(), 'manual')")->execute([$tid, $uid, $slot['class_id']]);
        $pdo->commit(); 
        $msg = "Attendance saved and Class Teacher notified."; $msg_type = "success";
    } catch (Exception $e) { $pdo->rollBack(); $msg = "Error: " . $e->getMessage(); $msg_type = "danger"; }
}

/**
 * --- HANDLE DISCIPLINE REPORT ---
 */
if (isset($_POST['action']) && $_POST['action'] === 'report_discipline') {
    try {
        $sev = $_POST['severity'] ?? 'low'; $sid_rep = $_POST['student_id']; $infraction = $_POST['infraction'];
        $pdo->prepare("INSERT INTO student_discipline (student_id, timetable_id, infraction, severity, reported_by, reported_date) VALUES (?, ?, ?, ?, ?, ?)")->execute([$sid_rep, $tid, $infraction, $sev, $uid, $date]);
        
        $det = $pdo->query("SELECT s.full_name, c.class_name FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = $sid_rep")->fetch();
        $rep_name = $_SESSION['full_name'] ?? 'Teacher';

        // TRIGGER: WonderPush to Admins for Discipline Issues
        if (in_array(strtolower($sev), ['medium', 'high'])) {
            $admins = $pdo->query("SELECT id FROM users WHERE role LIKE '%admin%' OR role LIKE '%discipline_teacher%'")->fetchAll(PDO::FETCH_COLUMN);
            sendPushNotification(
                $admins, 
                "? " . strtoupper($sev) . " Discipline Alert", 
                "{$det['full_name']} ({$det['class_name']}) reported for $infraction by $rep_name",
                'admin_discipline.php',
                true // Show Action Buttons
            );
        }
        $msg = "Discipline report submitted."; $msg_type = "warning";
    } catch(Exception $e) {}
}

$present_list = []; $absent_list = [];
foreach ($students as $s) { if ($s['local_status'] === 'absent') $absent_list[] = $s; else $present_list[] = $s; }
?>
<!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, user-scalable=no, viewport-fit=cover">
    <title><?= htmlspecialchars($slot['subject']) ?></title>
    <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() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 160px; }
        .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; display: flex; justify-content: space-between; align-items: center; }
        .student-row { display: flex; align-items: center; padding: 12px 15px; border-bottom: 1px solid #f1f5f9; justify-content: space-between; }
        .save-bar { position: fixed; bottom: 90px; left: 20px; right: 20px; z-index: 1050; background: white; padding: 10px; border-radius: 20px; box-shadow: 0 10px 30px rgba(0,0,0,0.15); }
        .reason-dropdown { display: none; }
        .student-row.is-absent .reason-dropdown { display: block; }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="class_session.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold">Class Session</div>
            <div style="width: 24px;"></div>
        </div>
        <h2 class="mb-0 fw-bold"><?= htmlspecialchars($slot['subject']) ?></h2>
        <div class="opacity-75 small"><?= htmlspecialchars($slot['class_name']) ?></div>
    </div>

    <div class="floating-card">
        <div class="text-start"><div class="small text-muted fw-bold">TIME</div><div class="fw-bold text-dark fs-5"><?= substr($slot['start_time'],0,5) ?></div></div>
        <div class="text-end"><div class="small text-muted fw-bold">TOTAL</div><div class="fw-bold text-primary fs-5"><?= count($students) ?></div></div>
    </div>

    <form method="POST" id="attForm" class="px-3">
        <input type="hidden" name="action" value="save_attendance">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> text-center small rounded-4 shadow-sm"><?= $msg ?></div><?php endif; ?>
        
        <div class="accordion" id="attAccordion">
            <div class="accordion-item mb-2 border-0 shadow-sm rounded-4 overflow-hidden">
                <h2 class="accordion-header"><button class="accordion-button bg-white text-danger fw-bold" type="button" data-bs-toggle="collapse" data-bs-target="#collapseAbsent">
                    <i class="bi bi-x-circle-fill me-2"></i> Absent <span class="badge bg-danger ms-auto rounded-pill" id="absentCount"><?= count($absent_list) ?></span>
                </button></h2>
                <div id="collapseAbsent" class="accordion-collapse collapse show">
                    <div class="accordion-body p-0" id="absentContainer">
                        <?php foreach($absent_list as $s): ?>
                            <div class="student-row is-absent" id="row_<?= $s['id'] ?>">
                                <div class="d-flex align-items-center flex-grow-1">
                                    <button type="button" class="btn btn-light btn-sm rounded-circle text-warning me-3" onclick="openDiscipline(<?= $s['id'] ?>, '<?= addslashes($s['full_name']) ?>')"><i class="bi bi-exclamation-triangle-fill"></i></button>
                                    <div>
                                        <div class="fw-bold text-dark small"><?= htmlspecialchars($s['full_name']) ?></div>
                                        <div class="reason-dropdown mt-1">
                                            <select name="reason[<?= $s['id'] ?>]" class="form-select form-select-sm border-danger text-danger bg-danger bg-opacity-10 py-0">
                                                <option value="Unknown">Reason?</option>
                                                <?php foreach($reason_list as $r): ?><option value="<?= $r ?>" <?= ($s['local_reason'] == $r) ? 'selected' : '' ?>><?= $r ?></option><?php endforeach; ?>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                                <div class="form-check"><input class="form-check-input" type="checkbox" name="absent[]" value="<?= $s['id'] ?>" checked onchange="toggleStatus(this, <?= $s['id'] ?>)"></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <div class="accordion-item border-0 shadow-sm rounded-4 overflow-hidden">
                <h2 class="accordion-header"><button class="accordion-button bg-white text-success fw-bold" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePresent">
                    <i class="bi bi-check-circle-fill me-2"></i> Present <span class="badge bg-success ms-auto rounded-pill" id="presentCount"><?= count($present_list) ?></span>
                </button></h2>
                <div id="collapsePresent" class="accordion-collapse collapse show">
                    <div class="accordion-body p-0" id="presentContainer">
                        <?php foreach($present_list as $s): ?>
                            <div class="student-row" id="row_<?= $s['id'] ?>">
                                <div class="d-flex align-items-center flex-grow-1">
                                    <button type="button" class="btn btn-light btn-sm rounded-circle text-warning me-3" onclick="openDiscipline(<?= $s['id'] ?>, '<?= addslashes($s['full_name']) ?>')"><i class="bi bi-exclamation-triangle-fill"></i></button>
                                    <div class="fw-bold text-dark small"><?= htmlspecialchars($s['full_name']) ?></div>
                                </div>
                                <div class="form-check"><input class="form-check-input" type="checkbox" name="absent[]" value="<?= $s['id'] ?>" onchange="toggleStatus(this, <?= $s['id'] ?>)"></div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="save-bar"><button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold shadow-sm py-2">Save Records</button></div>
    </form>

    <div class="modal fade" id="disciplineModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-sm">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header bg-danger text-white border-0"><h6 class="modal-title fw-bold">Discipline Report</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
                <form method="POST">
                    <div class="modal-body p-4">
                        <input type="hidden" name="action" value="report_discipline">
                        <input type="hidden" name="student_id" id="modal_student_id">
                        <p class="small fw-bold text-center mb-3" id="modal_student_name"></p>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">Infraction</label>
                            <select name="infraction" class="form-select bg-light border-0 fw-bold">
                                <?php foreach($infractions as $i): ?><option value="<?= $i ?>"><?= $i ?></option><?php endforeach; ?>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label small fw-bold text-muted">Severity</label>
                            <select name="severity" class="form-select bg-light border-0 fw-bold">
                                <option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option>
                            </select>
                        </div>
                        <button class="btn btn-danger w-100 rounded-pill fw-bold">Submit Push Alert</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

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

    <script src="https://cdn.by.wonderpush.com/sdk/1.1/wonderpush-loader.min.js" async></script>
    <script>
        window.WonderPush = window.WonderPush || [];
        WonderPush.push(["init", {
            webKey: "390f889f3181cac1ea2336c9b5da141b9f796bba46beb826dc127919d80ef64b",
        }]);
        WonderPush.push(function() {
            WonderPush.setUserId("<?= $uid ?>"); 
        });

        // UI Helpers
        function toggleStatus(checkbox, id) {
            const row = document.getElementById('row_' + id);
            if (checkbox.checked) {
                row.classList.add('is-absent');
                document.getElementById('absentContainer').appendChild(row);
            } else {
                row.classList.remove('is-absent');
                document.getElementById('presentContainer').appendChild(row);
            }
            document.getElementById('absentCount').innerText = document.querySelectorAll('#absentContainer .student-row').length;
            document.getElementById('presentCount').innerText = document.querySelectorAll('#presentContainer .student-row').length;
        }

        function openDiscipline(id, name) { 
            document.getElementById('modal_student_id').value = id; 
            document.getElementById('modal_student_name').innerText = name; 
            new bootstrap.Modal(document.getElementById('disciplineModal')).show(); 
        }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>