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

$user_id = $_SESSION['user_id'];
$msg = ''; $msg_type = '';

// Load Leave Types from Settings
$leave_types_str = getSetting('leave_types', 'MC,CRK,Cuti Rehat,Other');
$leave_types = array_map('trim', explode(',', $leave_types_str));

// 1. SUBMIT LEAVE (MULTI-DAY)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $type = $_POST['leave_type'];
    $detail = trim($_POST['reason']);
    $notes = trim($_POST['relief_notes']);
    
    $final_reason = $type;
    if (!empty($detail)) $final_reason .= " - " . $detail;

    $attachment_path = null;
    
    if ($end_date < $start_date) {
        $msg = "End date cannot be before start date."; $msg_type = "danger";
    } else {
        try {
            // HANDLE FILE UPLOAD
            if (isset($_FILES['attachment']) && $_FILES['attachment']['error'] == 0) {
                $target_dir = "uploads/mc/";
                if (!is_dir($target_dir)) mkdir($target_dir, 0777, true);
                $ext = strtolower(pathinfo($_FILES["attachment"]["name"], PATHINFO_EXTENSION));
                if (in_array($ext, ['jpg', 'jpeg', 'png', 'pdf'])) {
                    $new_filename = "mc_" . $user_id . "_" . time() . "." . $ext;
                    if (move_uploaded_file($_FILES["attachment"]["tmp_name"], $target_dir . $new_filename)) {
                        $attachment_path = $target_dir . $new_filename;
                    }
                }
            }

            // LOOP DATES
            $current = strtotime($start_date);
            $end = strtotime($end_date);
            $count = 0;
            
            // TRANSACTION START
            $pdo->beginTransaction();

            while ($current <= $end) {
                $this_date = date('Y-m-d', $current);
                $check = $pdo->prepare("SELECT id FROM teacher_absences WHERE user_id=? AND absence_date=?");
                $check->execute([$user_id, $this_date]);
                
                if (!$check->fetch()) {
                    $stmt = $pdo->prepare("INSERT INTO teacher_absences (user_id, absence_date, reason, relief_notes, attachment, created_by) VALUES (?, ?, ?, ?, ?, ?)");
                    $stmt->execute([$user_id, $this_date, $final_reason, $notes, $attachment_path, $user_id]);
                    $count++;
                }
                $current = strtotime('+1 day', $current);
            }
            
            $pdo->commit();
            
            if ($count > 0) {
                $msg = "Leave submitted for $count day(s)."; $msg_type = "success";

                // --- START NOTIFICATION LOGIC ---
                $u_stmt = $pdo->prepare("SELECT full_name FROM users WHERE id = ?");
                $u_stmt->execute([$user_id]);
                $teacher_name = $u_stmt->fetchColumn() ?: 'A Teacher';

                $date_range = date('d M', strtotime($start_date)) . " - " . date('d M', strtotime($end_date));
                $notif_msg = "?? Leave Alert: $teacher_name applied for $type ($date_range)";
                $link = "admin_relief.php?date=$start_date&absent_teacher=$user_id"; 

                $rcpt_sql = "SELECT id, telegram_chat_id FROM users WHERE role LIKE '%admin%' OR role LIKE '%principal%' OR role LIKE '%timetable_coord%'";
                $recipients = $pdo->query($rcpt_sql)->fetchAll(PDO::FETCH_ASSOC);

                $ins_notif = $pdo->prepare("INSERT INTO notifications (user_id, message, link, is_read, created_at) VALUES (?, ?, ?, 0, NOW())");

                foreach ($recipients as $rcpt) {
                    $ins_notif->execute([$rcpt['id'], $notif_msg, $link]);

                    if (!empty($rcpt['telegram_chat_id'])) {
                        $tg_msg = "<b>Leave Application Alert</b>\n" .
                                  "?? <b>Name:</b> $teacher_name\n" .
                                  "?? <b>Date:</b> $date_range\n" .
                                  "?? <b>Reason:</b> $final_reason\n" .
                                  "?? <b>Note:</b> " . ($notes ?: 'None');
                        
                        if (function_exists('sendTelegram')) {
                            sendTelegram($tg_msg, $rcpt['telegram_chat_id']);
                        }
                    }
                }
                // --- END NOTIFICATION LOGIC ---

            } else {
                $msg = "Dates already recorded."; $msg_type = "warning";
            }

        } catch (Exception $e) { 
            if ($pdo->inTransaction()) $pdo->rollBack();
            $msg = "Error: " . $e->getMessage(); $msg_type = "danger"; 
        }
    }
}

// 2. DELETE LOGIC (UPDATED FOR GROUP DELETE)
if (isset($_GET['delete_group'])) {
    // Expects comma separated IDs: 101,102,103
    $ids = explode(',', $_GET['delete_group']);
    $ids = array_map('intval', $ids); // Sanitize
    $in  = str_repeat('?,', count($ids) - 1) . '?';
    
    // Append user_id to params for security (can only delete own)
    $params = $ids;
    $params[] = $user_id;

    $sql = "DELETE FROM teacher_absences WHERE id IN ($in) AND user_id = ?";
    $stmt = $pdo->prepare($sql);
    $stmt->execute($params);

    $msg = "Leave record(s) deleted."; $msg_type = "warning";
}

// 3. FETCH AND GROUP HISTORY (NEW LOGIC)
// Fetch raw rows (limit increased to allow grouping of recent sets)
$my_leaves = $pdo->prepare("SELECT * FROM teacher_absences WHERE user_id = ? ORDER BY absence_date DESC LIMIT 60");
$my_leaves->execute([$user_id]);
$raw_history = $my_leaves->fetchAll(PDO::FETCH_ASSOC);

$grouped_history = [];
$current_group = null;

foreach ($raw_history as $row) {
    // Check if this row belongs to the current group being built
    // Conditions: Same Reason AND Date is exactly 1 day before the group's current start date (since we iterate backwards)
    
    $is_continuous = false;
    if ($current_group) {
        $prev_date = strtotime('-1 day', strtotime($current_group['start_date']));
        $this_date = strtotime($row['absence_date']);
        
        if ($this_date == $prev_date && $row['reason'] == $current_group['reason']) {
            $is_continuous = true;
        }
    }

    if ($is_continuous) {
        // Extend current group backwards
        $current_group['start_date'] = $row['absence_date'];
        $current_group['ids'][] = $row['id'];
    } else {
        // Save previous group if exists
        if ($current_group) {
            $grouped_history[] = $current_group;
        }
        // Start new group
        $current_group = [
            'start_date' => $row['absence_date'],
            'end_date'   => $row['absence_date'],
            'reason'     => $row['reason'],
            'ids'        => [$row['id']]
        ];
    }
}
// Add the last remaining group
if ($current_group) {
    $grouped_history[] = $current_group;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Apply Leave</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 href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        :root { --primary-grad: <?= getHeaderTheme() ?>; --bg-color: #f8f9fd; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background-color: var(--bg-color); 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 0 20px; border-radius: 24px; padding: 20px; box-shadow: 0 15px 35px rgba(0,0,0,0.08); position: relative; z-index: 10; }
        .form-control, .form-select { border-radius: 12px; padding: 12px; border: 1px solid #e2e8f0; background-color: #f8fafc; }
        .history-item { display: flex; align-items: center; justify-content: space-between; padding: 12px 10px; border-bottom: 1px solid #f1f5f9; }
        .date-badge { background: #eff6ff; color: #3b82f6; border-radius: 12px; width: 55px; height: 55px; display: flex; flex-direction: column; align-items: center; justify-content: center; margin-right: 12px; flex-shrink: 0; }
        .date-day { font-size: 1.1rem; font-weight: 800; line-height: 1; }
        .date-month { font-size: 0.65rem; text-transform: uppercase; font-weight: 700; }
    </style>
</head>
<body>
    <div class="app-header">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <a href="dashboard.php" class="text-white"><i class="bi bi-arrow-left fs-4"></i></a>
            <div class="fw-bold">Apply Leave</div>
            <div style="width: 24px;"></div>
        </div>
        <div class="display-1 mb-2 opacity-50"><i class="bi bi-briefcase"></i></div>
        <p class="text-white-50 small mb-0">Submit leave applications</p>
    </div>

    <div class="floating-card">
        <?php if($msg): ?><div class="alert alert-<?= $msg_type ?> border-0 shadow-sm rounded-3 small mb-3 text-center"><?= $msg ?></div><?php endif; ?>
        <form method="POST" enctype="multipart/form-data">
            <h6 class="fw-bold text-dark mb-3">New Application</h6>
            <div class="row g-2 mb-3">
                <div class="col-6"><label class="form-label small fw-bold text-muted">From</label><input type="date" name="start_date" class="form-control text-center" required min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>"></div>
                <div class="col-6"><label class="form-label small fw-bold text-muted">Until</label><input type="date" name="end_date" class="form-control text-center" required min="<?= date('Y-m-d') ?>" value="<?= date('Y-m-d') ?>"></div>
            </div>
            <div class="mb-3"><label class="form-label small fw-bold text-muted">Type</label><select name="leave_type" class="form-select" required><?php foreach($leave_types as $type): ?><option value="<?= htmlspecialchars($type) ?>"><?= htmlspecialchars($type) ?></option><?php endforeach; ?></select></div>
            <div class="mb-3"><label class="form-label small fw-bold text-muted">Details</label><input type="text" name="reason" class="form-control" placeholder="e.g. Fever"></div>
            <div class="mb-3"><label class="form-label small fw-bold text-primary">Relief Notes</label><textarea name="relief_notes" class="form-control" rows="2" placeholder="Instructions..."></textarea></div>
            <div class="mb-4"><label class="form-label small fw-bold text-muted">Attachment</label><input type="file" name="attachment" class="form-control" accept=".pdf,.jpg,.png"></div>
            <button type="submit" class="btn btn-primary w-100 rounded-pill py-3 fw-bold shadow-sm" style="background: var(--primary-grad); border:none;">Submit Application</button>
        </form>
    </div>

    <div class="px-3 pb-4 mt-4">
        <h6 class="fw-bold text-muted ps-2 mb-3 small text-uppercase">Recent History</h6>
        <div class="bg-white rounded-4 shadow-sm p-2">
            <?php if(empty($grouped_history)): ?>
                <div class="text-center py-4 text-muted small">No records found.</div>
            <?php else: foreach($grouped_history as $group): 
                $sDate = strtotime($group['start_date']);
                $eDate = strtotime($group['end_date']);
                $isRange = ($sDate != $eDate);
                $ids_str = implode(',', $group['ids']);
            ?>
            <div class="history-item">
                <div class="d-flex align-items-center overflow-hidden">
                    <div class="date-badge">
                        <span class="date-day"><?= date('d', $sDate) ?></span>
                        <span class="date-month"><?= date('M', $sDate) ?></span>
                    </div>
                    <div class="overflow-hidden">
                        <div class="fw-bold text-dark text-truncate small"><?= htmlspecialchars($group['reason']) ?></div>
                        <div class="small text-muted" style="font-size:0.65rem;">
                            <?php if($isRange): ?>
                                <span class="badge bg-light text-dark border me-1">
                                    <?= date('d M', $sDate) ?> - <?= date('d M', $eDate) ?>
                                </span>
                            <?php else: ?>
                                <?= date('l', $sDate) ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <a href="?delete_group=<?= $ids_str ?>" class="btn btn-light text-danger btn-sm rounded-circle" onclick="return confirm('Delete this leave record?')"><i class="bi bi-trash"></i></a>
            </div>
            <?php endforeach; endif; ?>
        </div>
    </div>

    <?php include 'menu.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>