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

// --- SECURITY HEADERS & CSRF ---
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));
}

$msg = '';
$msg_type = '';
$user_id = $_SESSION['user_id'];
$role = $_SESSION['role'];
$can_manage_others = hasRole(['admin', 'timetable_coord', 'principal', 'assistant']);
$back_link = ($role === 'teacher') ? 'dashboard.php' : 'admin_dashboard.php';

// --- 1. CALENDAR & FILTER LOGIC ---
$month = $_GET['month'] ?? date('m');
$year = $_GET['year'] ?? date('Y');
$sel_date = $_GET['date'] ?? null;

$first_day = mktime(0,0,0,$month,1,$year);
$days_in_month = date('t', $first_day);
$month_name = date('F Y', $first_day);
$week_start = getSetting('week_start_day', 1); 
$start_dow = date('N', $first_day);
$offset = ($week_start == 1) ? ($start_dow - 1) : ($start_dow % 7);

$cal_stmt = $pdo->prepare("SELECT absence_date, COUNT(*) as count FROM teacher_absences WHERE MONTH(absence_date) = ? AND YEAR(absence_date) = ? GROUP BY absence_date");
$cal_stmt->execute([$month, $year]);
$calendar_data = $cal_stmt->fetchAll(PDO::FETCH_KEY_PAIR);

// --- 2. FETCH TODAY'S DATA ---
$today_sql = "SELECT a.*, u.full_name, u.phone_number FROM teacher_absences a JOIN users u ON a.user_id = u.id WHERE a.absence_date = CURDATE() ORDER BY u.full_name ASC";
$today_list = $pdo->query($today_sql)->fetchAll();
$today_count = count($today_list);

// --- 3. AUTO-RELIEF FUNCTION (UPDATED) ---
function runAutoRelief($pdo, $absent_id, $date) {
    $day_num = date('N', strtotime($date));
    $max_load = 2;

    // Get slots needed
    $slots_sql = "SELECT t.*, c.floor_level FROM timetable t JOIN classes c ON t.class_id = c.id WHERE t.teacher_id = ? AND t.day_of_week = ?";
    $slots_stmt = $pdo->prepare($slots_sql);
    $slots_stmt->execute([$absent_id, $day_num]);
    $missing_slots = $slots_stmt->fetchAll();

    // Get Candidates with Health Info
    $sql = "SELECT id, position_rank, is_pregnant, mobility_status FROM users WHERE role != 'student' AND exclude_relief = 0 AND id NOT IN (SELECT user_id FROM teacher_absences WHERE absence_date = ?)";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$date]);
    $candidates = $stmt->fetchAll();

    foreach ($missing_slots as $slot) {
        // Check if already covered
        $check = $pdo->prepare("SELECT id FROM relief_assignments WHERE timetable_id=? AND assignment_date=?");
        $check->execute([$slot['id'], $date]);
        if($check->fetch()) continue;

        $best_candidate = null; 
        $lowest_score = 9999;

        foreach ($candidates as $cand) {
            $tid = $cand['id'];

            // 1. FLOOR CHECK
            if ($slot['floor_level'] >= 2) {
                if ($cand['is_pregnant'] || $cand['mobility_status'] != 'fit') continue;
            }

            // 2. BUSY CHECK
            $busy = $pdo->prepare("SELECT 1 FROM timetable WHERE teacher_id=? AND day_of_week=? AND start_time < ? AND end_time > ?");
            $busy->execute([$tid, $day_num, $slot['end_time'], $slot['start_time']]); // Simplified overlap
            if ($busy->fetch()) continue;

            // 3. SCORE (simplified for auto-relief)
            $load = $pdo->prepare("SELECT COUNT(*) FROM relief_assignments WHERE reliever_id=? AND assignment_date=?");
            $load->execute([$tid, $date]); 
            $current_load = $load->fetchColumn();

            if ($current_load >= $max_load) continue;

            // Simple score: Load + Rank Penalty
            $score = ($current_load * 10) + ($cand['position_rank'] * 5);

            if ($score < $lowest_score) {
                $lowest_score = $score;
                $best_candidate = $tid;
            }
        }

        if ($best_candidate) {
            $pdo->prepare("INSERT INTO relief_assignments (timetable_id, reliever_id, assignment_date, created_by) VALUES (?,?,?,?)")->execute([$slot['id'], $best_candidate, $date, 0]);
            
            // Trigger Telegram here if needed (omitted for brevity)
        }
    }
}

// --- 4. HANDLE ACTIONS (SECURED) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // CSRF Check
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die("Security Alert: Invalid Request (CSRF).");
    }

    // Insert Action
    if (isset($_POST['action']) && $_POST['action'] === 'report') {
        $target_id = $_POST['user_id'] ?? $user_id; 
        $date = $_POST['date'];
        $reason = trim($_POST['reason']);

        if ($target_id != $user_id && !$can_manage_others) die("Access Denied");

        $cutoff_time = getSetting('absence_cutoff_time', '07:30');
        if ($date == date('Y-m-d') && date('H:i') > $cutoff_time && !$can_manage_others) {
            $msg = "Reporting closed for today."; $msg_type = "danger";
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO teacher_absences (user_id, absence_date, reason, created_by) VALUES (?, ?, ?, ?)");
                $stmt->execute([$target_id, $date, $reason, $user_id]);
                if (getSetting('relief_mode') === 'auto') { runAutoRelief($pdo, $target_id, $date); $msg = "Absence recorded. Auto-relief assigned."; } 
                else { $msg = "Absence recorded."; }
                $msg_type = "success";
                $today_list = $pdo->query($today_sql)->fetchAll(); $today_count = count($today_list);
            } catch (PDOException $e) { $msg = "Error: " . $e->getMessage(); $msg_type = "danger"; }
        }
    }

    // Delete Action
    if (isset($_POST['action']) && $_POST['action'] === 'delete') {
        $id = $_POST['delete_id'];
        $pdo->prepare("DELETE FROM teacher_absences WHERE id=?")->execute([$id]);
        $msg = "Record deleted."; $msg_type = "warning";
        $today_list = $pdo->query($today_sql)->fetchAll(); $today_count = count($today_list);
    }
}

// --- 5. FETCH LIST DATA ---
$teachers = $can_manage_others ? $pdo->query("SELECT id, full_name FROM users ORDER BY full_name ASC")->fetchAll() : [];

$list_sql = "SELECT a.*, u.full_name FROM teacher_absences a JOIN users u ON a.user_id = u.id WHERE 1=1";
$params = [];

if (!$can_manage_others) { $list_sql .= " AND a.user_id = ?"; $params[] = $user_id; }

if ($sel_date) {
    $list_sql .= " AND a.absence_date = ?"; $params[] = $sel_date;
} else {
    $list_sql .= " AND MONTH(a.absence_date) = ? AND YEAR(a.absence_date) = ?"; $params[] = $month; $params[] = $year;
}

$list_sql .= " ORDER BY a.absence_date DESC, u.full_name ASC";
$absences = $pdo->prepare($list_sql); $absences->execute($params); $rows = $absences->fetchAll();

$cutoff_display = getSetting('absence_cutoff_time', '07:30');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Manage Absences</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <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: #f4f6f9; font-family: sans-serif; padding-bottom: 80px; }
        .class-header-card { background: linear-gradient(135deg, #0d6efd 0%, #0a58ca 100%); color: white; border-radius: 0 0 20px 20px; padding: 25px 20px 30px 20px; margin-bottom: 20px; }
        .today-card { background: white; border-radius: 15px; box-shadow: 0 4px 15px rgba(0,0,0,0.05); margin-bottom: 20px; border-left: 5px solid #dc3545; }
        .today-empty { border-left-color: #198754; }
        .cal-container { background: white; border-radius: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); overflow: hidden; margin-bottom: 20px; }
        .cal-header { display: flex; justify-content: space-between; align-items: center; padding: 15px; border-bottom: 1px solid #f0f0f0; }
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); text-align: center; }
        .cal-day-name { font-size: 0.75rem; color: #adb5bd; font-weight: 700; padding: 10px 0; background: #f8f9fa; }
        .cal-day { aspect-ratio: 1/1; display: flex; flex-direction: column; align-items: center; justify-content: center; font-size: 0.9rem; font-weight: 600; color: #495057; border-bottom: 1px solid #f0f0f0; border-right: 1px solid #f0f0f0; cursor: pointer; position: relative; transition: 0.2s; }
        .cal-day:hover { background-color: #f0f7ff; color: #0d6efd; }
        .cal-day.active { background-color: #0d6efd; color: white; }
        .cal-day.today { color: #0d6efd; font-weight: 900; }
        .cal-dot { width: 6px; height: 6px; background-color: #dc3545; border-radius: 50%; margin-top: 4px; }
        .list-container { background: white; border-radius: 15px; box-shadow: 0 2px 10px rgba(0,0,0,0.03); overflow: hidden; }
        .absence-row { display: flex; align-items: center; justify-content: space-between; padding: 12px 15px; border-bottom: 1px solid #f0f0f0; }
        .date-box { background: #e7f1ff; color: #0d6efd; border-radius: 10px; width: 50px; height: 50px; display: flex; flex-direction: column; align-items: center; justify-content: center; line-height: 1; flex-shrink: 0; margin-right: 15px; }
        .date-box .day { font-size: 1.1rem; font-weight: 800; }
        .date-box .month { font-size: 0.65rem; text-transform: uppercase; font-weight: 600; }
        .btn-icon-sm { width: 36px; height: 36px; border-radius: 10px; display: flex; align-items: center; justify-content: center; background: #f8f9fa; border: 1px solid #dee2e6; color: #6c757d; text-decoration: none; cursor: pointer; border: none; }
        @media print { .no-print { display: none !important; } }
    </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>
            <a href="<?= $back_link ?>" class="btn btn-sm btn-outline-light rounded-pill px-3">Back</a>
        </div>
        <div class="d-flex flex-column flex-md-row justify-content-between align-items-md-end">
            <div>
                <h3 class="fw-bold mb-0">Absences</h3>
                <div class="text-white-50 small">Cut-off: <?= date('h:i A', strtotime($cutoff_display)) ?></div>
            </div>
            <div class="mt-3 mt-md-0 d-flex gap-2">
                <button onclick="window.print()" class="btn btn-outline-light btn-sm rounded-pill px-3 fw-bold">Print</button>
                <button class="btn btn-light btn-sm rounded-pill px-4 text-primary fw-bold shadow-sm" onclick="openModal()">+ Report</button>
            </div>
        </div>
    </div>

    <div class="container px-3">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> alert-dismissible fade show shadow-sm border-0 mb-3 small"><?= $msg ?><button type="button" class="btn-close" data-bs-dismiss="alert"></button></div><?php endif; ?>

        <div class="today-card <?= $today_count == 0 ? 'today-empty' : '' ?> no-print">
            <div class="p-3 border-bottom d-flex justify-content-between align-items-center">
                <h6 class="fw-bold mb-0 <?= $today_count > 0 ? 'text-danger' : 'text-success' ?>">
                    <?= $today_count > 0 ? '<i class="bi bi-exclamation-circle-fill me-2"></i>Absent Today' : '<i class="bi bi-check-circle-fill me-2"></i>All Present' ?>
                </h6>
                <span class="badge bg-light text-dark border"><?= date('d M Y') ?></span>
            </div>
            
            <?php if($today_count > 0): ?>
                <div class="list-group list-group-flush">
                    <?php foreach($today_list as $t): 
                        $hasProof = !empty($t['attachment']); $ext = $hasProof ? pathinfo($t['attachment'], PATHINFO_EXTENSION) : '';
                    ?>
                        <div class="list-group-item d-flex justify-content-between align-items-center py-3">
                            <div>
                                <div class="fw-bold text-dark"><?= htmlspecialchars($t['full_name']) ?></div>
                                <div class="small text-muted"><?= htmlspecialchars($t['reason']) ?></div>
                            </div>
                            <div class="d-flex gap-2">
                                <?php if($hasProof): ?>
                                    <button class="btn btn-sm btn-light border text-primary" onclick="viewProof('<?= $t['attachment'] ?>', '<?= $ext ?>')"><i class="bi bi-paperclip"></i></button>
                                <?php endif; ?>
                                <button class="btn btn-sm btn-light border text-danger" onclick="confirmDelete(<?= $t['id'] ?>)"><i class="bi bi-trash"></i></button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php else: ?>
                <div class="p-4 text-center text-muted small">
                    No staff absences recorded for today.
                </div>
            <?php endif; ?>
        </div>

        <div class="cal-container no-print">
            <div class="cal-header">
                <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>
                <div class="fw-bold text-primary text-uppercase"><?= $month_name ?></div>
                <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="cal-grid bg-light">
                <?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>"; ?>
            </div>
            <div class="cal-grid">
                <?php
                for ($i=0; $i<$offset; $i++) echo "<div class='cal-day empty'></div>";
                for ($d=1; $d<=$days_in_month; $d++) {
                    $date_str = sprintf("%04d-%02d-%02d", $year, $month, $d);
                    $has_rec = isset($calendar_data[$date_str]);
                    $cls = ($date_str == date('Y-m-d')) ? 'today' : '';
                    if ($date_str == $sel_date) $cls .= ' active';
                    echo "<div class='cal-day $cls' onclick=\"window.location='?month=$month&year=$year&date=$date_str'\"><span>$d</span>".($has_rec ? "<div class='cal-dot'></div>" : "")."</div>";
                }
                ?>
            </div>
            <?php if($sel_date): ?>
                <div class="p-2 bg-light text-center border-top">
                    <a href="?month=<?= $month ?>&year=<?= $year ?>" class="btn btn-sm btn-outline-secondary rounded-pill px-3" style="font-size: 0.75rem;">Clear Filter</a>
                </div>
            <?php endif; ?>
        </div>

        <h6 class="fw-bold text-secondary ms-2 mb-2 d-print-none"><?= $sel_date ? "Records: ".date('d M', strtotime($sel_date)) : "History ($month_name)" ?></h6>
        <div class="d-none d-print-block mb-3"><h3>Absence Report</h3><p>Period: <?= $month_name ?></p><hr></div>

        <div class="list-container">
            <?php foreach($rows as $row): 
                $ts = strtotime($row['absence_date']); $hasProof = !empty($row['attachment']); $ext = $hasProof ? pathinfo($row['attachment'], PATHINFO_EXTENSION) : '';
            ?>
                <div class="absence-row">
                    <div class="d-flex align-items-center overflow-hidden pe-2">
                        <div class="date-box">
                            <span class="day"><?= date('d', $ts) ?></span>
                            <span class="month"><?= date('M', $ts) ?></span>
                        </div>
                        <div class="overflow-hidden">
                            <div class="fw-bold text-dark text-truncate"><?= htmlspecialchars($row['full_name']) ?></div>
                            <div class="small text-muted text-truncate"><?= htmlspecialchars($row['reason']) ?></div>
                        </div>
                    </div>
                    <div class="d-flex gap-2 ms-2 no-print">
                        <?php if($hasProof): ?>
                            <button class="btn-icon-sm" style="color:#0d6efd" onclick="viewProof('<?= $row['attachment'] ?>', '<?= $ext ?>')"><i class="bi bi-paperclip"></i></button>
                        <?php endif; ?>
                        <button class="btn-icon-sm text-danger" onclick="confirmDelete(<?= $row['id'] ?>)"><i class="bi bi-trash"></i></button>
                    </div>
                </div>
            <?php endforeach; ?>
            <?php if(empty($rows)): ?><div class="text-center py-5 text-muted small">No absences found.</div><?php endif; ?>
        </div>
    </div>

    <div class="modal fade" id="absenceModal" tabindex="-1"><div class="modal-dialog modal-dialog-centered"><div class="modal-content border-0 shadow"><div class="modal-header bg-primary text-white"><h6 class="modal-title fw-bold">Report Absence</h6><button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button></div>
    <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
        <input type="hidden" name="action" value="report">
        <div class="modal-body p-4"><?php if ($can_manage_others): ?><div class="mb-3"><label class="small fw-bold">Teacher</label><select name="user_id" class="form-select bg-light border-0" required><option value="">Select...</option><?php foreach($teachers as $t): ?><option value="<?= $t['id'] ?>"><?= htmlspecialchars($t['full_name']) ?></option><?php endforeach; ?></select></div><?php else: ?><input type="hidden" name="user_id" value="<?= $user_id ?>"><?php endif; ?><div class="mb-3"><label class="small fw-bold">Date</label><input type="date" name="date" class="form-control bg-light border-0" required min="<?= date('Y-m-d') ?>"></div><div class="mb-2"><label class="small fw-bold">Reason</label><textarea name="reason" class="form-control bg-light border-0" rows="3" required></textarea></div></div><div class="modal-footer bg-light p-2 border-0"><button class="btn btn-primary w-100 fw-bold rounded-pill">Submit</button></div>
    </form>
    </div></div></div>

    <form id="deleteForm" method="POST" style="display:none">
        <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_id">
    </form>

    <div class="modal fade" id="proofModal" tabindex="-1"><div class="modal-dialog modal-lg modal-dialog-centered"><div class="modal-content border-0 shadow"><div class="modal-header bg-dark text-white py-2"><h6 class="modal-title small">Evidence</h6><button type="button" class="btn-close btn-close-white btn-sm" data-bs-dismiss="modal"></button></div><div class="modal-body p-0 bg-light text-center" style="min-height: 300px; max-height: 80vh; overflow: auto;"><div id="proofContainer" class="d-flex align-items-center justify-content-center h-100 p-3"></div></div><div class="modal-footer bg-white p-2"><a id="downloadBtn" href="#" target="_blank" class="btn btn-primary btn-sm rounded-pill px-3">Download</a></div></div></div></div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        const absenceModal = new bootstrap.Modal(document.getElementById('absenceModal'));
        const proofModal = new bootstrap.Modal(document.getElementById('proofModal'));
        function openModal() { absenceModal.show(); }
        function confirmDelete(id) {
            if(confirm("Are you sure you want to delete this record?")) {
                document.getElementById('delete_id').value = id;
                document.getElementById('deleteForm').submit();
            }
        }
        function viewProof(url, ext) {
            const container = document.getElementById('proofContainer');
            document.getElementById('downloadBtn').href = url;
            let content = '';
            if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext.toLowerCase())) { content = `<img src="${url}" class="img-fluid rounded shadow-sm" style="max-height: 60vh;">`; } 
            else if (ext.toLowerCase() === 'pdf') { content = `<iframe src="${url}" style="width:100%; height:60vh; border:none;"></iframe>`; } 
            else { content = `<div class="py-5 text-muted small">Preview not available.</div>`; }
            container.innerHTML = content; proofModal.show();
        }
    </script>
</body>
</html>