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

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

// 1. PERMISSION CHECK (Standardized)
$user_roles = explode(',', $_SESSION['role'] ?? '');
if (empty(array_intersect($user_roles, ['admin', 'timetable_coord', 'principal', 'assistant']))) {
    header("Location: dashboard.php"); exit;
}

// PARAMS
$month = isset($_GET['month']) ? intval($_GET['month']) : intval(date('m'));
$year = isset($_GET['year']) ? intval($_GET['year']) : intval(date('Y'));
$selected_date = $_GET['date'] ?? null;

// Handle Month Navigation Edge Cases
if ($month < 1) { $month = 12; $year--; }
if ($month > 12) { $month = 1; $year++; }

// FETCH MONTH DATA (Counts per day)
$stmt = $pdo->prepare("SELECT assignment_date, COUNT(*) as count FROM relief_assignments WHERE MONTH(assignment_date) = ? AND YEAR(assignment_date) = ? GROUP BY assignment_date");
$stmt->execute([$month, $year]);
$monthly_data = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// FETCH DAILY DETAILS
$daily_records = [];
if ($selected_date) {
    // Note: Removed 'created_by' join to prevent SQL errors if column doesn't exist
    $sql = "SELECT r.*, t.start_time, t.end_time, t.subject, c.class_name, 
            u_orig.full_name as original_teacher, 
            u_rel.full_name as reliever
            FROM relief_assignments r 
            JOIN timetable t ON r.timetable_id = t.id 
            JOIN classes c ON t.class_id = c.id 
            JOIN users u_orig ON t.teacher_id = u_orig.id 
            JOIN users u_rel ON r.reliever_id = u_rel.id 
            WHERE r.assignment_date = ? 
            ORDER BY t.start_time ASC";
            
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$selected_date]);
    $daily_records = $stmt->fetchAll();
}

$first_day = mktime(0,0,0,$month,1,$year);
$days_in_month = date('t',$first_day);
$offset = date('N',$first_day) - 1; 
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Relief Records</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <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: #f4f6f9; font-family: sans-serif; padding-bottom: 60px; }
        .class-header-card { background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%); color: white; border-radius: 0 0 20px 20px; padding: 30px 20px 40px 20px; margin-bottom: 20px; }
        /* CALENDAR */
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 8px; }
        .cal-cell { background: white; border-radius: 10px; min-height: 70px; padding: 5px; border: 1px solid #e9ecef; cursor: pointer; transition: 0.2s; position: relative; }
        .cal-cell:hover { border-color: #0d6efd; transform: translateY(-2px); }
        .cal-cell.active { background: #e7f1ff; border: 2px solid #0d6efd; }
        .cal-cell.empty { background: transparent; border: none; cursor: default; }
        .day-num { font-weight: bold; font-size: 0.9rem; color: #495057; display: block; }
        /* RECORD LIST */
        .record-card { background: white; border-radius: 12px; padding: 15px; margin-bottom: 10px; border-left: 4px solid #0d6efd; box-shadow: 0 2px 5px rgba(0,0,0,0.02); }
    </style>
</head>
<body class="container-fluid p-0">

    <div class="class-header-card shadow no-print">
        <div class="d-flex justify-content-between align-items-center mb-2">
            <div><small class="text-white-50 fw-bold text-uppercase">Admin Panel</small></div>
            <div>
                <button onclick="window.print()" class="btn btn-sm btn-outline-light rounded-pill px-3 me-1">Print</button>
                <a href="admin_relief.php" class="btn btn-sm btn-outline-light rounded-pill px-3">Back</a>
            </div>
        </div>
        <h2 class="fw-bold mb-0">Relief History</h2>
        <div class="text-white-50 small">Archive of all substitute teacher assignments.</div>
    </div>

    <div class="container">
        <div class="row g-4">
            <div class="col-lg-5">
                <div class="card border-0 shadow-sm">
                    <div class="card-header bg-white d-flex justify-content-between align-items-center py-3 border-0">
                        <a href="?month=<?= $month-1 ?>&year=<?= $year ?>" class="btn btn-sm btn-light rounded-circle shadow-sm"><i class="bi bi-chevron-left"></i></a>
                        <h5 class="fw-bold mb-0 text-uppercase text-primary"><?= date('F Y', $first_day) ?></h5>
                        <a href="?month=<?= $month+1 ?>&year=<?= $year ?>" class="btn btn-sm btn-light rounded-circle shadow-sm"><i class="bi bi-chevron-right"></i></a>
                    </div>
                    <div class="card-body p-3 bg-light rounded-bottom">
                        <div class="d-flex justify-content-between text-center small fw-bold text-muted mb-2 px-1">
                            <span>Mon</span><span>Tue</span><span>Wed</span><span>Thu</span><span>Fri</span><span>Sat</span><span>Sun</span>
                        </div>
                        <div class="cal-grid">
                            <?php
                            // Empty cells for offset
                            for ($i=0; $i<$offset; $i++) echo '<div class="cal-cell empty"></div>';
                            
                            // Days
                            for ($d=1; $d<=$days_in_month; $d++) {
                                $date_str = sprintf("%04d-%02d-%02d", $year, $month, $d);
                                $count = $monthly_data[$date_str] ?? 0;
                                $is_active = ($date_str == $selected_date) ? 'active' : '';
                                
                                echo "<div onclick=\"window.location='?month=$month&year=$year&date=$date_str'\" class='cal-cell $is_active'>";
                                echo "<span class='day-num'>$d</span>";
                                if($count > 0) echo "<div class='mt-1'><small class='badge bg-primary rounded-pill' style='font-size:0.6rem'>$count</small></div>";
                                echo "</div>";
                            }
                            ?>
                        </div>
                    </div>
                </div>
            </div>

            <div class="col-lg-7">
                <?php if($selected_date): ?>
                    <h5 class="fw-bold text-secondary mb-3">
                        Records for <span class="text-dark"><?= date('d F Y', strtotime($selected_date)) ?></span>
                    </h5>
                    
                    <?php if(empty($daily_records)): ?>
                        <div class="text-center py-5 text-muted border rounded bg-white">
                            <i class="bi bi-clipboard-x display-4 opacity-25"></i>
                            <p class="mt-2">No records found.</p>
                        </div>
                    <?php else: ?>
                        <?php foreach($daily_records as $r): ?>
                            <div class="record-card">
                                <div class="d-flex justify-content-between align-items-start mb-2">
                                    <span class="badge bg-light text-dark border"><?= substr($r['start_time'],0,5) ?> - <?= substr($r['end_time'],0,5) ?></span>
                                    <span class="badge bg-success bg-opacity-10 text-success border border-success px-2 rounded-pill">Assigned</span>
                                </div>
                                
                                <div class="row align-items-center">
                                    <div class="col-5">
                                        <div class="small text-muted text-uppercase fw-bold" style="font-size:0.65rem;">Absent</div>
                                        <div class="text-danger fw-bold text-truncate"><?= htmlspecialchars($r['original_teacher']) ?></div>
                                        <div class="small text-muted"><?= htmlspecialchars($r['class_name']) ?> (<?= htmlspecialchars($r['subject']) ?>)</div>
                                    </div>
                                    <div class="col-2 text-center text-muted">
                                        <i class="bi bi-arrow-right fs-4"></i>
                                    </div>
                                    <div class="col-5 text-end">
                                        <div class="small text-muted text-uppercase fw-bold" style="font-size:0.65rem;">Reliever</div>
                                        <div class="text-success fw-bold text-truncate"><?= htmlspecialchars($r['reliever']) ?></div>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    <?php endif; ?>

                <?php else: ?>
                    <div class="card border-0 shadow-sm h-100 bg-white d-flex align-items-center justify-content-center text-center p-5">
                        <div>
                            <i class="bi bi-calendar-touch text-primary display-1 opacity-25"></i>
                            <h5 class="mt-3 text-secondary">Select a date</h5>
                            <p class="text-muted small">Choose a date from the calendar to view details.</p>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>