<?php
// Filename: dashboard_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', 'assistant_hem', 'discipline_teacher'];

if (empty(array_intersect($user_roles, $allowed_access))) {
    die("Access Denied");
}

// --- 2. AJAX HANDLER ---
if (isset($_GET['ajax']) && $_GET['ajax'] === 'students') {
    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');
$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 successfully."; $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') {
        $student_id = $_POST['student_id'];
        $infraction = $_POST['infraction'];
        $severity = $_POST['severity'];
        $desc = $_POST['description'];
        $date = $_POST['date'];

        $stmt = $pdo->prepare("INSERT INTO student_discipline (student_id, infraction, severity, description, reported_by, reported_date) VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$student_id, $infraction, $severity, $desc, $uid, $date]);
        
        // --- NOTIFICATION TRIGGER (Fixed Emoji & Logic) ---
        if ($severity === 'high') {
            // Get Details
            $info_stmt = $pdo->prepare("SELECT s.full_name, c.class_name FROM students s JOIN classes c ON s.class_id = c.id WHERE s.id = ?");
            $info_stmt->execute([$student_id]);
            $student = $info_stmt->fetch();

            if ($student) {
                // FIXED: Use Unicode Escape for Siren Emoji (prevents '??' issue)
                $emoji = "\u{1F6A8}"; 
                
                // 1. Send Telegram
                $alert_msg = "$emoji <b>HIGH DISCIPLINE ALERT</b>\n";
                $alert_msg .= "--------------------------------\n";
                $alert_msg .= "? <b>Name:</b> " . htmlspecialchars($student['full_name']) . "\n";
                $alert_msg .= "? <b>Class:</b> " . htmlspecialchars($student['class_name']) . "\n";
                $alert_msg .= "?? <b>Offense:</b> " . htmlspecialchars($infraction) . "\n";
                $alert_msg .= "? <b>Note:</b> " . htmlspecialchars($desc) . "\n";
                $alert_msg .= "? <b>Reporter:</b> " . htmlspecialchars($_SESSION['full_name'] ?? 'Staff');

                if (function_exists('sendTelegram')) {
                    sendTelegram($alert_msg, null, 'urgent');
                }

                // 2. Send Dashboard Notifications (To All Relevant Staff)
                $targets = $pdo->query("SELECT id FROM users WHERE role REGEXP 'admin|principal|assistant_hem|discipline_teacher'")->fetchAll(PDO::FETCH_COLUMN);
                
                $dash_msg = "$emoji High Severity: {$student['full_name']} ({$infraction})";
                $ins_notif = $pdo->prepare("INSERT INTO notifications (user_id, message, created_at, is_read) VALUES (?, ?, NOW(), 0)");
                
                foreach ($targets as $tid) {
                    // FIXED: Removed the condition "if ($tid != $uid)"
                    // Now YOU (the reporter) will also receive the bell notification to verify it works.
                    $ins_notif->execute([$tid, $dash_msg]);
                }
            }
        }

        $msg = "Case recorded and notifications sent."; $msg_type = "success";
    }
}

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

$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_sql = "SELECT infraction, COUNT(*) as c FROM student_discipline WHERE YEAR(reported_date) = ? GROUP BY infraction ORDER BY c DESC LIMIT 1";
$top_issue = $pdo->prepare($top_sql); $top_issue->execute([$year]);
$top_res = $top_issue->fetch();

$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 ORDER BY sd.reported_date DESC LIMIT 100";
$records = $pdo->query($sql)->fetchAll();

$all_classes = $pdo->query("SELECT id, class_name, form_level FROM classes ORDER BY form_level ASC, class_name ASC")->fetchAll();
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">
    <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); z-index: 10; position: relative; }
        .dashboard-card { background: #fff; border-radius: 20px; border: 1px solid rgba(0,0,0,0.04); overflow: hidden; }
        .nav-pills .nav-link.active { background-color: #8B5CF6; color: white; }
    </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">Discipline HQ</div>
            <button class="btn btn-light text-primary fw-bold btn-sm rounded-pill px-3 shadow-sm" data-bs-toggle="modal" data-bs-target="#addModal">
                <i class="bi bi-plus-lg me-1"></i> Add Record
            </button>
        </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-4"><?= $msg ?></div>
        <?php endif; ?>

        <ul class="nav nav-pills mb-4 justify-content-center bg-light p-1 rounded-pill" id="discTabs">
            <li class="nav-item flex-fill"><button class="nav-link active w-100 rounded-pill" data-bs-toggle="tab" data-bs-target="#tab-list">Records</button></li>
            <li class="nav-item flex-fill"><button class="nav-link w-100 rounded-pill" data-bs-toggle="tab" data-bs-target="#tab-stats">Stats</button></li>
        </ul>

        <div class="tab-content">
            <div class="tab-pane fade show active" id="tab-list">
                <div class="dashboard-card shadow-sm">
                    <div class="table-responsive">
                        <table class="table table-hover align-middle mb-0">
                            <thead class="bg-light small">
                                <tr><th class="ps-3">Student</th><th>Infraction</th><th class="text-end pe-3">Action</th></tr>
                            </thead>
                            <tbody>
                                <?php foreach ($records as $r): ?>
                                <tr>
                                    <td class="ps-3">
                                        <div class="fw-bold"><?= htmlspecialchars($r['full_name']) ?></div>
                                        <div class="small text-muted"><?= htmlspecialchars($r['class_name']) ?></div>
                                    </td>
                                    <td>
                                        <span class="badge bg-<?= $r['severity'] == 'high' ? 'danger' : ($r['severity'] == 'medium' ? 'warning' : 'info') ?> rounded-pill mb-1"><?= ucfirst($r['severity']) ?></span>
                                        <div class="small fw-bold"><?= htmlspecialchars($r['infraction']) ?></div>
                                    </td>
                                    <td class="text-end pe-3">
                                        <button class="btn btn-sm btn-outline-primary rounded-pill" onclick='openEdit(<?= json_encode($r) ?>)'>Edit</button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="tab-pane fade" id="tab-stats">
                <div class="dashboard-card p-3">
                    <canvas id="trendChart" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="addModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form class="modal-content border-0 rounded-4" method="POST">
                <div class="modal-header border-0"><h5 class="fw-bold">New Record</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="action" value="add">
                    <div class="mb-3">
                        <label class="small fw-bold mb-1">Class</label>
                        <select class="form-select" id="add_class_id" onchange="loadStudents(this.value, 'add_student_id')">
                            <option value="">Select Class</option>
                            <?php foreach($all_classes as $c): ?><option value="<?= $c['id'] ?>"><?= $c['class_name'] ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold mb-1">Student</label>
                        <select class="form-select" name="student_id" id="add_student_id" required><option value="">Select Student</option></select>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold mb-1">Offense</label>
                        <select class="form-select" name="infraction" required>
                            <?php foreach($infraction_list as $inf): ?><option value="<?= $inf ?>"><?= $inf ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="row">
                        <div class="col-6 mb-3">
                            <label class="small fw-bold mb-1">Severity</label>
                            <select class="form-select" name="severity"><option value="low">Low</option><option value="medium">Medium</option><option value="high">High</option></select>
                        </div>
                        <div class="col-6 mb-3">
                            <label class="small fw-bold mb-1">Date</label>
                            <input type="date" class="form-control" name="date" value="<?= date('Y-m-d') ?>" required>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold mb-1">Notes</label>
                        <textarea class="form-control" name="description" rows="3"></textarea>
                    </div>
                </div>
                <div class="modal-footer border-0"><button type="submit" class="btn btn-primary w-100 rounded-pill">Save Case</button></div>
            </form>
        </div>
    </div>

    <div class="modal fade" id="editModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <form class="modal-content border-0 rounded-4" method="POST">
                <div class="modal-header border-0"><h5 class="fw-bold">Edit Record</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
                <div class="modal-body">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="record_id" id="edit_id">
                    <div class="mb-3"><label class="small fw-bold">Student</label><input type="text" class="form-control bg-light" id="edit_name" readonly></div>
                    <div class="mb-3">
                        <label class="small fw-bold">Offense</label>
                        <select class="form-select" name="infraction" id="edit_infraction">
                            <?php foreach($infraction_list as $inf): ?><option value="<?= $inf ?>"><?= $inf ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="small fw-bold">Severity</label>
                        <select class="form-select" name="severity" id="edit_severity"><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">Notes</label><textarea class="form-control" name="description" id="edit_desc" rows="3"></textarea></div>
                    <hr>
                    <button type="button" class="btn btn-link text-danger btn-sm p-0 w-100" onclick="confirmDelete()">Delete this record</button>
                </div>
                <div class="modal-footer border-0"><button type="submit" class="btn btn-primary w-100 rounded-pill">Update</button></div>
            </form>
        </div>
    </div>

    <form id="deleteForm" method="POST"><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_target"></form>

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

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        async function loadStudents(classId, targetId) {
            const select = document.getElementById(targetId);
            select.innerHTML = '<option value="">Loading...</option>';
            if(!classId) return select.innerHTML = '<option value="">Select Class First</option>';
            const res = await fetch(`dashboard_discipline.php?ajax=students&class_id=${classId}`);
            const data = await res.json();
            select.innerHTML = '<option value="">Select Student</option>';
            data.forEach(s => select.innerHTML += `<option value="${s.id}">${s.full_name}</option>`);
        }

        function openEdit(r) {
            document.getElementById('edit_id').value = r.id;
            document.getElementById('edit_name').value = r.full_name;
            document.getElementById('edit_infraction').value = r.infraction;
            document.getElementById('edit_severity').value = r.severity;
            document.getElementById('edit_desc').value = r.description;
            new bootstrap.Modal(document.getElementById('editModal')).show();
        }

        function confirmDelete() {
            if(confirm('Are you sure you want to delete this record?')) {
                document.getElementById('delete_target').value = document.getElementById('edit_id').value;
                document.getElementById('deleteForm').submit();
            }
        }

        new Chart(document.getElementById('trendChart'), {
            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', tension: 0.3 }]
            }
        });
    </script>
</body>
</html>