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

$msg = ''; $msg_type = '';
$user_id = $_SESSION['user_id'];
$user_roles = explode(',', $_SESSION['role'] ?? '');
$manage_roles = ['admin', 'timetable_coord', 'principal', 'assistant'];
$can_manage = !empty(array_intersect($user_roles, $manage_roles));

// Redirect logic
$back_link = $can_manage ? 'admin_dashboard.php' : 'dashboard.php';

// --- HELPER: AUTO-LINK ---
function makeLinksClickable($text) {
    return preg_replace('/\b(https?:\/\/[^\s]+)/i', '<a href="$1" target="_blank" class="text-primary text-decoration-underline" style="word-break: break-all;">$1</a>', htmlspecialchars($text));
}

// 1. HANDLE ACTIONS
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'report') {
    $target_id = $_POST['user_id'] ?? $user_id; 
    $date = $_POST['date'];
    $reason = trim($_POST['reason']);
    $notes = trim($_POST['relief_notes'] ?? '');
    $file_path = null;

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

    $cutoff = getSetting('absence_cutoff_time', '07:30');
    
    if ($date == date('Y-m-d') && date('H:i') > $cutoff && !$can_manage) {
        $msg = "Reporting closed for today (Cutoff: $cutoff). Contact Admin."; 
        $msg_type = "danger";
    } else {
        if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
            $dir = "uploads/mc/";
            if (!is_dir($dir)) mkdir($dir, 0777, true);
            $ext = strtolower(pathinfo($_FILES["attachment"]["name"], PATHINFO_EXTENSION));
            if (in_array($ext, ['jpg', 'jpeg', 'png', 'pdf'])) {
                $new_name = "mc_" . $target_id . "_" . time() . "." . $ext;
                if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $dir . $new_name)) $file_path = $dir . $new_name;
            }
        }

        try {
            $stmt = $pdo->prepare("INSERT INTO teacher_absences (user_id, absence_date, reason, relief_notes, attachment, created_by) VALUES (?, ?, ?, ?, ?, ?)");
            $stmt->execute([$target_id, $date, $reason, $notes, $file_path, $user_id]);
            $msg = "Absence recorded successfully."; 
            $msg_type = "success";
        } catch (Exception $e) { 
            $msg = "Error: " . $e->getMessage(); 
            $msg_type = "danger"; 
        }
    }
}

if (isset($_GET['delete_id'])) {
    $del_id = $_GET['delete_id'];
    $sql = "SELECT attachment FROM teacher_absences WHERE id = ?";
    if (!$can_manage) $sql .= " AND user_id = ?"; 
    
    $stmt = $pdo->prepare($sql);
    $stmt->execute($can_manage ? [$del_id] : [$del_id, $user_id]);
    $rec = $stmt->fetch();
    
    if ($rec) {
        if ($rec['attachment'] && file_exists($rec['attachment'])) unlink($rec['attachment']);
        $pdo->prepare("DELETE FROM teacher_absences WHERE id = ?")->execute([$del_id]);
        $msg = "Record deleted."; $msg_type = "warning";
    }
}

// 2. FETCH DATA
$year = isset($_GET['year']) && is_numeric($_GET['year']) ? intval($_GET['year']) : intval(date('Y'));
$month = isset($_GET['month']) && is_numeric($_GET['month']) ? intval($_GET['month']) : intval(date('m'));

// Stats
$stat_today = $pdo->query("SELECT COUNT(*) FROM teacher_absences WHERE absence_date = CURRENT_DATE")->fetchColumn();
$stat_week = $pdo->query("SELECT COUNT(*) FROM teacher_absences WHERE YEARWEEK(absence_date, 1) = YEARWEEK(CURRENT_DATE, 1)")->fetchColumn();
$stat_month = $pdo->query("SELECT COUNT(*) FROM teacher_absences WHERE MONTH(absence_date) = MONTH(CURRENT_DATE) AND YEAR(absence_date) = YEAR(CURRENT_DATE)")->fetchColumn();

// Calendar Events
$holidays = $pdo->prepare("SELECT start_date, end_date, type, description FROM school_holidays WHERE YEAR(start_date) = ?");
$holidays->execute([$year]);
$cal_events = [];

foreach ($holidays->fetchAll() as $h) {
    $curr = strtotime($h['start_date']); $end = strtotime($h['end_date']);
    while ($curr <= $end) {
        $color = ($h['type'] == 'national') ? 'danger' : (($h['type'] == 'term') ? 'primary' : 'info');
        $cal_events[date('Y-m-d', $curr)][] = ['type' => 'holiday', 'desc' => $h['description'], 'color' => $color];
        $curr = strtotime('+1 day', $curr);
    }
}

$abs_stmt = $pdo->prepare("SELECT a.absence_date, u.full_name, a.reason, a.relief_notes, a.attachment FROM teacher_absences a JOIN users u ON a.user_id = u.id WHERE MONTH(a.absence_date) = ? AND YEAR(a.absence_date) = ?");
$abs_stmt->execute([$month, $year]);
$abs_details = [];

while ($row = $abs_stmt->fetch()) {
    $d = $row['absence_date'];
    $abs_details[$d][] = [
        'name' => $row['full_name'], 
        'reason' => $row['reason'],
        'notes' => $row['relief_notes'],
        'proof' => $row['attachment']
    ];
}
foreach ($abs_details as $d => $list) { 
    $cal_events[$d][] = ['type' => 'absent', 'count' => count($list)]; 
}

// History List
$list_sql = "SELECT a.*, u.full_name FROM teacher_absences a JOIN users u ON a.user_id = u.id ";
if (!$can_manage) $list_sql .= "WHERE a.user_id = $user_id ";
$list_sql .= "ORDER BY a.absence_date DESC LIMIT 50";
$absences = $pdo->query($list_sql)->fetchAll();

// Teacher List
$teachers = $can_manage ? $pdo->query("SELECT id, full_name FROM users WHERE role LIKE '%teacher%' ORDER BY full_name ASC")->fetchAll() : [];

// Calendar Vars
$week_start = intval(getSetting('week_start_day', 1));
$first_day = mktime(0,0,0,$month,1,$year);
$days_in_month = date('t', $first_day);
$start_dow = date('N', $first_day);
$offset = ($week_start == 1) ? ($start_dow - 1) : ($start_dow % 7);
?>
<!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>Absence Manager</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">

    <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;
        }

        /* SEGMENTED TABS (Updated 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 */
        .cal-grid { display: grid; grid-template-columns: repeat(7, 1fr); gap: 3px; text-align: center; margin-bottom: 5px; }
        .cal-day { 
            aspect-ratio: 1/1; display: flex; flex-direction: column; align-items: center; justify-content: center; 
            font-size: 0.9rem; font-weight: 700; border-radius: 12px; background: #f8fafc; 
            border: 1px solid transparent; position: relative; cursor: pointer; transition: 0.1s; 
        }
        .cal-day:active { transform: scale(0.95); background-color: #e0f2fe; }
        .cal-day.empty { background: transparent; cursor: default; }

        .bg-danger { background-color: #fee2e2 !important; color: #ef4444 !important; }
        .bg-primary { background-color: #e0f2fe !important; color: #0ea5e9 !important; }
        .bg-info { background-color: #f3e8ff !important; color: #8b5cf6 !important; }
        
        .abs-badge { 
            position: absolute; bottom: 2px; right: 2px; font-size: 0.6rem; 
            background: #f59e0b; color: white; width: 16px; height: 16px; 
            display: flex; align-items: center; justify-content: center; 
            border-radius: 50%; font-weight: 800; 
        }

        /* LIST ITEM */
        .list-item { 
            background: white; border-radius: 16px; padding: 15px; margin-bottom: 10px; 
            border: 1px solid #f1f5f9; border-left: 4px solid #8B5CF6; 
            box-shadow: 0 2px 5px rgba(0,0,0,0.02); transition: 0.2s;
        }
        .note-preview { font-size: 0.75rem; background: #fffbeb; color: #b45309; padding: 8px; border-radius: 8px; margin-top: 8px; display: block; border: 1px dashed #fcd34d; word-wrap: break-word; }

        /* FORM */
        .form-control, .form-select { border-radius: 12px; padding: 10px; border: 1px solid #e2e8f0; background: #f8fafc; font-size: 0.9rem; }
        .form-control:focus, .form-select:focus { border-color: #8B5CF6; background: white; box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.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="<?= $back_link ?>" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold fs-5">Absence Manager</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="opacity-75 small">Track & Report Leave</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-4 fw-bold"><?= $msg ?></div>
        <?php endif; ?>

        <div class="row g-2 mb-4">
            <div class="col-4">
                <div class="bg-light rounded-3 p-2 text-center border">
                    <div class="h4 fw-bold text-danger mb-0"><?= $stat_today ?></div>
                    <div class="small text-muted fw-bold" style="font-size:0.6rem;">TODAY</div>
                </div>
            </div>
            <div class="col-4">
                <div class="bg-light rounded-3 p-2 text-center border">
                    <div class="h4 fw-bold text-warning mb-0"><?= $stat_week ?></div>
                    <div class="small text-muted fw-bold" style="font-size:0.6rem;">WEEK</div>
                </div>
            </div>
            <div class="col-4">
                <div class="bg-light rounded-3 p-2 text-center border">
                    <div class="h4 fw-bold text-primary mb-0"><?= $stat_month ?></div>
                    <div class="small text-muted fw-bold" style="font-size:0.6rem;">MONTH</div>
                </div>
            </div>
        </div>

        <div class="nav nav-pills segmented-control" id="absTabs" role="tablist">
            <button class="nav-link active" id="tab-report-btn" data-bs-toggle="tab" data-bs-target="#report">Report</button>
            <button class="nav-link" id="tab-calendar-btn" data-bs-toggle="tab" data-bs-target="#calendar">Calendar</button>
            <button class="nav-link" id="tab-history-btn" data-bs-toggle="tab" data-bs-target="#history">History</button>
        </div>

        <div class="tab-content">
            
            <div class="tab-pane fade show active" id="report">
                <form method="POST" enctype="multipart/form-data">
                    <input type="hidden" name="action" value="report">
                    
                    <?php if ($can_manage): ?>
                        <div class="mb-3">
                            <label class="form-label text-muted">Teacher</label>
                            <select name="user_id" class="form-select" required>
                                <option value="">Select...</option>
                                <?php foreach($teachers as $t) echo "<option value='{$t['id']}'>{$t['full_name']}</option>"; ?>
                            </select>
                        </div>
                    <?php else: ?>
                        <input type="hidden" name="user_id" value="<?= $user_id ?>">
                        <div class="mb-3 p-3 bg-light rounded-3 border small text-center fw-bold text-primary">
                            Reporting for: <?= htmlspecialchars($_SESSION['full_name']) ?>
                        </div>
                    <?php endif; ?>
                    
                    <div class="row g-2 mb-3">
                        <div class="col-6">
                            <label class="form-label text-muted">Date</label>
                            <input type="date" name="date" class="form-control" required min="<?= date('Y-m-d') ?>">
                        </div>
                        <div class="col-6">
                            <label class="form-label text-muted">Proof</label>
                            <input type="file" name="attachment" class="form-control" accept=".jpg,.jpeg,.png,.pdf">
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label text-muted">Reason</label>
                        <textarea name="reason" class="form-control" rows="2" placeholder="e.g. Medical Leave (MC)" required></textarea>
                    </div>

                    <div class="mb-4">
                        <label class="form-label text-muted text-primary"><i class="bi bi-link-45deg me-1"></i>Relief Notes / MMI Links</label>
                        <textarea name="relief_notes" class="form-control" rows="2" placeholder="Paste links or homework here..."></textarea>
                    </div>

                    <button class="btn btn-primary w-100 fw-bold rounded-pill py-2 shadow-sm">Submit Report</button>
                </form>
            </div>

            <div class="tab-pane fade" id="calendar">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <a href="?month=<?=$month-1?>&year=<?=$year?>&tab=calendar" class="btn btn-sm btn-light rounded-circle shadow-sm"><i class="bi bi-chevron-left"></i></a>
                    <span class="fw-bold fs-5"><?= date("F Y", mktime(0,0,0,$month,1,$year)) ?></span>
                    <a href="?month=<?=$month+1?>&year=<?=$year?>&tab=calendar" class="btn btn-sm btn-light rounded-circle shadow-sm"><i class="bi bi-chevron-right"></i></a>
                </div>

                <div class="cal-grid">
                    <?php $days=['M','T','W','T','F','S','S']; foreach($days as $d) echo "<div class='small text-muted fw-bold text-uppercase py-1'>$d</div>"; 
                    for($i=0; $i<$offset; $i++) echo "<div></div>";
                    for($d=1; $d<=$days_in_month; $d++) {
                        $date_str = sprintf("%04d-%02d-%02d", $year, $month, $d);
                        $evs = $cal_events[$date_str] ?? [];
                        $day_class = ''; $abs_badge = '';
                        foreach($evs as $e) {
                            if($e['type'] == 'holiday') $day_class = "bg-{$e['color']}";
                            if($e['type'] == 'absent') $abs_badge = "<div class='abs-badge'>{$e['count']}</div>";
                        }
                        echo "<div class='cal-day $day_class' onclick=\"showDayDetails('$date_str')\"><span>$d</span>$abs_badge</div>";
                    } ?>
                </div>
                
                <div class="mt-3 text-center small text-muted fw-bold d-flex justify-content-center gap-3">
                    <span class="d-flex align-items-center"><div style="width:10px;height:10px;" class="bg-danger rounded-circle me-1"></div> Public</span>
                    <span class="d-flex align-items-center"><div style="width:10px;height:10px;" class="bg-primary rounded-circle me-1"></div> School</span>
                    <span class="d-flex align-items-center"><div style="width:10px;height:10px;" class="bg-warning rounded-circle me-1"></div> Absent</span>
                </div>
            </div>

            <div class="tab-pane fade" id="history">
                <?php if(empty($absences)): ?>
                    <div class="text-center py-5 text-muted opacity-50"><i class="bi bi-journal-x display-1"></i><br>No records found.</div>
                <?php else: ?>
                    <div class="d-flex flex-column gap-2">
                        <?php foreach($absences as $row): ?>
                            <div class="list-item">
                                <div class="d-flex justify-content-between align-items-start">
                                    <div class="w-100 me-2">
                                        <div class="fw-bold text-dark"><?= htmlspecialchars($row['full_name']) ?></div>
                                        <div class="small text-muted"><?= date('d M Y', strtotime($row['absence_date'])) ?> &bull; <?= htmlspecialchars($row['reason']) ?></div>
                                        <?php if(!empty($row['relief_notes'])): ?>
                                            <div class="note-preview"><i class="bi bi-chat-quote me-1"></i><?= makeLinksClickable($row['relief_notes']) ?></div>
                                        <?php endif; ?>
                                    </div>
                                    <div class="d-flex flex-column gap-1">
                                        <?php if($row['attachment']): ?>
                                            <a href="<?= $row['attachment'] ?>" target="_blank" class="btn btn-sm btn-light text-primary border rounded-circle"><i class="bi bi-file-earmark-text"></i></a>
                                        <?php endif; ?>
                                        <?php if($can_manage || $row['user_id'] == $user_id): ?>
                                            <a href="?delete_id=<?= $row['id'] ?>" class="btn btn-sm btn-light text-danger border rounded-circle" onclick="return confirm('Delete?')"><i class="bi bi-trash"></i></a>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>

        </div>
    </div>

    <div class="modal fade" id="dayModal" tabindex="-1">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content border-0 shadow rounded-4">
                <div class="modal-header bg-light border-0 py-3">
                    <h6 class="modal-title fw-bold text-dark"><i class="bi bi-calendar-event me-2 text-primary"></i>Absentees: <span id="modalDate"></span></h6>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <ul class="list-group list-group-flush" id="modalList"></ul>
                    <div id="modalEmpty" class="text-center py-5 text-muted d-none small">No absences recorded.</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>
        // Tab Persistence
        const urlParams = new URLSearchParams(window.location.search);
        if(urlParams.get('tab') === 'calendar') {
            const triggerEl = document.querySelector('#tab-calendar-btn');
            if(triggerEl) new bootstrap.Tab(triggerEl).show();
        }

        const absenceData = <?= json_encode($abs_details) ?>;
        const dayModal = new bootstrap.Modal(document.getElementById('dayModal'));

        function makeLinks(text) {
            if(!text) return '';
            var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
            return text.replace(exp,"<a href='$1' target='_blank' class='text-primary fw-bold text-decoration-underline'>LINK</a>");
        }

        function showDayDetails(dateStr) {
            const dateObj = new Date(dateStr);
            document.getElementById('modalDate').innerText = dateObj.toLocaleDateString('en-GB', { day: 'numeric', month: 'short' });
            const list = document.getElementById('modalList');
            const emptyMsg = document.getElementById('modalEmpty');
            list.innerHTML = '';

            if (absenceData[dateStr]) {
                emptyMsg.classList.add('d-none');
                absenceData[dateStr].forEach(item => {
                    const li = document.createElement('li');
                    li.className = 'list-group-item py-3';
                    
                    let proofBtn = item.proof ? `<a href="${item.proof}" target="_blank" class="badge bg-light text-primary border text-decoration-none ms-2">Proof</a>` : '';
                    let notesHtml = item.notes ? `<div class="small text-muted fst-italic mt-1 bg-light p-2 rounded border border-light">${makeLinks(item.notes)}</div>` : '';

                    li.innerHTML = `
                        <div class="d-flex justify-content-between align-items-center mb-1">
                            <span class="fw-bold text-dark">${item.name}</span>
                            <span class="badge bg-danger bg-opacity-10 text-danger">${item.reason}</span>
                        </div>
                        ${notesHtml}
                        <div class="text-end mt-1">${proofBtn}</div>
                    `;
                    list.appendChild(li);
                });
            } else {
                emptyMsg.classList.remove('d-none');
            }
            dayModal.show();
        }
    </script>
</body>
</html>