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

// 1. PERMISSION CHECK
$uid = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$allowed_roles = ['admin', 'timetable_coord', 'principal', 'assistant'];

if (empty(array_intersect($user_roles, $allowed_roles))) {
    header("Location: dashboard.php"); exit;
}

// --- SETTINGS & BASICS ---
$week_start = intval(getSetting('week_start_day', 1));
$today_str = date('Y-m-d');
$now_time = date('H:i:s');

// --- 2. FETCH DATA FOR DASHBOARD ---
$total_staff = $pdo->query("SELECT COUNT(*) FROM users WHERE role NOT LIKE '%student%'")->fetchColumn();
$total_subjects = $pdo->query("SELECT COUNT(*) FROM subjects")->fetchColumn();

$today_day = date('N');
$total_slots_today = $pdo->prepare("SELECT COUNT(*) FROM timetable WHERE day_of_week = ?");
$total_slots_today->execute([$today_day]);
$slots_count = $total_slots_today->fetchColumn();

$scans_today = $pdo->query("SELECT COUNT(*) FROM attendance_logs WHERE DATE(scan_time) = CURRENT_DATE")->fetchColumn();
$attendance_rate = ($slots_count > 0) ? round(($scans_today / $slots_count) * 100) : 0;

// LIVE MONITOR DATA
$rt_sql = "SELECT t.start_time, t.end_time, c.class_name, u.full_name, t.subject, al.scan_time 
           FROM timetable t 
           JOIN classes c ON t.class_id = c.id 
           JOIN users u ON t.teacher_id = u.id 
           LEFT JOIN attendance_logs al ON t.id = al.timetable_id AND DATE(al.scan_time) = CURRENT_DATE 
           WHERE t.day_of_week = ? AND ? BETWEEN t.start_time AND t.end_time 
           ORDER BY t.end_time ASC";
$rt_stmt = $pdo->prepare($rt_sql);
$rt_stmt->execute([$today_day, $now_time]);
$live_classes = $rt_stmt->fetchAll();

// CHARTS DATA
$top_absentees = $pdo->query("SELECT u.full_name, COUNT(*) as total FROM teacher_absences a JOIN users u ON a.user_id = u.id GROUP BY a.user_id ORDER BY total DESC LIMIT 5")->fetchAll();
$day_trends = $pdo->query("SELECT DAYNAME(absence_date) as day_name, COUNT(*) as total FROM teacher_absences GROUP BY day_name ORDER BY FIELD(day_name, 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')")->fetchAll();

// --- 3. DEMOGRAPHICS CALCULATIONS ---
$users = $pdo->query("SELECT full_name, username FROM users WHERE username IS NOT NULL AND username != '' AND role NOT LIKE '%student%'")->fetchAll();
$male_count = 0; $female_count = 0;
$ages = ['<30'=>0, '30-39'=>0, '40-49'=>0, '50+'=>0];
$curr_year = date('Y'); $curr_short_year = date('y'); 

foreach($users as $u) {
    $ic = preg_replace('/[^0-9]/', '', $u['username']);
    if(strlen($ic) == 12) {
        $last_digit = intval(substr($ic, -1));
        if ($last_digit % 2 != 0) { $male_count++; } else { $female_count++; }
        
        $yy = substr($ic, 0, 2);
        $birth_year = ($yy > $curr_short_year) ? intval("19" . $yy) : intval("20" . $yy);
        $age = $curr_year - $birth_year;

        if ($age < 30) $ages['<30']++;
        elseif ($age < 40) $ages['30-39']++;
        elseif ($age < 50) $ages['40-49']++;
        else $ages['50+']++;
    }
}

// --- 4. CALENDAR LOGIC ---
$month = $_GET['month'] ?? date('m');
$year = $_GET['year'] ?? date('Y');
$filter_date = $_GET['date'] ?? date('Y-m-d');
$day_of_week_filter = date('N', strtotime($filter_date));

$first_day_timestamp = mktime(0,0,0, $month, 1, $year);
$days_in_mo = date('t', $first_day_timestamp);
$start_dow = date('N', $first_day_timestamp);
$blank_slots = ($week_start == 1) ? ($start_dow - 1) : ($start_dow % 7);

$list_sql = "SELECT t.start_time, t.end_time, c.class_name, u.full_name as teacher, al.scan_time 
             FROM timetable t 
             JOIN classes c ON t.class_id = c.id 
             JOIN users u ON t.teacher_id = u.id 
             LEFT JOIN attendance_logs al ON t.id = al.timetable_id AND DATE(al.scan_time) = ? 
             WHERE t.day_of_week = ? 
             ORDER BY t.start_time";
$stmt = $pdo->prepare($list_sql);
$stmt->execute([$filter_date, $day_of_week_filter]);
$daily_report = $stmt->fetchAll();
?>
<!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 Reports</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">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

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

        /* HEADER */
        .app-header {
            background: var(--primary-grad); padding: 30px 20px 80px 20px;
            border-radius: 0 0 35px 35px; color: white; text-align: center;
        }

        /* FLOATING CARD */
        .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;
        }

        /* STAT CARDS (Grid Layout Fix) */
        .stat-card {
            background: #f8fafc; border-radius: 16px; padding: 15px; text-align: center;
            border: 1px solid #f1f5f9; height: 100%; transition: transform 0.2s;
        }
        .stat-card:active { transform: scale(0.98); }
        .stat-card h3 { font-weight: 800; margin-bottom: 0; color: var(--text-dark); font-size: 1.5rem; }
        .stat-card small { font-weight: 700; font-size: 0.65rem; text-transform: uppercase; color: var(--text-gray); letter-spacing: 0.5px; }
        
        .st-blue { border-bottom: 4px solid #3b82f6; }
        .st-purple { border-bottom: 4px solid #8b5cf6; }
        .st-green { border-bottom: 4px solid #10b981; }
        .st-orange { border-bottom: 4px solid #f59e0b; }

        /* SEGMENTED CONTROL TABS (Fixed Design) */
        .segmented-control {
            background: #f1f5f9; padding: 4px; border-radius: 12px;
            display: flex; width: 100%; margin-bottom: 20px;
        }
        .segmented-control .nav-link { 
            flex: 1; border-radius: 10px; color: var(--text-gray); font-weight: 700; 
            padding: 10px 0; border: none; font-size: 0.85rem; transition: 0.2s;
            background: transparent;
        }
        .segmented-control .nav-link.active { 
            background: white; color: #8B5CF6; box-shadow: 0 2px 5px rgba(0,0,0,0.05); 
        }

        /* CALENDAR GRID */
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 5px; text-align: center; margin-bottom: 10px; }
        .cal-day-name { font-size: 0.7rem; color: #94a3b8; font-weight: 700; padding: 5px 0; }
        
        .cal-day { 
            background: #fff; aspect-ratio: 1/1; display: flex; flex-direction: column; 
            align-items: center; justify-content: center; font-size: 0.85rem; font-weight: 600; 
            color: var(--text-dark); border-radius: 12px; cursor: pointer; border: 1px solid #f1f5f9;
        }
        .cal-day:hover { border-color: #8B5CF6; z-index: 2; }
        .cal-day.active { background: #8B5CF6; color: white; box-shadow: 0 4px 10px rgba(139, 92, 246, 0.3); border-color: #8B5CF6; }
        .cal-day.empty { background: transparent; border: none; cursor: default; }

        /* LIST ITEM */
        .report-item { display: flex; align-items: center; padding: 12px 0; border-bottom: 1px solid #f1f5f9; }
        .report-item:last-child { border-bottom: none; }
        
        .chart-box { position: relative; height: 220px; width: 100%; }

        /* LIVE ROW */
        .live-row { 
            display: flex; align-items: center; justify-content: space-between; 
            padding: 12px 15px; background: white; border-radius: 12px; 
            margin-bottom: 8px; border: 1px solid #f1f5f9; 
        }
        .blink-dot { width: 8px; height: 8px; background: #ef4444; border-radius: 50%; display: inline-block; animation: pulse 1.5s infinite; }
        @keyframes pulse { 0% { opacity: 1; } 50% { opacity: 0.3; } 100% { opacity: 1; } }

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

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

    <div class="floating-card">
        
        <div class="nav nav-pills segmented-control" id="reportTabs" role="tablist">
            <button class="nav-link active" id="dash-tab" data-bs-toggle="tab" data-bs-target="#dashboard" type="button">Overview</button>
            <button class="nav-link" id="staff-tab" data-bs-toggle="tab" data-bs-target="#staff" type="button">Demographics</button>
        </div>

        <div class="tab-content">
            
            <div class="tab-pane fade show active" id="dashboard">
                
                <div class="row g-2 mb-4">
                    <div class="col-6 col-md-3">
                        <div class="stat-card st-blue">
                            <h3 class="text-primary"><?= $total_staff ?></h3>
                            <small>Staff Count</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="stat-card st-purple">
                            <h3 style="color:#8B5CF6;"><?= $total_subjects ?></h3>
                            <small>Subjects</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="stat-card st-green">
                            <h3 class="text-success"><?= $attendance_rate ?>%</h3>
                            <small>Scan Rate</small>
                        </div>
                    </div>
                    <div class="col-6 col-md-3">
                        <div class="stat-card st-orange">
                            <h3 class="text-warning"><?= count($live_classes) ?></h3>
                            <small>Active Now</small>
                        </div>
                    </div>
                </div>

                <div class="mb-4">
                    <h6 class="fw-bold text-dark mb-3 small text-uppercase"><i class="bi bi-broadcast me-2 text-danger"></i>Live Monitor</h6>
                    <?php if(empty($live_classes)): ?>
                        <div class="text-center py-4 bg-light rounded-4 text-muted small">No classes in session.</div>
                    <?php else: ?>
                        <?php foreach($live_classes as $row): ?>
                        <div class="live-row">
                            <div>
                                <div class="fw-bold text-dark small"><?= htmlspecialchars($row['class_name']) ?> &bull; <?= htmlspecialchars($row['subject']) ?></div>
                                <div class="text-muted" style="font-size:0.7rem;"><?= htmlspecialchars($row['full_name']) ?></div>
                            </div>
                            <div>
                                <?php if($row['scan_time']): ?>
                                    <span class="badge bg-success rounded-pill" style="font-size:0.6rem;">OK</span>
                                <?php else: ?>
                                    <span class="text-danger small fw-bold" style="font-size:0.65rem;"><span class="blink-dot me-1"></span>MISSING</span>
                                <?php endif; ?>
                            </div>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <div class="card border-0 shadow-sm rounded-4 mb-4">
                    <div class="card-header bg-white py-3 d-flex justify-content-between align-items-center">
                        <span class="fw-bold small text-uppercase">Daily Log</span>
                        <div class="d-flex align-items-center gap-2">
                            <a href="?month=<?= $month-1 ?>&year=<?= $year ?>&date=<?= $filter_date ?>" class="btn btn-light btn-sm rounded-circle"><i class="bi bi-chevron-left"></i></a>
                            <span class="small fw-bold"><?= date("M Y", strtotime("$year-$month-01")) ?></span>
                            <a href="?month=<?= $month+1 ?>&year=<?= $year ?>&date=<?= $filter_date ?>" class="btn btn-light btn-sm rounded-circle"><i class="bi bi-chevron-right"></i></a>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="cal-grid mb-3">
                            <?php $days = ($week_start==7) ? ['S','M','T','W','T','F','S'] : ['M','T','W','T','F','S','S']; foreach($days as $d) echo "<div class='cal-day-name'>$d</div>"; ?>
                            <?php
                            for($i=0; $i < $blank_slots; $i++) echo '<div class="cal-day empty"></div>';
                            for($d=1; $d<=$days_in_mo; $d++) {
                                $date_str = "$year-$month-".str_pad($d,2,'0',STR_PAD_LEFT);
                                $isActive = ($date_str == $filter_date) ? 'active' : '';
                                echo "<a href='?date=$date_str&month=$month&year=$year' class='text-decoration-none'><div class='cal-day $isActive'>$d</div></a>";
                            }
                            ?>
                        </div>

                        <div class="bg-light rounded-3 p-3">
                            <h6 class="small fw-bold text-muted mb-3 text-uppercase">Log: <?= date('d M Y', strtotime($filter_date)) ?></h6>
                            <?php if(empty($daily_report)): ?>
                                <div class="text-center text-muted small py-2">No records found.</div>
                            <?php else: ?>
                                <?php foreach($daily_report as $row): 
                                    $status_badge = '<span class="badge bg-danger">Miss</span>';
                                    if ($row['scan_time']) $status_badge = '<span class="badge bg-success">OK</span>';
                                    elseif ($filter_date > $today_str || ($filter_date == $today_str && $row['start_time'] > $now_time)) $status_badge = '<span class="badge bg-secondary">Wait</span>';
                                ?>
                                <div class="report-item">
                                    <div style="width: 50px;" class="small fw-bold text-dark"><?= substr($row['start_time'],0,5) ?></div>
                                    <div class="flex-grow-1 ps-2 overflow-hidden">
                                        <div class="small fw-bold text-truncate"><?= htmlspecialchars($row['class_name']) ?></div>
                                        <div class="text-muted text-truncate" style="font-size:0.7rem;"><?= htmlspecialchars($row['teacher']) ?></div>
                                    </div>
                                    <div><?= $status_badge ?></div>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>

                <div class="row g-4">
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 p-3">
                            <h6 class="small fw-bold text-muted mb-3 text-uppercase">Top Absentees</h6>
                            <div class="chart-box"><canvas id="chartAbsentees"></canvas></div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 p-3">
                            <h6 class="small fw-bold text-muted mb-3 text-uppercase">Weekly Trends</h6>
                            <div class="chart-box"><canvas id="chartDays"></canvas></div>
                        </div>
                    </div>
                </div>

            </div>

            <div class="tab-pane fade" id="staff">
                <div class="text-center mb-4">
                    <h5 class="fw-bold text-dark">Staff Demographics</h5>
                    <p class="small text-muted">Data derived from registered IC Numbers.</p>
                </div>

                <div class="row g-4 mb-4">
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 p-3 text-center">
                            <h6 class="small fw-bold text-muted mb-3 text-uppercase">Gender Ratio</h6>
                            <div class="chart-box" style="height: 200px;"><canvas id="chartGender"></canvas></div>
                            <div class="d-flex justify-content-center gap-3 mt-3 small fw-bold">
                                <span class="text-primary"><i class="bi bi-gender-male"></i> <?= $male_count ?> Male</span>
                                <span class="text-danger"><i class="bi bi-gender-female"></i> <?= $female_count ?> Female</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card border-0 shadow-sm rounded-4 p-3">
                            <h6 class="small fw-bold text-muted mb-3 text-uppercase text-center">Age Distribution</h6>
                            <div class="chart-box"><canvas id="chartAge"></canvas></div>
                        </div>
                    </div>
                </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>
    <script>
        const commonOptions = { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } } };
        
        // 1. ABSENTEES
        new Chart(document.getElementById('chartAbsentees'), { 
            type: 'bar', 
            data: { 
                labels: <?= json_encode(array_column($top_absentees, 'full_name')) ?>, 
                datasets: [{ data: <?= json_encode(array_column($top_absentees, 'total')) ?>, backgroundColor: '#ef4444', borderRadius: 6 }] 
            }, 
            options: commonOptions 
        });
        
        // 2. TRENDS
        new Chart(document.getElementById('chartDays'), { 
            type: 'line', 
            data: { 
                labels: <?= json_encode(array_column($day_trends, 'day_name')) ?>, 
                datasets: [{ data: <?= json_encode(array_column($day_trends, 'total')) ?>, borderColor: '#3b82f6', tension: 0.4, fill: true, backgroundColor: 'rgba(59,130,246,0.1)' }] 
            }, 
            options: commonOptions 
        });

        // 3. GENDER
        new Chart(document.getElementById('chartGender'), { 
            type: 'doughnut', 
            data: { 
                labels: ['Male', 'Female'], 
                datasets: [{ data: [<?= $male_count ?>, <?= $female_count ?>], backgroundColor: ['#3b82f6', '#ef4444'], borderWidth: 0 }] 
            }, 
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { position: 'bottom' } }, cutout: '70%' } 
        });

        // 4. AGE
        new Chart(document.getElementById('chartAge'), { 
            type: 'bar', 
            data: { 
                labels: <?= json_encode(array_keys($ages)) ?>, 
                datasets: [{ data: <?= json_encode(array_values($ages)) ?>, backgroundColor: ['#14b8a6', '#f59e0b', '#f97316', '#8b5cf6'], borderRadius: 6 }] 
            }, 
            options: commonOptions 
        });
    </script>
</body>
</html>