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

$user_id = $_SESSION['user_id'];
$start_date = $_GET['start_date'] ?? date('Y-m-01'); // Default: First day of this month
$end_date = $_GET['end_date'] ?? date('Y-m-d');   // Default: Today

$week_start = getSetting('week_start_day', 1);
$weekend_days = ($week_start == 1) ? [6, 7] : [5, 6]; 

// 1. GET ALL TEACHER SLOTS (Regular Timetable)
$stmt = $pdo->prepare("
    SELECT t.id, t.day_of_week, t.start_time, t.end_time, t.subject, c.class_name
    FROM timetable t
    JOIN classes c ON t.class_id = c.id
    WHERE t.teacher_id = ?
");
$stmt->execute([$user_id]);
$regular_slots = $stmt->fetchAll(PDO::FETCH_GROUP); // Group by Day of Week

// 2. GET HOLIDAYS & ABSENCES
$holidays = $pdo->query("SELECT start_date, end_date FROM school_holidays")->fetchAll();
$absences = $pdo->prepare("SELECT absence_date FROM teacher_absences WHERE user_id = ?");
$absences->execute([$user_id]);
$my_absences = $absences->fetchAll(PDO::FETCH_COLUMN);

// 3. GET RELIEF ASSIGNMENTS (Where I am the reliever)
$reliefs = $pdo->prepare("
    SELECT r.assignment_date, t.start_time, t.end_time, t.subject, c.class_name, t.id as tid
    FROM relief_assignments r
    JOIN timetable t ON r.timetable_id = t.id
    JOIN classes c ON t.class_id = c.id
    WHERE r.reliever_id = ? AND r.assignment_date BETWEEN ? AND ?
");
$reliefs->execute([$user_id, $start_date, $end_date]);
$my_reliefs = $reliefs->fetchAll(PDO::FETCH_GROUP); // Group by Date

// 4. GET MY ATTENDANCE LOGS
$logs_stmt = $pdo->prepare("SELECT DATE(scan_time) as d, timetable_id FROM attendance_logs WHERE user_id = ? AND scan_time BETWEEN ? AND ?");
$logs_stmt->execute([$user_id, "$start_date 00:00:00", "$end_date 23:59:59"]);
$my_logs = [];
foreach ($logs_stmt->fetchAll() as $l) {
    $my_logs[$l['d']][] = $l['timetable_id'];
}

// 5. CALCULATE MISSED CLASSES
$missed_list = [];
$total_classes = 0;
$total_missed = 0;

$current = strtotime($start_date);
$last = strtotime($end_date);

while ($current <= $last) {
    $date_str = date('Y-m-d', $current);
    $day_num = date('N', $current);
    
    // Skip if Weekend
    if (in_array($day_num, $weekend_days)) { $current = strtotime('+1 day', $current); continue; }
    
    // Skip if Holiday
    $is_holiday = false;
    foreach ($holidays as $h) { if ($date_str >= $h['start_date'] && $date_str <= $h['end_date']) { $is_holiday = true; break; } }
    if ($is_holiday) { $current = strtotime('+1 day', $current); continue; }
    
    // Skip if Teacher Absent
    if (in_array($date_str, $my_absences)) { $current = strtotime('+1 day', $current); continue; }
    
    // CHECK REGULAR SLOTS
    if (isset($regular_slots[$day_num])) {
        foreach ($regular_slots[$day_num] as $slot) {
            // Skip if I was relieved (someone else covered me) - Advanced logic, skipping for simplicity unless requested
            
            $total_classes++;
            if (!isset($my_logs[$date_str]) || !in_array($slot['id'], $my_logs[$date_str])) {
                $total_missed++;
                $missed_list[] = [
                    'date' => $date_str,
                    'time' => substr($slot['start_time'], 0, 5),
                    'class' => $slot['class_name'],
                    'subject' => $slot['subject'],
                    'type' => 'Regular'
                ];
            }
        }
    }

    // CHECK RELIEF SLOTS
    if (isset($my_reliefs[$date_str])) {
        foreach ($my_reliefs[$date_str] as $rel) {
            $total_classes++;
            if (!isset($my_logs[$date_str]) || !in_array($rel['tid'], $my_logs[$date_str])) {
                $total_missed++;
                $missed_list[] = [
                    'date' => $date_str,
                    'time' => substr($rel['start_time'], 0, 5),
                    'class' => $rel['class_name'],
                    'subject' => $rel['subject'],
                    'type' => 'Relief'
                ];
            }
        }
    }

    $current = strtotime('+1 day', $current);
}

$compliance_rate = ($total_classes > 0) ? round((($total_classes - $total_missed) / $total_classes) * 100) : 100;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Missing Class History</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <style>
        body { background-color: #f3f6f9; font-family: sans-serif; padding-bottom: 50px; }
        .header-card { background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%); color: white; padding: 30px 20px 50px 20px; border-radius: 0 0 25px 25px; margin-bottom: -30px; }
        .stat-card { background: white; border: 0; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); text-align: center; padding: 20px; height: 100%; }
        .missed-item { background: white; border-radius: 12px; padding: 15px; margin-bottom: 10px; border-left: 5px solid #dc3545; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
    </style>
</head>
<body>
    <div class="header-card shadow">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <h4 class="fw-bold mb-0">History</h4>
            <a href="dashboard.php" class="btn btn-sm btn-outline-light rounded-pill px-3">Back</a>
        </div>
        <div class="opacity-75 small">Missed Class Report</div>
    </div>

    <div class="container px-3">
        <div class="row g-3 mb-4">
            <div class="col-6"><div class="stat-card"><h2 class="fw-bold text-danger mb-0"><?= $total_missed ?></h2><small class="text-muted text-uppercase fw-bold">Missed</small></div></div>
            <div class="col-6"><div class="stat-card"><h2 class="fw-bold text-success mb-0"><?= $compliance_rate ?>%</h2><small class="text-muted text-uppercase fw-bold">Compliance</small></div></div>
        </div>

        <div class="card border-0 shadow-sm mb-4">
            <div class="card-body p-3">
                <form method="GET" class="row g-2">
                    <div class="col-5"><input type="date" name="start_date" class="form-control form-control-sm" value="<?= $start_date ?>"></div>
                    <div class="col-5"><input type="date" name="end_date" class="form-control form-control-sm" value="<?= $end_date ?>"></div>
                    <div class="col-2"><button class="btn btn-primary btn-sm w-100"><i class="bi bi-search"></i></button></div>
                </form>
            </div>
        </div>

        <h6 class="fw-bold text-muted ms-1 mb-3">Missed Sessions</h6>
        <?php if (empty($missed_list)): ?>
            <div class="text-center py-5 text-muted"><i class="bi bi-check-circle-fill text-success display-1 mb-3"></i><p>Great job! No missed classes in this period.</p></div>
        <?php else: ?>
            <?php foreach ($missed_list as $m): ?>
                <div class="missed-item">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <div class="fw-bold text-dark"><?= $m['subject'] ?></div>
                            <small class="text-muted"><?= $m['class'] ?> &bull; <?= $m['time'] ?></small>
                        </div>
                        <div class="text-end">
                            <div class="badge bg-danger mb-1"><?= $m['type'] ?></div>
                            <div class="small text-muted"><?= date('d M', strtotime($m['date'])) ?></div>
                        </div>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</body>
</html>