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

$uid = $_SESSION['user_id'];
$user_roles = array_filter(array_map('trim', explode(',', $_SESSION['role'] ?? '')));

// UPDATED: Added 'discipline_teacher' to the admin group so they can view any class
$is_admin = !empty(array_intersect($user_roles, ['admin', 'principal', 'assistant', 'discipline_teacher']));

$month = intval($_GET['month'] ?? date('n'));
$year  = intval($_GET['year'] ?? date('Y'));
$selected_class_id = $_GET['class_id'] ?? null;

// Cache theme once (avoid calling getHeaderTheme() inside CSS evaluation repeatedly)
$header_theme = '';
try { $header_theme = getHeaderTheme(); }
catch (Throwable $e) { $header_theme = 'linear-gradient(135deg,#3b82f6 0%,#60a5fa 100%)'; }

$my_class = null;
$all_classes = [];

// --- 1. DETERMINE CLASS ACCESS ---
if ($is_admin) {
    $all_classes = $pdo->query("SELECT id, class_name, form_level FROM classes ORDER BY form_level ASC, class_name ASC")->fetchAll(PDO::FETCH_ASSOC);

    if ($selected_class_id) {
        $stmt = $pdo->prepare("SELECT * FROM classes WHERE id = ?");
        $stmt->execute([$selected_class_id]);
        $my_class = $stmt->fetch(PDO::FETCH_ASSOC);
    } elseif (!empty($all_classes)) {
        $my_class = $all_classes[0];
    }
} else {
    $stmt = $pdo->prepare("SELECT * FROM classes WHERE class_teacher_id = ?");
    $stmt->execute([$uid]);
    $my_class = $stmt->fetch(PDO::FETCH_ASSOC);
}

// Security Stop
if (!$my_class) {
    die("<div class='container mt-5 text-center'><div class='alert alert-warning rounded-4 shadow-sm border-0'><strong>Access Denied</strong><br>You are not assigned as a Class Teacher.<br><a href='dashboard.php' class='btn btn-sm btn-dark mt-3 rounded-pill px-4'>Back to Dashboard</a></div></div>");
}

// --- Date boundaries (index-friendly) ---
$yearStart = sprintf('%04d-01-01', $year);
$yearEnd   = sprintf('%04d-12-31', $year);

// --- 2. FETCH STUDENTS FOR SELECTED CLASS ---
$s_stmt = $pdo->prepare("SELECT id, full_name, ic_number FROM students WHERE class_id = ? ORDER BY full_name ASC");
$s_stmt->execute([$my_class['id']]);
$students = $s_stmt->fetchAll(PDO::FETCH_ASSOC);

if (empty($students)) {
    $warning_list = [];
    $monthly_stats = [];
} else {
    // Build student maps
    $studentIds = array_column($students, 'id');
    $studentNameById = [];
    foreach ($students as $s) $studentNameById[(int)$s['id']] = $s['full_name'];

    // --- 3. FETCH ALL ABSENCES FOR CLASS IN ONE QUERY (NO N+1) ---
    // Over a year, for the selected class students, only absent dates.
    $placeholders = implode(',', array_fill(0, count($studentIds), '?'));
    $sql = "
        SELECT student_id, date
        FROM student_attendance
        WHERE status = 'absent'
          AND date BETWEEN ? AND ?
          AND student_id IN ($placeholders)
        ORDER BY student_id ASC, date ASC
    ";
    $params = array_merge([$yearStart, $yearEnd], $studentIds);
    $abs_stmt = $pdo->prepare($sql);
    $abs_stmt->execute($params);
    $rows = $abs_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Group absent dates by student_id as timestamps (faster diff checks)
    $absByStudent = [];
    foreach ($rows as $r) {
        $sid = (int)$r['student_id'];
        // normalize date -> midnight timestamp
        $ts = strtotime($r['date']);
        if ($ts) $absByStudent[$sid][] = $ts;
    }

    // --- 4. ANALYTICS LOGIC (computed in PHP, no extra queries) ---
    $warning_list = [];
    $monthly_stats = [];

    foreach ($studentIds as $sid) {
        $sid = (int)$sid;
        $datesTs = $absByStudent[$sid] ?? [];

        // A) WARNING LOGIC (Yearly)
        $consecutive = 0;
        $max_consecutive = 0;
        $last_ts = 0;

        foreach ($datesTs as $curr_ts) {
            if ($last_ts === 0) {
                $consecutive = 1;
            } else {
                $diffDays = ($curr_ts - $last_ts) / 86400;
                // If gap <= 3 days (Fri -> Mon is 3), treat as consecutive
                if ($diffDays <= 3) $consecutive++;
                else $consecutive = 1;
            }
            if ($consecutive > $max_consecutive) $max_consecutive = $consecutive;
            $last_ts = $curr_ts;
        }

        $cumulative = count($datesTs);

        $status_label = '';
        $action_needed = false;

        if ($max_consecutive >= 7) {
            $status_label = 'Amaran Terakhir (7 Days Consec)'; $action_needed = true;
        } elseif ($cumulative >= 60) {
            $status_label = 'Amaran Terakhir (60 Days Total)'; $action_needed = true;
        } elseif ($max_consecutive >= 3) {
            $status_label = 'Amaran Pertama (3 Days Consec)'; $action_needed = true;
        }

        if ($action_needed) {
            $warning_list[] = [
                'name' => $studentNameById[$sid] ?? 'Unknown',
                'consecutive' => $max_consecutive,
                'cumulative' => $cumulative,
                'label' => $status_label
            ];
        }

        // B) MONTHLY STATS (count within selected month)
        $month_absent = 0;
        foreach ($datesTs as $ts) {
            if ((int)date('n', $ts) === $month) $month_absent++;
        }

        $monthly_stats[] = [
            'name' => $studentNameById[$sid] ?? 'Unknown',
            'absent' => $month_absent
        ];
    }
}

$month_name = date('F', mktime(0, 0, 0, $month, 10));
?>
<!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>Analytics: <?= htmlspecialchars($my_class['class_name']) ?></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: <?= $header_theme ?>; --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; }
        .nav-pills .nav-link { border-radius: 12px; color: #64748b; font-weight: 600; padding: 10px; width: 100%; text-align: center; background: #f1f5f9; }
        .nav-pills .nav-link.active { background: #8B5CF6; color: white; }
        .warning-item { background: #fff5f5; border: 1px solid #fed7d7; border-radius: 16px; padding: 15px; margin-bottom: 10px; }
        .warning-badge { background: #c53030; color: white; font-size: 0.65rem; padding: 4px 8px; border-radius: 6px; text-transform: uppercase; font-weight: 700; }
        .stat-row { display: flex; justify-content: space-between; align-items: center; padding: 12px; border-bottom: 1px solid #f1f5f9; }
        .stat-row:last-child { border-bottom: none; }
    </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">Class Analysis</div>
            <div style="width: 24px;"></div>
        </div>

        <h2 class="mb-0 fw-bold"><?= htmlspecialchars($my_class['class_name']) ?></h2>
        <div class="opacity-75 small">Attendance & Warnings</div>
    </div>

    <div class="floating-card">

        <?php if($is_admin): ?>
        <form method="GET" class="mb-3">
            <div class="input-group">
                <span class="input-group-text bg-light border-0 ps-3 rounded-start-4"><i class="bi bi-people-fill"></i></span>
                <select name="class_id" class="form-select border-0 bg-light fw-bold rounded-end-4" onchange="this.form.submit()">
                    <?php foreach($all_classes as $c): ?>
                        <option value="<?= $c['id'] ?>" <?= ($my_class['id'] == $c['id']) ? 'selected' : '' ?>>
                            <?= htmlspecialchars($c['class_name']) ?> (F<?= htmlspecialchars($c['form_level']) ?>)
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <input type="hidden" name="month" value="<?= $month ?>">
            <input type="hidden" name="year" value="<?= $year ?>">
        </form>
        <?php endif; ?>

        <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
            <li class="nav-item col-6 pe-1" role="presentation">
                <button class="nav-link active" id="pills-warn-tab" data-bs-toggle="pill" data-bs-target="#pills-warn" type="button">Action Required</button>
            </li>
            <li class="nav-item col-6 ps-1" role="presentation">
                <button class="nav-link" id="pills-month-tab" data-bs-toggle="pill" data-bs-target="#pills-month" type="button">Monthly View</button>
            </li>
        </ul>

        <div class="tab-content" id="pills-tabContent">

            <div class="tab-pane fade show active" id="pills-warn">
                <div class="text-center mb-3">
                    <h6 class="fw-bold text-danger"><?= count($warning_list) ?> Students At Risk</h6>
                    <small class="text-muted">Based on MOE 3/7/60 Rule</small>
                </div>

                <?php if(empty($warning_list)): ?>
                    <div class="text-center py-4 text-muted small">
                        <i class="bi bi-shield-check display-4 text-success opacity-50"></i><br>
                        No students require warning letters.
                    </div>
                <?php else: ?>
                    <?php foreach($warning_list as $w): ?>
                        <div class="warning-item">
                            <div class="d-flex justify-content-between align-items-start mb-2">
                                <div class="fw-bold text-dark"><?= htmlspecialchars($w['name']) ?></div>
                                <span class="warning-badge"><?= htmlspecialchars($w['label']) ?></span>
                            </div>
                            <div class="d-flex justify-content-between text-muted small mb-3">
                                <span>Consecutive: <strong class="text-dark"><?= (int)$w['consecutive'] ?></strong></span>
                                <span>Total (Year): <strong class="text-dark"><?= (int)$w['cumulative'] ?></strong></span>
                            </div>
                            <button class="btn btn-dark w-100 btn-sm rounded-pill fw-bold" onclick="alert('Feature: Print PDF for <?= htmlspecialchars($w['name'], ENT_QUOTES) ?> would open here.')">
                                <i class="bi bi-file-earmark-pdf me-2"></i>Generate Surat Amaran
                            </button>
                        </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>

            <div class="tab-pane fade" id="pills-month">
                <form method="GET" class="row g-2 mb-3 align-items-center justify-content-center">
                    <?php if($is_admin): ?><input type="hidden" name="class_id" value="<?= (int)$my_class['id'] ?>"><?php endif; ?>

                    <div class="col-auto">
                        <select name="month" class="form-select form-select-sm fw-bold border-0 bg-light rounded-pill" onchange="this.form.submit()">
                            <?php for($m=1; $m<=12; $m++): ?>
                                <option value="<?= $m ?>" <?= $m==$month ? 'selected':'' ?>><?= date('F', mktime(0,0,0,$m,1)) ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div class="col-auto">
                        <select name="year" class="form-select form-select-sm fw-bold border-0 bg-light rounded-pill" onchange="this.form.submit()">
                            <?php for($y=date('Y'); $y>=2023; $y--): ?>
                                <option value="<?= $y ?>" <?= $year==$y?'selected':'' ?>><?= $y ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>

                    <?php if($is_admin): ?>
                        <input type="hidden" name="class_id" value="<?= (int)$my_class['id'] ?>">
                    <?php endif; ?>
                </form>

                <div class="bg-light rounded-4 p-2">
                    <?php foreach($monthly_stats as $stat):
                        $is_perfect = ((int)$stat['absent'] === 0);
                    ?>
                        <div class="stat-row">
                            <span class="small fw-bold text-dark"><?= htmlspecialchars($stat['name']) ?></span>
                            <?php if($is_perfect): ?>
                                <span class="badge bg-success bg-opacity-10 text-success rounded-pill">100%</span>
                            <?php else: ?>
                                <span class="small fw-bold text-danger"><?= (int)$stat['absent'] ?> Days Absent</span>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </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>
</body>
</html>
