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

$uid = $_SESSION['user_id'];
$msg = ''; $msg_type = '';

// --- SECURITY ---
header("X-Frame-Options: DENY");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");

if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));

// --- 1. ACCESS CHECK ---
$stmt = $pdo->prepare("SELECT role FROM users WHERE id = ?");
$stmt->execute([$uid]);
$user_roles_str = $stmt->fetchColumn() ?: '';
$user_roles = array_map('trim', explode(',', $user_roles_str));
$allowed_access = ['admin', 'principal', 'assistant', 'discipline_teacher'];

if (empty(array_intersect($user_roles, $allowed_access))) {
    if (function_exists('denyAccess')) denyAccess("Access Denied: Restricted to Discipline Team.");
    else die("Access Denied");
}

// --- 2. OPTIMIZATION: AJAX HANDLER (New) ---
// This makes the page load fast. It only loads students when you select a class.
if (isset($_GET['ajax']) && $_GET['ajax'] === 'students') {
    if (ob_get_length()) ob_clean();
    header('Content-Type: application/json; charset=utf-8');
    $cid = (int)($_GET['class_id'] ?? 0);
    if ($cid <= 0) { echo json_encode([]); exit; }
    $st = $pdo->prepare("SELECT id, full_name, ic_number FROM students WHERE class_id = ? ORDER BY full_name ASC");
    $st->execute([$cid]);
    echo json_encode($st->fetchAll(PDO::FETCH_ASSOC));
    exit;
}

// --- SETTINGS ---
$year  = isset($_GET['year']) ? intval($_GET['year']) : intval(date('Y'));
$month = isset($_GET['month']) ? intval($_GET['month']) : intval(date('n'));

$s_name = getSetting('school_name', 'SMK Muadzam Shah');
$s_addr = getSetting('school_address', 'Jalan Sekolah, 26700 Muadzam Shah, Pahang');
$s_phone = getSetting('school_phone', '');
$principal_name = getSetting('principal_name', '[Nama Pengetua]');
$letter_reference = getSetting('letter_reference', 'Ruj/SMKMS/DS/01');
$official_logo_path = getSetting('official_logo_path', '');
$addr_print = preg_replace('/,\s*/', ",<br>", htmlspecialchars($s_addr));
$raw_infractions = getSetting('infraction_list', 'Disruptive Behavior,Late,Truancy,Fighting,Vandalism,Smoking,Other');
$infraction_list = array_filter(array_map('trim', explode(',', $raw_infractions)));

// --- ACTIONS ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) die("Invalid Request");

    $action = $_POST['action'] ?? '';

    if ($action === 'delete') {
        $pdo->prepare("DELETE FROM student_discipline WHERE id = ?")->execute([$_POST['delete_id']]);
        $msg = "Record deleted."; $msg_type = "warning";
    }
    if ($action === 'edit') {
        $stmt = $pdo->prepare("UPDATE student_discipline SET infraction=?, severity=?, description=? WHERE id=?");
        $stmt->execute([$_POST['infraction'], $_POST['severity'], $_POST['description'], $_POST['record_id']]);
        $msg = "Record updated."; $msg_type = "success";
    }
    if ($action === 'add') {
        $stmt = $pdo->prepare("INSERT INTO student_discipline (student_id, infraction, severity, description, reported_by, reported_date) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$_POST['student_id'], $_POST['infraction'], $_POST['severity'] ?? 'low', $_POST['description'], $uid, $_POST['date'] ?? date('Y-m-d')]);
        
        // 🔔 Create notification for discipline report (principal + assistant_hem + admin + discipline_teacher)
        $notif = $pdo->prepare("
            INSERT INTO notifications (user_id, title, message, link, is_read, created_at)
            SELECT id, :title, :msg, :link, 0, NOW()
            FROM users
            WHERE role IN ('principal','assistant_hem','admin','discipline_teacher')
        ");
        $notif->execute([
            ':title' => 'New Discipline Report',
            ':msg'   => 'A new discipline report has been submitted.',
            ':link'  => 'dashboard_discipline.php'
        ]);
$msg = "New case recorded."; $msg_type = "success";
    }
    if ($action === 'send_telegram') {
        $chat_id = $_POST['chat_id']; $tg_msg = $_POST['message'];
        if (!empty($chat_id) && !empty($tg_msg) && function_exists('sendTelegram')) {
            if (sendTelegram($tg_msg, $chat_id)) { $msg = "Telegram sent."; $msg_type = "success"; }
            else { $msg = "Failed to send Telegram."; $msg_type = "danger"; }
        } else { $msg = "Parent not linked or message empty."; $msg_type = "warning"; }
    }
}

// --- DATA FETCHING ---
$team_sql = "SELECT * FROM users WHERE role REGEXP 'discipline_teacher|admin|principal' ORDER BY full_name ASC";
$disc_team = $pdo->query($team_sql)->fetchAll();

// Trend Chart
$trend_sql = "SELECT MONTH(reported_date) as m, COUNT(*) as c FROM student_discipline WHERE YEAR(reported_date) = ? GROUP BY m";
$stmt = $pdo->prepare($trend_sql); $stmt->execute([$year]); 
$trends_raw = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$chart_trend = array_fill(0, 12, 0); foreach ($trends_raw as $m => $c) $chart_trend[$m - 1] = $c;

// Top Rules
$top_sql = "SELECT infraction, COUNT(*) as c FROM student_discipline WHERE YEAR(reported_date) = ? GROUP BY infraction ORDER BY c DESC LIMIT 5";
$stmt = $pdo->prepare($top_sql); $stmt->execute([$year]); 
$top_rules = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Top Offenders (FIXED FOR STRICT SQL)
$notorious_sql = "
    SELECT s.full_name, c.class_name, COUNT(sd.id) as count 
    FROM student_discipline sd 
    JOIN students s ON sd.student_id = s.id 
    JOIN classes c ON s.class_id = c.id 
    WHERE YEAR(sd.reported_date) = ? 
    GROUP BY s.id, s.full_name, c.class_name 
    ORDER BY count DESC LIMIT 5";
$stmt = $pdo->prepare($notorious_sql); $stmt->execute([$year]); 
$top_offenders = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Calendar Data
$cal_data = [];
$cal_sql = "SELECT reported_date, COUNT(*) as c FROM student_discipline WHERE YEAR(reported_date) = ? AND MONTH(reported_date) = ? GROUP BY reported_date";
$stmt = $pdo->prepare($cal_sql); $stmt->execute([$year, $month]);
while ($row = $stmt->fetch()) $cal_data[$row['reported_date']]['cases'] = $row['c'];

// Holidays
$hol_sql = "SELECT start_date, end_date, type, description FROM school_holidays WHERE YEAR(start_date) = ? ORDER BY start_date ASC";
$stmt = $pdo->prepare($hol_sql); $stmt->execute([$year]); 
$holidays = $stmt->fetchAll();

foreach ($holidays as $h) {
    $curr = strtotime($h['start_date']); $end = strtotime($h['end_date']);
    while ($curr <= $end) {
        if (date('n', $curr) == $month) {
            $d_str = date('Y-m-d', $curr);
            $cal_data[$d_str]['holiday'] = $h['type'];
            $cal_data[$d_str]['desc'] = $h['description'];
        }
        $curr = strtotime('+1 day', $curr);
    }
}

$first_day = mktime(0, 0, 0, $month, 1, $year); 
$days_in_month = date('t', $first_day); 
$week_start = intval(getSetting('week_start_day', 1)); 
$start_dow = date('N', $first_day); 
$offset = ($week_start == 1) ? ($start_dow - 1) : ($start_dow % 7);

// Main Records List
$filter_class = $_GET['class_id'] ?? ''; $filter_date = $_GET['date'] ?? '';
$sql = "SELECT sd.*, s.full_name, s.ic_number, s.parent_chat_id, c.class_name, u.full_name as reporter FROM student_discipline sd JOIN students s ON sd.student_id = s.id JOIN classes c ON s.class_id = c.id JOIN users u ON sd.reported_by = u.id WHERE 1=1";
$params = [];
if ($filter_class) { $sql .= " AND s.class_id = ?"; $params[] = $filter_class; }
if ($filter_date) { $sql .= " AND sd.reported_date = ?"; $params[] = $filter_date; }
$sql .= " ORDER BY sd.reported_date DESC, sd.created_at DESC LIMIT 100";
$stmt = $pdo->prepare($sql); $stmt->execute($params); 
$records = $stmt->fetchAll();

// Classes (Optimized: We do NOT load all students here anymore)
$all_classes = $pdo->query("SELECT id, class_name, form_level FROM classes ORDER BY form_level ASC, class_name ASC")->fetchAll();
$classes_by_form = []; foreach ($all_classes as $c) $classes_by_form[$c['form_level'] ?: 'Other'][] = ['id' => $c['id'], 'name' => $c['class_name']];

try { $header_theme = getHeaderTheme(); } catch (Throwable $e) { $header_theme = 'linear-gradient(135deg,#3b82f6 0%,#60a5fa 100%)'; }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Discipline HQ</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <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@5.3.0/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root { --primary-grad: <?= $header_theme ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); padding-bottom: 120px; }
        .app-header { background: var(--primary-grad); padding: 30px 20px 80px 20px; border-radius: 0 0 35px 35px; color: white; }
        .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; min-height: 400px; }
        .nav-pills .nav-link { color: #64748b; font-weight: 600; padding: 10px 20px; border-radius: 50px; transition: all 0.2s; }
        .nav-pills .nav-link.active { background-color: #f3e8ff; color: #8B5CF6; font-weight: 700; }
        .dashboard-card { background: #fff; border-radius: 20px; box-shadow: 0 4px 20px rgba(0,0,0,0.03); border: 1px solid rgba(0,0,0,0.04); overflow: hidden; }
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 6px; text-align: center; margin-bottom: 10px; }
        .cal-day { aspect-ratio: 1/1; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: 0.9rem; font-weight: 600; color: #495057; border-radius: 16px; cursor: pointer; background: #f8f9fa; border: none; position: relative; transition: transform 0.1s; }
        .cal-day:active { transform: scale(0.95); }
        .bg-national { background: linear-gradient(135deg, #ef4444 0%, #f87171 100%) !important; color: white !important; }
        .bg-term { background: linear-gradient(135deg, #3b82f6 0%, #60a5fa 100%) !important; color: white !important; }
        .bg-school_event { background: linear-gradient(135deg, #8B5CF6 0%, #a78bfa 100%) !important; color: white !important; }
        .cal-badge { position: absolute; top: 4px; right: 4px; width: 8px; height: 8px; background: #ef4444; border-radius: 50%; box-shadow: 0 0 0 2px white; }
        .form-control, .form-select { border-radius: 12px; padding: 10px; border-color: #e2e8f0; font-size: 0.95rem; }
        @media print { body * { visibility: hidden; } .print-area, .print-area * { visibility: visible; } .print-area { position: absolute; left: 0; top: 0; width: 100%; } }
    </style>
</head>
<body>

    <div class="app-header no-print">
        <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">Discipline HQ</div>
            <div class="d-flex gap-2">
                <button class="btn btn-light text-primary fw-bold btn-sm rounded-pill px-3 shadow-sm" onclick="openAddModal()">
                    <i class="bi bi-plus-lg me-1"></i> Add
                </button>
            </div>
        </div>
        <div class="opacity-75 small text-center">Manage discipline records & reports</div>
    </div>

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

        <ul class="nav nav-pills mb-4 justify-content-center bg-light p-1 rounded-pill" id="discTabs" style="display: inline-flex; width: 100%;">
            <li class="nav-item flex-fill text-center"><button class="nav-link active w-100" id="tab-dash" data-bs-toggle="tab" data-bs-target="#dash">Overview</button></li>
            <li class="nav-item flex-fill text-center"><button class="nav-link w-100" id="tab-records" data-bs-toggle="tab" data-bs-target="#records">Records</button></li>
            <li class="nav-item flex-fill text-center"><button class="nav-link w-100" id="tab-calendar" data-bs-toggle="tab" data-bs-target="#calendar">Calendar</button></li>
            <li class="nav-item flex-fill text-center"><button class="nav-link w-100" id="tab-team" data-bs-toggle="tab" data-bs-target="#team">Team</button></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="dash">
                <div class="row g-3 mb-4">
                    <div class="col-4"><div class="dashboard-card p-3 text-center h-100"><div class="h2 fw-bold text-primary mb-0"><?= count($records) ?></div><div class="small text-muted fw-bold" style="font-size:0.7rem;">TOTAL</div></div></div>
                    <div class="col-4"><div class="dashboard-card p-3 text-center h-100"><div class="h2 fw-bold text-warning mb-0"><?= $top_rules[0]['c'] ?? 0 ?></div><div class="small text-muted fw-bold" style="font-size:0.7rem;">TOP ISSUE</div></div></div>
                    <div class="col-4"><div class="dashboard-card p-3 text-center h-100"><div class="h2 fw-bold text-danger mb-0"><?= count($top_offenders) ?></div><div class="small text-muted fw-bold" style="font-size:0.7rem;">REPEATERS</div></div></div>
                </div>

                <div class="row g-3">
                    <div class="col-md-8">
                        <div class="dashboard-card p-3 h-100">
                            <h6 class="fw-bold text-dark mb-3">Offense Trend (<?= $year ?>)</h6>
                            <div style="height: 200px;"><canvas id="trendChart"></canvas></div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="dashboard-card h-100">
                            <div class="p-3 bg-danger bg-opacity-10 text-danger fw-bold border-bottom"><i class="bi bi-exclamation-triangle-fill me-2"></i>Most Notorious</div>
                            <ul class="list-group list-group-flush small">
                                <?php foreach ($top_offenders as $o): ?>
                                <li class="list-group-item border-0 d-flex justify-content-between align-items-center px-3 py-2">
                                    <div><div class="fw-bold text-dark"><?= htmlspecialchars($o['full_name']) ?></div><div class="text-muted" style="font-size:0.7rem;"><?= htmlspecialchars($o['class_name']) ?></div></div>
                                    <span class="badge bg-danger rounded-pill"><?= $o['count'] ?></span>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="records">
                <div class="dashboard-card p-3 mb-3 bg-light border-0">
                    <form method="GET" class="row g-2">
                        <div class="col-12">
                            <select name="class_id" class="form-select border-0 shadow-sm">
                                <option value="">Filter by Class...</option>
                                <?php foreach ($all_classes as $c): ?>
                                    <option value="<?= $c['id'] ?>" <?= $filter_class == $c['id'] ? 'selected' : '' ?>><?= htmlspecialchars($c['class_name']) ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-12"><button class="btn btn-primary btn-sm w-100 fw-bold rounded-pill">Apply Filter</button></div>
                    </form>
                </div>

                <div class="dashboard-card overflow-hidden">
                    <div class="table-responsive">
                        <table class="table table-borderless align-middle mb-0">
                            <thead class="bg-light text-muted small"><tr><th class="ps-4 py-3">Student</th><th class="py-3">Offense</th><th class="text-end pe-4 py-3"></th></tr></thead>
                            <tbody>
                                <?php foreach ($records as $r): $bg = match ($r['severity']) { 'high' => 'danger', 'medium' => 'warning text-dark', default => 'info text-dark', }; ?>
                                    <tr class="border-bottom">
                                        <td class="ps-4">
                                            <div class="fw-bold text-dark"><?= htmlspecialchars($r['full_name']) ?></div>
                                            <div class="small text-muted"><?= htmlspecialchars($r['class_name']) ?></div>
                                        </td>
                                        <td>
                                            <div class="fw-bold text-dark small"><?= htmlspecialchars($r['infraction']) ?></div>
                                            <span class="badge bg-<?= $bg ?> bg-opacity-25 text-<?= str_replace(' text-dark','',$bg) ?> rounded-pill" style="font-size:0.65rem;"><?= ucfirst($r['severity']) ?></span>
                                        </td>
                                        <td class="text-end pe-4">
                                            <button class="btn btn-light text-primary btn-sm rounded-circle shadow-sm" style="width:32px;height:32px;" onclick='openManageModal(<?= json_encode($r) ?>)'>
                                                <i class="bi bi-pencil-fill" style="font-size:0.7rem;"></i>
                                            </button>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($records)): ?><tr><td colspan="3" class="text-center small text-muted py-4">No records found.</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="calendar">
                <div class="dashboard-card p-3">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <a href="?month=<?= $month - 1 ?>&year=<?= $year ?>&tab=calendar" class="btn btn-light btn-sm rounded-circle shadow-sm"><i class="bi bi-chevron-left"></i></a>
                        <span class="fw-bold text-primary"><?= date("F Y", mktime(0, 0, 0, $month, 1, $year)) ?></span>
                        <a href="?month=<?= $month + 1 ?>&year=<?= $year ?>&tab=calendar" class="btn btn-light btn-sm rounded-circle shadow-sm"><i class="bi bi-chevron-right"></i></a>
                    </div>
                    <div class="cal-grid">
                        <?php $days = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; foreach ($days as $d) echo "<div class='small text-muted fw-bold py-2' style='font-size:0.7rem;'>$d</div>";
                        for ($i = 0; $i < $offset; $i++) echo "<div></div>";
                        for ($d = 1; $d <= $days_in_month; $d++) {
                            $date_str = sprintf("%04d-%02d-%02d", $year, $month, $d); $cell_class = ''; $badge = ''; $tooltip = '';
                            if (!empty($cal_data[$date_str]['holiday'])) { $cell_class = 'bg-' . $cal_data[$date_str]['holiday']; $tooltip = $cal_data[$date_str]['desc'] ?? ''; }
                            if (!empty($cal_data[$date_str]['cases'])) { $badge = "<div class='cal-badge'></div>"; }
                            echo "<div class='cal-day $cell_class' onclick=\"window.location='?date=$date_str&tab=records'\" title='" . htmlspecialchars($tooltip, ENT_QUOTES) . "'><span>$d</span>$badge</div>";
                        }
                        ?>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="team">
                <div class="row g-3">
                    <?php foreach ($disc_team as $tm): ?>
                        <div class="col-md-6">
                            <div class="dashboard-card p-3 h-100 d-flex align-items-center">
                                <div class="bg-primary bg-opacity-10 text-primary rounded-3 d-flex align-items-center justify-content-center me-3" style="width:48px;height:48px;font-size:1.2rem;font-weight:bold;"><?= substr($tm['full_name'],0,1) ?></div>
                                <div><h6 class="fw-bold text-dark mb-0"><?= htmlspecialchars($tm['full_name']) ?></h6><div class="small text-muted"><?= htmlspecialchars($tm['phone_number'] ?? '-') ?></div></div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="addModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-bold text-dark">New Record</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"><input type="hidden" name="action" value="add">
                    <div class="modal-body p-4">
                        <div class="row g-2 mb-3">
                            <div class="col-4">
                                <label class="small fw-bold text-muted">Form</label>
                                <select id="sel_form" class="form-select" onchange="loadClasses()">
                                    <option value="">-</option>
                                    <?php foreach(array_keys($classes_by_form) as $f) echo "<option value='$f'>$f</option>"; ?>
                                </select>
                            </div>
                            <div class="col-8">
                                <label class="small fw-bold text-muted">Class</label>
                                <select id="sel_class" class="form-select" disabled onchange="loadStudents()"><option value="">Select Form First</option></select>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="small fw-bold text-muted">Student</label>
                            <select name="student_id" id="sel_student" class="form-select" disabled required><option value="">Select Class First</option></select>
                        </div>
                        <div class="bg-light p-3 rounded-3 mb-3">
                            <div class="mb-2"><label class="small fw-bold text-muted">Infraction</label><select name="infraction" class="form-select" required><option value="">-- Select --</option><?php foreach ($infraction_list as $inf): ?><option value="<?= htmlspecialchars($inf) ?>"><?= htmlspecialchars($inf) ?></option><?php endforeach; ?></select></div>
                            <div class="row g-2">
                                <div class="col-6"><label class="small fw-bold text-muted">Severity</label><select name="severity" class="form-select"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select></div>
                                <div class="col-6"><label class="small fw-bold text-muted">Date</label><input type="date" name="date" class="form-control" value="<?= date('Y-m-d') ?>" required></div>
                            </div>
                        </div>
                        <div class="mb-0"><label class="small fw-bold text-muted">Description</label><textarea name="description" class="form-control" rows="2" placeholder="Details..."></textarea></div>
                    </div>
                    <div class="modal-footer border-0 pt-0 px-4 pb-4"><button class="btn btn-primary w-100 fw-bold rounded-pill">Save Record</button></div>
                </form>
            </div>
        </div>
    </div>

    <div class="modal fade" id="manageModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-bold">Manage Case</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body p-4">
                    <div class="d-flex justify-content-between align-items-start mb-4 border-bottom pb-3">
                        <div><h5 class="fw-bold mb-0 text-dark" id="m_name">Student</h5><div class="text-muted small" id="m_class">Class</div></div>
                        <div class="text-end"><span class="badge bg-dark rounded-pill" id="m_sev">HIGH</span><div class="small text-danger fw-bold mt-1" id="m_inf">Fighting</div></div>
                    </div>

                    <h6 class="fw-bold text-primary mb-2" style="font-size:0.8rem; text-transform:uppercase;"><i class="bi bi-printer me-2"></i>Generate Letter</h6>
                    <div class="bg-light p-3 rounded-3 mb-3">
                        <div class="row g-2 mb-3">
                            <div class="col-6"><label class="small fw-bold text-muted">Meeting Date</label><input type="date" id="meet_date" class="form-control form-control-sm" value="<?= date('Y-m-d', strtotime('+1 day')) ?>"></div>
                            <div class="col-6"><label class="small fw-bold text-muted">Time</label><input type="time" id="meet_time" class="form-control form-control-sm" value="09:00"></div>
                        </div>
                        <div class="d-grid gap-2">
                            <button class="btn btn-sm btn-white border shadow-sm rounded-pill fw-bold text-start ps-3" onclick="showLetterPreview('warning')"><i class="bi bi-file-earmark-text me-2 text-warning"></i> Amaran Salah Laku</button>
                            <button class="btn btn-sm btn-white border shadow-sm rounded-pill fw-bold text-start ps-3" onclick="showLetterPreview('absence')"><i class="bi bi-file-earmark-x me-2 text-danger"></i> Amaran Ketidakhadiran</button>
                            <button class="btn btn-sm btn-white border shadow-sm rounded-pill fw-bold text-start ps-3" onclick="showLetterPreview('call')"><i class="bi bi-telephone-outbound me-2 text-primary"></i> Panggilan Ibu Bapa</button>
                        </div>
                    </div>
                    
                    <div id="letterPreview" class="border rounded bg-white p-3 small mb-3 d-none shadow-sm" style="max-height: 250px; overflow:auto;"></div>
                    <button id="btnPrintFromPreview" class="btn btn-sm btn-dark w-100 mb-4 d-none rounded-pill fw-bold" onclick="printLetter(currentLetterType)"><i class="bi bi-printer me-1"></i> Print This Letter</button>
                    
                    <h6 class="fw-bold text-info mb-2" style="font-size:0.8rem; text-transform:uppercase;"><i class="bi bi-telegram me-2"></i>Notify Parent</h6>
                    <form method="POST" class="mb-4">
                        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"><input type="hidden" name="action" value="send_telegram"><input type="hidden" name="chat_id" id="m_chat_id">
                        <div class="input-group">
                            <input type="text" name="message" id="m_tg_msg" class="form-control form-control-sm" placeholder="Message..." required>
                            <button class="btn btn-info btn-sm text-white fw-bold"><i class="bi bi-send"></i></button>
                        </div>
                        <div class="form-text small" id="m_tg_status">Checking link...</div>
                    </form>

                    <div class="d-flex gap-2">
                        <button class="btn btn-light border w-100 rounded-pill fw-bold text-secondary" onclick="enableEditMode()">Edit</button>
                        <button id="m_del_btn" class="btn btn-light border text-danger w-100 rounded-pill fw-bold">Delete</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <form id="deleteForm" method="POST" style="display:none"><input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"><input type="hidden" name="action" value="delete"><input type="hidden" name="delete_id" id="delete_id_input"></form>

    <div class="modal fade" id="editFormModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <form method="POST">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>"><input type="hidden" name="action" value="edit"><input type="hidden" name="record_id" id="e_id">
                    <div class="modal-header border-0 pb-0"><h5 class="modal-title fw-bold">Edit Details</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                    <div class="modal-body p-4">
                        <div class="mb-3"><label class="small fw-bold text-muted">Infraction</label><select name="infraction" id="e_inf" class="form-select"><?php foreach ($infraction_list as $inf): ?><option value="<?= htmlspecialchars($inf) ?>"><?= htmlspecialchars($inf) ?></option><?php endforeach; ?></select></div>
                        <div class="mb-3"><label class="small fw-bold text-muted">Severity</label><select name="severity" id="e_sev" class="form-select"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select></div>
                        <div class="mb-3"><label class="small fw-bold text-muted">Description</label><textarea name="description" id="e_desc" class="form-control" rows="3"></textarea></div>
                        <button class="btn btn-primary w-100 fw-bold rounded-pill">Save Changes</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <div id="printArea" class="print-area d-none bg-white text-dark p-5">
        <div id="tpl_warning" class="d-none">
            <div class="text-start mb-3"><table style="width:100%;"><tr><?php if (!empty($official_logo_path)): ?><td style="width:80px; vertical-align:top;"><img src="<?= htmlspecialchars($official_logo_path) ?>" style="width:70px;height:70px;object-fit:contain;"></td><?php else: ?><td style="width:80px;"></td><?php endif; ?><td style="vertical-align:top;font-size:0.9rem;"><strong><?= htmlspecialchars($s_name) ?></strong><br><?= $addr_print ?><br><?php if ($s_phone): ?>No. Tel: <?= htmlspecialchars($s_phone) ?><br><?php endif; ?></td></tr></table><hr class="border-dark border-2 mt-2 mb-3"></div>
            <table class="w-100 mb-3" style="font-size:0.9rem;"><tr><td style="width:60%;">Rujukan : <span class="p_ref"><?= htmlspecialchars($letter_reference) ?></span></td><td style="width:40%;">Tarikh : <?= date('d M Y') ?></td></tr></table>
            <p class="mb-1">Kepada<br>Ibu Bapa / Penjaga<br><span class="p_student_name_upper"></span></p>
            <p class="mt-3 mb-1"><strong>Tindakan Disiplin : AMARAN 1</strong></p>
            <table class="mb-3" style="font-size:0.9rem;"><tr><td style="width:70px;">Nama</td><td>:</td><td><span class="p_name_upper"></span></td></tr><tr><td>No KP</td><td>:</td><td><span class="p_ic"></span></td></tr><tr><td>Kelas</td><td>:</td><td><span class="p_class"></span></td></tr></table>
            <p style="text-align:justify;">Di bawah Peraturan 4, Peraturan-Peraturan Pelajaran (Disiplin Sekolah) 1959, tanggungjawab terhadap disiplin murid adalah terletak pada Guru Besar / Pengetua sekolah.</p>
            <p style="text-align:justify;">2. Saya dengan ini memaklumkan bahawa murid di atas telah melakukan salah laku berikut:</p>
            <p class="border border-dark p-2" style="font-size:0.9rem; text-align:justify;">"Bahawa kamu, nama <strong><span class="p_name_upper"></span></strong>, No. Kad Pengenalan <strong><span class="p_ic"></span></strong>, pada tarikh <strong><span class="p_offense_date"></span></strong> telah didapati <strong><span class="p_full_offense"></span></strong>."</p>
            <p style="text-align:justify;">3. Dengan ini pihak sekolah memberi <strong>AMARAN</strong> kepada kamu. Diharapkan kesalahan ini tidak berulang.</p>
            <p class="mt-4 mb-1">Sekian, terima kasih.</p><p class="mb-4">"BERKHIDMAT UNTUK NEGARA"</p>
            <p>Saya yang menurut perintah,</p><br><br><br><p>..............................................................<br>( <span class="p_principal_name"><?= htmlspecialchars($principal_name) ?></span> )<br>Pengetua,<br><?= htmlspecialchars($s_name) ?></p>
        </div>
        <div id="tpl_absence" class="d-none">
             <div class="text-start mb-3"><table style="width:100%;"><tr><?php if (!empty($official_logo_path)): ?><td style="width:80px; vertical-align:top;"><img src="<?= htmlspecialchars($official_logo_path) ?>" style="width:70px;height:70px;object-fit:contain;"></td><?php else: ?><td style="width:80px;"></td><?php endif; ?><td style="vertical-align:top;font-size:0.9rem;"><strong><?= htmlspecialchars($s_name) ?></strong><br><?= $addr_print ?><br><?php if ($s_phone): ?>No. Tel: <?= htmlspecialchars($s_phone) ?><br><?php endif; ?></td></tr></table><hr class="border-dark border-2 mt-2 mb-3"></div>
            <table class="w-100 mb-3" style="font-size:0.9rem;"><tr><td style="width:60%;">Rujukan : <span class="p_ref"><?= htmlspecialchars($letter_reference) ?></span></td><td style="width:40%;">Tarikh : <?= date('d M Y') ?></td></tr></table>
            <p class="mb-1">Kepada<br>Ibu Bapa / Penjaga<br><span class="p_student_name_upper"></span></p>
            <p class="mt-3 mb-2"><strong>AMARAN PERTAMA KETIDAKHADIRAN KE SEKOLAH</strong></p>
            <p style="text-align:justify;">Dimaklumkan bahawa anak/jagaan tuan/puan, <strong><span class="p_name_upper"></span></strong> dari kelas <strong><span class="p_class"></span></strong> telah tidak hadir ke sekolah tanpa sebab pada: <strong><span class="p_offense_date"></span></strong>.</p>
            <p style="text-align:justify;">2. Sila pastikan anak/jagaan tuan/puan hadir ke sekolah setiap hari.</p>
            <p class="mt-4 mb-1">Sekian, terima kasih.</p><p class="mb-4">"BERKHIDMAT UNTUK NEGARA"</p>
            <p>Saya yang menjalankan amanah,</p><br><br><br><p>..............................................................<br>( <span class="p_principal_name"><?= htmlspecialchars($principal_name) ?></span> )<br>Pengetua,<br><?= htmlspecialchars($s_name) ?></p>
        </div>
        <div id="tpl_call" class="d-none">
            <div class="text-start mb-3"><table style="width:100%;"><tr><?php if (!empty($official_logo_path)): ?><td style="width:80px; vertical-align:top;"><img src="<?= htmlspecialchars($official_logo_path) ?>" style="width:70px;height:70px;object-fit:contain;"></td><?php else: ?><td style="width:80px;"></td><?php endif; ?><td style="vertical-align:top;font-size:0.9rem;"><strong><?= htmlspecialchars($s_name) ?></strong><br><?= $addr_print ?><br><?php if ($s_phone): ?>No. Tel: <?= htmlspecialchars($s_phone) ?><br><?php endif; ?></td></tr></table><hr class="border-dark border-2 mt-2 mb-3"></div>
            <table class="w-100 mb-3" style="font-size:0.9rem;"><tr><td style="width:60%;">Rujukan : <span class="p_ref"><?= htmlspecialchars($letter_reference) ?></span></td><td style="width:40%;">Tarikh : <?= date('d M Y') ?></td></tr></table>
            <p class="mb-1">Kepada<br>Ibu Bapa / Penjaga<br><strong><span class="p_name_upper"></span></strong></p>
            <p class="mt-3 mb-2"><strong>SURAT PANGGILAN IBU BAPA / PENJAGA</strong></p>
            <p style="text-align:justify;">Tuan / Puan dijemput hadir ke sekolah bagi membincangkan hal disiplin anak/jagaan tuan/puan, <strong><span class="p_name_upper"></span></strong>, berkaitan kesalahan:</p>
            <p class="fw-bold text-center my-3">"<span class="p_full_offense"></span>"</p>
            <ul class="my-3"><li><strong>Tarikh:</strong> <span id="p_meet_date"></span></li><li><strong>Masa:</strong> <span id="p_meet_time"></span></li><li><strong>Tempat:</strong> Bilik Disiplin</li></ul>
            <p class="mt-4 mb-1">Sekian, terima kasih.</p><p class="mb-4">"BERKHIDMAT UNTUK NEGARA"</p>
            <p>Saya yang menjalankan amanah,</p><br><br><br><p>..............................................................<br>( <span class="p_principal_name"><?= htmlspecialchars($principal_name) ?></span> )<br>Pengetua,<br><?= htmlspecialchars($s_name) ?></p>
        </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 trendCanvas = document.getElementById('trendChart');
        if (trendCanvas) { 
            new Chart(trendCanvas, { 
                type: 'line', 
                data: { 
                    labels: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'], 
                    datasets: [{ 
                        label: 'Cases', 
                        data: <?= json_encode($chart_trend) ?>, 
                        borderColor: '#8B5CF6', backgroundColor: 'rgba(139, 92, 246, 0.1)', borderWidth: 2, fill: true, tension: 0.4, pointRadius: 3
                    }] 
                }, 
                options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, grid: { borderDash: [5, 5] } }, x: { grid: { display: false } } } } 
            }); 
        }

        // --- OPTIMIZATION: ONLY LOAD STUDENTS WHEN NEEDED ---
        const classesByForm = <?= json_encode($classes_by_form) ?>;
        
        // This function replaces the old huge JSON variable
        async function fetchStudentsByClass(classId) {
            try {
                const res = await fetch(`admin_discipline.php?ajax=students&class_id=${classId}`);
                if (!res.ok) return [];
                return await res.json();
            } catch (e) { console.error(e); return []; }
        }

        const addModal = new bootstrap.Modal(document.getElementById('addModal'));
        const manageModal = new bootstrap.Modal(document.getElementById('manageModal'));
        const editFormModal = new bootstrap.Modal(document.getElementById('editFormModal'));
        let currentRecord = null;
        let currentLetterType = null;

        function openAddModal() { addModal.show(); }

        function loadClasses() {
            const form = document.getElementById('sel_form').value; const cs = document.getElementById('sel_class'); const ss = document.getElementById('sel_student');
            cs.innerHTML = '<option value="">Select Class...</option>'; ss.innerHTML = '<option value="">Select Form First</option>'; ss.disabled = true;
            if (form && classesByForm[form]) { cs.disabled = false; classesByForm[form].forEach(c => cs.add(new Option(c.name, c.id))); } else { cs.disabled = true; }
        }

        async function loadStudents() {
            const cid = document.getElementById('sel_class').value; const ss = document.getElementById('sel_student');
            ss.innerHTML = '<option value="">Loading...</option>'; ss.disabled = true;
            
            // Fetch from server instead of huge javascript array
            const students = await fetchStudentsByClass(cid);
            
            ss.innerHTML = '<option value="">Select Student...</option>';
            if (students && students.length > 0) {
                ss.disabled = false;
                students.forEach(s => ss.add(new Option(s.full_name + ' (' + s.ic_number + ')', s.id)));
            } else {
                ss.innerHTML = '<option value="">No students found</option>';
            }
        }

        function mapSeverityLabel(sev) { switch ((sev || '').toLowerCase()) { case 'high': return 'BERAT'; case 'medium': return 'SEDERHANA'; case 'low': return 'RINGAN'; default: return sev ? sev.toUpperCase() : ''; } }
        function formatDateMY(dateStr) { if (!dateStr) return ''; const d = new Date(dateStr); if (isNaN(d)) return dateStr; return d.toLocaleDateString('en-GB'); }

        function openManageModal(r) {
            currentRecord = r;
            document.getElementById('m_name').innerText = r.full_name; document.getElementById('m_class').innerText = r.class_name + ' (' + r.ic_number + ')'; document.getElementById('m_inf').innerText = r.infraction; document.getElementById('m_sev').innerText = r.severity.toUpperCase();
            document.getElementById('m_chat_id').value = r.parent_chat_id || ''; document.getElementById('m_tg_msg').value = `PEMBERITAHUAN: Anak anda ${r.full_name} dari kelas ${r.class_name} telah melakukan kesalahan ${r.infraction}. Sila hubungi pihak sekolah.`;
            const tgStatus = document.getElementById('m_tg_status');
            if (r.parent_chat_id) { tgStatus.innerText = "✓ Telegram Linked"; tgStatus.className = "form-text small text-success fw-bold"; } else { tgStatus.innerText = "✗ No Telegram Link"; tgStatus.className = "form-text small text-danger fw-bold"; }
            
            const delBtn = document.getElementById('m_del_btn');
            delBtn.onclick = function() {
                if(confirm('Are you sure you want to delete this record?')) {
                    document.getElementById('delete_id_input').value = r.id;
                    document.getElementById('deleteForm').submit();
                }
            };

            const preview = document.getElementById('letterPreview'); const btnPrint = document.getElementById('btnPrintFromPreview');
            preview.classList.add('d-none'); preview.innerHTML = ''; btnPrint.classList.add('d-none'); currentLetterType = null;
            manageModal.show();
        }

        function enableEditMode() {
            manageModal.hide(); document.getElementById('e_id').value = currentRecord.id; document.getElementById('e_inf').value = currentRecord.infraction; document.getElementById('e_sev').value = currentRecord.severity; document.getElementById('e_desc').value = currentRecord.description || ''; editFormModal.show();
        }

        function showLetterPreview(type) {
            if (!currentRecord) return; currentLetterType = type;
            const preview = document.getElementById('letterPreview'); const btnPrint = document.getElementById('btnPrintFromPreview');
            let templateHtml = '';
            if (type === 'warning') templateHtml = document.getElementById('tpl_warning').innerHTML;
            else if (type === 'absence') templateHtml = document.getElementById('tpl_absence').innerHTML;
            else templateHtml = document.getElementById('tpl_call').innerHTML;

            const tmp = document.createElement('div'); tmp.innerHTML = templateHtml;
            const fullOffense = (currentRecord.description && currentRecord.description.trim() !== '') ? currentRecord.infraction + ' - ' + currentRecord.description : currentRecord.infraction;

            tmp.querySelectorAll('.p_name').forEach(el => el.innerText = currentRecord.full_name);
            tmp.querySelectorAll('.p_name_upper').forEach(el => el.innerText = (currentRecord.full_name || '').toUpperCase());
            tmp.querySelectorAll('.p_student_name_upper').forEach(el => el.innerText = (currentRecord.full_name || '').toUpperCase());
            tmp.querySelectorAll('.p_class').forEach(el => el.innerText = currentRecord.class_name || '');
            tmp.querySelectorAll('.p_ic').forEach(el => el.innerText = currentRecord.ic_number || '');
            tmp.querySelectorAll('.p_full_offense').forEach(el => el.innerText = fullOffense);
            tmp.querySelectorAll('.p_sev').forEach(el => el.innerText = mapSeverityLabel(currentRecord.severity));
            tmp.querySelectorAll('.p_offense_date').forEach(el => el.innerText = formatDateMY(currentRecord.reported_date));

            if (type === 'call') {
                const d = new Date(document.getElementById('meet_date').value); const dateStr = d.toLocaleDateString('en-GB'); const timeStr = document.getElementById('meet_time').value || '09:00';
                const dateEl = tmp.querySelector('#p_meet_date'); const timeEl = tmp.querySelector('#p_meet_time');
                if (dateEl) dateEl.innerText = dateStr; if (timeEl) timeEl.innerText = timeStr;
            }
            preview.innerHTML = tmp.innerHTML; preview.classList.remove('d-none'); btnPrint.classList.remove('d-none');
        }

        function printLetter(type) {
            if (!type || !currentRecord) return;
            const printArea = document.getElementById('printArea'); printArea.classList.remove('d-none');
            ['warning', 'absence', 'call'].forEach(t => { const el = document.getElementById('tpl_' + t); if (el) el.classList.add('d-none'); });
            const activeTpl = document.getElementById('tpl_' + type); if (!activeTpl) return; activeTpl.classList.remove('d-none');
            const fullOffense = (currentRecord.description && currentRecord.description.trim() !== '') ? currentRecord.infraction + ' - ' + currentRecord.description : currentRecord.infraction;
            activeTpl.querySelectorAll('.p_name').forEach(e => e.innerText = currentRecord.full_name);
            activeTpl.querySelectorAll('.p_name_upper').forEach(e => e.innerText = (currentRecord.full_name || '').toUpperCase());
            activeTpl.querySelectorAll('.p_student_name_upper').forEach(e => e.innerText = (currentRecord.full_name || '').toUpperCase());
            activeTpl.querySelectorAll('.p_class').forEach(e => e.innerText = currentRecord.class_name || '');
            activeTpl.querySelectorAll('.p_ic').forEach(e => e.innerText = currentRecord.ic_number || '');
            activeTpl.querySelectorAll('.p_full_offense').forEach(e => e.innerText = fullOffense);
            activeTpl.querySelectorAll('.p_sev').forEach(e => e.innerText = mapSeverityLabel(currentRecord.severity));
            activeTpl.querySelectorAll('.p_offense_date').forEach(e => e.innerText = formatDateMY(currentRecord.reported_date));
            if (type === 'call') {
                const d = new Date(document.getElementById('meet_date').value); const dateStr = d.toLocaleDateString('en-GB'); const timeStr = document.getElementById('meet_time').value || '09:00';
                const dateEl = activeTpl.querySelector('#p_meet_date'); const timeEl = activeTpl.querySelector('#p_meet_time');
                if (dateEl) dateEl.innerText = dateStr; if (timeEl) timeEl.innerText = timeStr;
            }
            window.print(); printArea.classList.add('d-none');
        }
        const urlParams = new URLSearchParams(window.location.search); const tab = urlParams.get('tab');
        if (tab) { const triggerEl = document.querySelector(`#discTabs button[data-bs-target="#${tab}"]`); if (triggerEl) bootstrap.Tab.getOrCreateInstance(triggerEl).show(); }
    </script>
</body>
</html>