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

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

// -----------------------------------------
// API: GET AVAILABLE CANDIDATES (AJAX)
// -----------------------------------------
if (isset($_GET['action']) && $_GET['action'] === 'get_candidates') {
    header('Content-Type: application/json');
    
    $date = $_GET['date'];
    $day_num = date('N', strtotime($date));
    $start_time = $_GET['start'];
    $end_time = $_GET['end'];
    $req_subject = $_GET['subject'] ?? '';
    
    $max_daily = 2; // Hardcoded or fetch from settings

    // 1. Get List of "Experts" (Teachers who teach this subject)
    $expert_ids = [];
    if ($req_subject) {
        $stmt_exp = $pdo->prepare("SELECT DISTINCT teacher_id FROM timetable WHERE subject = ?");
        $stmt_exp->execute([$req_subject]);
        $expert_ids = $stmt_exp->fetchAll(PDO::FETCH_COLUMN);
    }

    // 2. Get all potential teachers
    $sql = "SELECT id, full_name, max_relief_weekly FROM users WHERE role LIKE '%teacher%' AND exclude_relief = 0 ORDER BY full_name";
    $candidates = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);
    
    $available = [];

    foreach ($candidates as $cand) {
        $cid = $cand['id'];
        $status = 'free'; // default

        // A. BUSY CHECK
        // Check if teaching SAME subject (Combined Opportunity)
        $busy_same = $pdo->prepare("SELECT id FROM timetable WHERE teacher_id = ? AND day_of_week = ? AND (start_time < ? AND end_time > ?) AND subject = ?");
        $busy_same->execute([$cid, $day_num, $end_time, $start_time, $req_subject]);
        
        if ($busy_same->fetch()) {
            $status = 'combine'; // Can combine classes
        } else {
            // Check if teaching DIFFERENT subject (Blocked)
            $busy_diff = $pdo->prepare("SELECT id FROM timetable WHERE teacher_id = ? AND day_of_week = ? AND (start_time < ? AND end_time > ?) AND subject != ?");
            $busy_diff->execute([$cid, $day_num, $end_time, $start_time, $req_subject]);
            if ($busy_diff->fetch()) continue; // Skip strictly busy teachers
        }

        // B. RELIEF CONFLICT
        $rel_busy = $pdo->prepare("SELECT r.id FROM relief_assignments r JOIN timetable t ON r.timetable_id = t.id WHERE r.reliever_id = ? AND r.assignment_date = ? AND (t.start_time < ? AND t.end_time > ?)");
        $rel_busy->execute([$cid, $date, $end_time, $start_time]);
        if ($rel_busy->fetch()) continue; // Already doing relief

        // C. LOAD CHECK
        $d_load = $pdo->prepare("SELECT COUNT(*) FROM relief_assignments WHERE reliever_id = ? AND assignment_date = ?");
        $d_load->execute([$cid, $date]);
        $daily_count = $d_load->fetchColumn();

        if ($daily_count >= $max_daily && $status !== 'combine') continue; // Hit limit (ignore limit for combine)

        $w_load = $pdo->prepare("SELECT COUNT(*) FROM relief_assignments WHERE reliever_id = ? AND YEARWEEK(assignment_date, 1) = YEARWEEK(?, 1)");
        $w_load->execute([$cid, $date]);
        $weekly_count = $w_load->fetchColumn();

        // D. DATA PREP
        $cand['daily_load'] = $daily_count;
        $cand['weekly_load'] = $weekly_count;
        $cand['status_tag'] = $status;
        $cand['is_expert'] = in_array($cid, $expert_ids); // Mark if they teach this subject
        
        $available[] = $cand;
    }

    // SORTING LOGIC
    usort($available, function($a, $b) {
        // 1. Combined Class Opportunities First
        if ($a['status_tag'] === 'combine' && $b['status_tag'] !== 'combine') return -1;
        if ($a['status_tag'] !== 'combine' && $b['status_tag'] === 'combine') return 1;

        // 2. Subject Experts Second
        if ($a['is_expert'] && !$b['is_expert']) return -1;
        if (!$a['is_expert'] && $b['is_expert']) return 1;

        // 3. Lowest Daily Load
        if ($a['daily_load'] != $b['daily_load']) return $a['daily_load'] <=> $b['daily_load'];
        
        // 4. Lowest Weekly Load
        return $a['weekly_load'] <=> $b['weekly_load'];
    });

    echo json_encode($available);
    exit;
}

// -----------------------------------------
// MAIN PAGE LOGIC
// -----------------------------------------
$msg = ''; $msg_type = '';
$date = $_GET['date'] ?? date('Y-m-d');
$day_num = date('N', strtotime($date));
$absent_teacher_id = $_GET['absent_teacher'] ?? '';

// 2. HANDLE POST ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'];
    
    if ($action === 'assign_relief') {
        $tid = $_POST['timetable_id'];
        $reliever_id = $_POST['reliever_id'];
        
        // Final Clash Check
        $slot_info = $pdo->prepare("SELECT start_time, end_time FROM timetable WHERE id = ?");
        $slot_info->execute([$tid]);
        $s_time = $slot_info->fetch();
        
        $stmt = $pdo->prepare("INSERT INTO relief_assignments (timetable_id, reliever_id, assignment_date, status) VALUES (?, ?, ?, 'assigned') ON DUPLICATE KEY UPDATE reliever_id = VALUES(reliever_id)");
        $stmt->execute([$tid, $reliever_id, $date]);
        $msg = "Relief assigned successfully."; $msg_type = "success";
    }
    
    if ($action === 'delete_relief') {
        $pdo->prepare("DELETE FROM relief_assignments WHERE id = ?")->execute([$_POST['relief_id']]);
        $msg = "Relief assignment removed."; $msg_type = "warning";
    }
}

// 3. FETCH DATA
$teachers = $pdo->query("SELECT id, full_name FROM users WHERE role LIKE '%teacher%' ORDER BY full_name")->fetchAll();

$slots = [];
if ($absent_teacher_id) {
    $sql = "SELECT t.*, c.class_name, 
            r.id as relief_id, r.reliever_id, u.full_name as reliever_name
            FROM timetable t 
            JOIN classes c ON t.class_id = c.id 
            LEFT JOIN relief_assignments r ON t.id = r.timetable_id AND r.assignment_date = ?
            LEFT JOIN users u ON r.reliever_id = u.id
            WHERE t.teacher_id = ? AND t.day_of_week = ? 
            ORDER BY t.start_time";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([$date, $absent_teacher_id, $day_num]);
    $slots = $stmt->fetchAll();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Relief Management</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <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: <?= getHeaderTheme() ?>; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: #f8f9fd; 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; }
        .slot-item { background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; border: 1px solid #f1f5f9; display: flex; align-items: center; justify-content: space-between; transition: transform 0.2s; }
        .slot-item:active { transform: scale(0.99); background: #f8fafc; }
        .slot-item.covered { border-left: 5px solid #10b981; }
        .slot-item.open { border-left: 5px solid #ef4444; }
        .time-box { width: 50px; text-align: center; line-height: 1.1; margin-right: 15px; }
        .time-start { font-weight: 800; font-size: 0.9rem; color: #333; }
        .time-end { font-size: 0.7rem; color: #94a3b8; }
        
        #loader { display: none; text-align: center; padding: 20px; }
        
        .candidate-item { cursor: pointer; transition: 0.2s; border: none; border-bottom: 1px solid #f1f5f9; }
        .candidate-item:hover { background-color: #f8fafc; }
        .candidate-item:last-child { border-bottom: none; }
        .candidate-item input:checked + div { color: #8B5CF6; font-weight: bold; }
        
        /* Badges */
        .badge-expert { background: #e0f2fe; color: #0284c7; border: 1px solid #bae6fd; font-size: 0.65rem; }
        .badge-combine { background: #dcfce7; color: #15803d; border: 1px solid #bbf7d0; font-size: 0.65rem; }
        .badge-load { background: #f3f4f6; color: #4b5563; font-size: 0.65rem; }

     /*   .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: white; padding: 10px 30px 25px 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">Relief Management</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Smart Assignment System</div>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 text-center small mb-3"><?= $msg ?></div><?php endif; ?>

        <form method="GET">
            <div class="mb-3">
                <label class="form-label">Date</label>
                <input type="date" name="date" class="form-control fw-bold" value="<?= $date ?>" onchange="this.form.submit()">
            </div>
            <div class="mb-2">
                <label class="form-label">Absent Teacher</label>
                <select name="absent_teacher" class="form-select fw-bold" onchange="this.form.submit()">
                    <option value="">Select Teacher...</option>
                    <?php foreach($teachers as $t): ?>
                        <option value="<?= $t['id'] ?>" <?= $absent_teacher_id == $t['id'] ? 'selected' : '' ?>><?= htmlspecialchars($t['full_name']) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
        </form>
    </div>

    <div class="px-3 pb-4">
        <?php if(!$absent_teacher_id): ?>
            <div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-person-x display-1"></i><br>Select an absent teacher.</div>
        <?php elseif(empty($slots)): ?>
            <div class="text-center py-5 text-muted small opacity-50"><i class="bi bi-calendar-check display-1"></i><br>No classes today.</div>
        <?php else: ?>
            <h6 class="fw-bold text-muted ps-2 mb-3 small text-uppercase">Schedule for <?= date('D, d M', strtotime($date)) ?></h6>
            <?php foreach($slots as $s): $is_covered = !empty($s['reliever_id']); ?>
            <div class="slot-item <?= $is_covered ? 'covered' : 'open' ?>" onclick='openAssignModal(<?= json_encode($s) ?>)'>
                <div class="d-flex align-items-center">
                    <div class="time-box">
                        <div class="time-start"><?= substr($s['start_time'],0,5) ?></div>
                        <div class="time-end"><?= substr($s['end_time'],0,5) ?></div>
                    </div>
                    <div>
                        <div class="fw-bold text-dark"><?= htmlspecialchars($s['subject']) ?></div>
                        <div class="small text-muted"><?= htmlspecialchars($s['class_name']) ?></div>
                    </div>
                </div>
                <div>
                    <?php if($is_covered): ?>
                        <span class="badge bg-success bg-opacity-10 text-success rounded-pill border border-success px-3"><?= htmlspecialchars(explode(' ', trim($s['reliever_name']))[0]) ?></span>
                    <?php else: ?>
                        <span class="badge bg-danger rounded-pill px-3">Assign</span>
                    <?php endif; ?>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <div class="modal fade" id="assignModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header border-0 bg-primary text-white">
                    <h6 class="modal-title fw-bold">Assign Relief</h6>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <div class="p-3 bg-light border-bottom">
                        <div class="fw-bold text-dark" id="modal_subject">Subject</div>
                        <div class="small text-muted" id="modal_time">Time</div>
                    </div>
                    
                    <form method="POST" id="assignForm" class="p-3">
                        <input type="hidden" name="action" value="assign_relief">
                        <input type="hidden" name="timetable_id" id="modal_tid">
                        <input type="hidden" name="date" value="<?= $date ?>">
                        
                        <label class="form-label mb-2 small fw-bold text-muted text-uppercase">Recommended Teachers</label>
                        
                        <div id="loader"><div class="spinner-border text-primary spinner-border-sm" role="status"></div></div>
                        <div id="candidateList" class="list-group list-group-flush rounded-3 border mb-3" style="max-height: 250px; overflow-y: auto;"></div>
                        
                        <button type="submit" class="btn btn-primary w-100 rounded-pill fw-bold" id="btnConfirm" disabled>Confirm Assignment</button>
                    </form>
                    
                    <form method="POST" id="deleteForm" class="px-3 pb-3" style="display:none;">
                        <input type="hidden" name="action" value="delete_relief">
                        <input type="hidden" name="relief_id" id="modal_rid">
                        <button type="submit" class="btn btn-light text-danger w-100 rounded-pill fw-bold border-danger" onclick="return confirm('Remove assignment?')">Remove Current Relief</button>
                    </form>
                </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 modal = new bootstrap.Modal(document.getElementById('assignModal'));
        const dateStr = "<?= $date ?>";

        function openAssignModal(slot) {
            document.getElementById('modal_tid').value = slot.id;
            document.getElementById('modal_subject').innerText = slot.subject + " (" + slot.class_name + ")";
            document.getElementById('modal_time').innerText = slot.start_time.substring(0,5) + " - " + slot.end_time.substring(0,5);
            
            const delForm = document.getElementById('deleteForm');
            const assignForm = document.getElementById('assignForm');
            const btnConfirm = document.getElementById('btnConfirm');
            const list = document.getElementById('candidateList');
            const loader = document.getElementById('loader');

            if (slot.relief_id) {
                document.getElementById('modal_rid').value = slot.relief_id;
                delForm.style.display = 'block';
                assignForm.style.display = 'none';
            } else {
                delForm.style.display = 'none';
                assignForm.style.display = 'block';
                list.innerHTML = '';
                loader.style.display = 'block';
                btnConfirm.disabled = true;

                // Added 'subject' to the API call for filtering
                fetch(`admin_relief.php?action=get_candidates&date=${dateStr}&start=${slot.start_time}&end=${slot.end_time}&subject=${encodeURIComponent(slot.subject)}`)
                    .then(response => response.json())
                    .then(data => {
                        loader.style.display = 'none';
                        if (data.length === 0) {
                            list.innerHTML = '<div class="p-3 text-center text-muted small">No available teachers found.</div>';
                        } else {
                            data.forEach(t => {
                                let badge = '';
                                
                                // Priority 1: Combined Class
                                if (t.status_tag === 'combine') {
                                    badge = `<span class="badge badge-combine rounded-pill ms-auto">Combine Class</span>`;
                                } 
                                // Priority 2: Subject Expert
                                else if (t.is_expert) {
                                    badge = `<span class="badge badge-expert rounded-pill ms-auto">${slot.subject} Teacher</span>`;
                                } 
                                // Priority 3: General Load
                                else {
                                    badge = `<span class="badge badge-load rounded-pill ms-auto">Load: ${t.daily_load}</span>`;
                                }
                                
                                const html = `
                                    <label class="list-group-item d-flex align-items-center candidate-item p-2">
                                        <input class="form-check-input me-3" type="radio" name="reliever_id" value="${t.id}" onchange="document.getElementById('btnConfirm').disabled = false" required>
                                        <div>
                                            <div class="fw-bold small text-dark">${t.full_name}</div>
                                            <div class="text-muted" style="font-size:0.65rem">Weekly: ${t.weekly_load} / ${t.max_relief_weekly}</div>
                                        </div>
                                        ${badge}
                                    </label>
                                `;
                                list.innerHTML += html;
                            });
                        }
                    })
                    .catch(err => {
                        console.error(err);
                        loader.style.display = 'none';
                        list.innerHTML = '<div class="p-3 text-center text-danger small">Error loading teachers.</div>';
                    });
            }
            modal.show();
        }
    </script>
</body>
</html>