<?php
session_start();

// Include access control functions
require_once '../includes/access_control.php';
require_once '../config/database.php';

// Check if user is logged in and is a teacher
require_teacher();

$user_role = $_SESSION['user_role'];
$user_id = $_SESSION['user_id'];
$user_name = $_SESSION['user_name'] ?? $_SESSION['username'] ?? 'শিক্ষক';

// Initialize variables
$error_message = '';
$success_message = '';

// Handle success message from PRG pattern
if (isset($_SESSION['success_message'])) {
    $success_message = $_SESSION['success_message'];
    unset($_SESSION['success_message']);
}

// Get teacher info
$teacher_info = null;
try {
    $stmt = $pdo->prepare("SELECT * FROM teachers WHERE user_id = ?");
    $stmt->execute([$user_id]);
    $teacher_info = $stmt->fetch();

    if (!$teacher_info) {
        $error_message = "শিক্ষক তথ্য পাওয়া যায়নি।";
    }
} catch (Exception $e) {
    $error_message = "ত্রুটি: " . $e->getMessage();
}

// Handle edit action for pending leaves
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'edit' && isset($_POST['leave_id'])) {
    $leave_id = (int)$_POST['leave_id'];
    $leave_type = $_POST['leave_type'] ?? '';
    $start_date = $_POST['start_date'] ?? '';
    $end_date = $_POST['end_date'] ?? '';
    $reason = trim($_POST['reason'] ?? '');

    if (!$teacher_info) {
        $error_message = "শিক্ষক তথ্য পাওয়া যায়নি।";
    } elseif (empty($leave_type) || empty($start_date) || empty($end_date) || empty($reason)) {
        $error_message = "সব ক্ষেত্র পূরণ করুন।";
    } elseif (strtotime($start_date) > strtotime($end_date)) {
        $error_message = "শুরুর তারিখ শেষ তারিখের চেয়ে বড় হতে পারে না।";
    } else {
        try {
            // Only allow editing of pending leaves by the owner
            $stmt = $pdo->prepare("UPDATE teacher_leaves SET leave_type = ?, start_date = ?, end_date = ?, reason = ?, updated_at = NOW() WHERE id = ? AND teacher_id = ? AND status = 'pending'");
            $result = $stmt->execute([$leave_type, $start_date, $end_date, $reason, $leave_id, $teacher_info['id']]);

            if ($result && $stmt->rowCount() > 0) {
                $_SESSION['success_message'] = "ছুটির আবেদন সফলভাবে আপডেট করা হয়েছে।";
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit();
            } else {
                $error_message = "আবেদন আপডেট করতে সমস্যা হয়েছে। শুধুমাত্র অমীমাংসিত আবেদন আপডেট করা যাবে।";
            }
        } catch (Exception $e) {
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}

// Handle delete action for pending leaves
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'delete' && isset($_POST['leave_id'])) {
    $leave_id = (int)$_POST['leave_id'];

    if (!$teacher_info) {
        $error_message = "শিক্ষক তথ্য পাওয়া যায়নি।";
    } else {
        try {
            // Only allow deletion of pending leaves by the owner
            $stmt = $pdo->prepare("DELETE FROM teacher_leaves WHERE id = ? AND teacher_id = ? AND status = 'pending'");
            $result = $stmt->execute([$leave_id, $teacher_info['id']]);

            if ($result && $stmt->rowCount() > 0) {
                $_SESSION['success_message'] = "ছুটির আবেদন সফলভাবে মুছে ফেলা হয়েছে।";
                header('Location: ' . $_SERVER['PHP_SELF']);
                exit();
            } else {
                $error_message = "আবেদন মুছে ফেলতে সমস্যা হয়েছে। শুধুমাত্র অমীমাংসিত আবেদন মুছে ফেলা যাবে।";
            }
        } catch (Exception $e) {
            $error_message = "ত্রুটি: " . $e->getMessage();
        }
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['action'])) {
    if (!$teacher_info) {
        $error_message = "শিক্ষক তথ্য পাওয়া যায়নি।";
    } else {
        $leave_type = $_POST['leave_type'] ?? '';
        $start_date = $_POST['start_date'] ?? '';
        $end_date = $_POST['end_date'] ?? '';
        $reason = trim($_POST['reason'] ?? '');

        // Basic validation
        if (empty($leave_type) || empty($start_date) || empty($end_date) || empty($reason)) {
            $error_message = "সব ফিল্ড পূরণ করুন।";
        } elseif (strtotime($start_date) > strtotime($end_date)) {
            $error_message = "শুরুর তারিখ শেষ তারিখের চেয়ে বড় হতে পারে না।";
        } else {
            try {
                $stmt = $pdo->prepare("INSERT INTO teacher_leaves (teacher_id, leave_type, start_date, end_date, reason) VALUES (?, ?, ?, ?, ?)");
                $result = $stmt->execute([$teacher_info['id'], $leave_type, $start_date, $end_date, $reason]);

                if ($result) {
                    $_SESSION['success_message'] = "ছুটির আবেদন সফলভাবে জমা দেওয়া হয়েছে।";
                    header('Location: ' . $_SERVER['PHP_SELF']);
                    exit();
                } else {
                    $error_message = "আবেদন জমা দেওয়ার সময় সমস্যা হয়েছে।";
                }
            } catch (Exception $e) {
                $error_message = "ত্রুটি: " . $e->getMessage();
            }
        }
    }
}

// Get search parameters
$selected_session = $_GET['session'] ?? '';
$selected_month = $_GET['month'] ?? '';
$show_rejected = isset($_GET['show_rejected']) && $_GET['show_rejected'] === '1';

// Validate parameters
if (!empty($selected_session) && !is_numeric($selected_session)) {
    $selected_session = '';
}
if (!empty($selected_month) && (!is_numeric($selected_month) || $selected_month < 1 || $selected_month > 12)) {
    $selected_month = '';
}

// Get available academic sessions
$available_sessions = [];
try {
    $stmt = $pdo->prepare("SELECT id, session_name, start_date, end_date FROM academic_sessions WHERE status = 'active' ORDER BY start_date DESC");
    $stmt->execute();
    $available_sessions = $stmt->fetchAll();
    } catch (Exception $e) {
        $error_message = "সেশন লোড করতে সমস্যা হয়েছে: " . htmlspecialchars($e->getMessage());
    }

// Get leave history - hide rejected by default unless specified
$hide_rejected = !$show_rejected;
$leave_history = [];
$leave_stats = ['total_taken' => 0, 'pending' => 0, 'approved' => 0, 'rejected' => 0, 'remaining' => 0];

if ($teacher_info) {
    try {
        // Build dynamic query with filters
        $where_conditions = ["teacher_id = ?"];
        $params = [$teacher_info['id']];

        if ($hide_rejected) {
            $where_conditions[] = "status != 'rejected'";
        }

        if (!empty($selected_session)) {
            $where_conditions[] = "YEAR(start_date) = ?";
            $params[] = $selected_session;
        }

        if (!empty($selected_month)) {
            $where_conditions[] = "MONTH(start_date) = ?";
            $params[] = $selected_month;
        }

        $where_clause = implode(" AND ", $where_conditions);

        // Get leave history with filters
        $stmt = $pdo->prepare("SELECT * FROM teacher_leaves WHERE {$where_clause} ORDER BY applied_date DESC");
        $stmt->execute($params);
        $leave_history = $stmt->fetchAll();

        // Get leave statistics (filtered)
        $current_year = !empty($selected_session) ? $selected_session : date('Y');

        // Build stats query with same filters
        $stats_where_conditions = ["teacher_id = ?"];
        $stats_params = [$teacher_info['id']];

        if (!empty($selected_session)) {
            $stats_where_conditions[] = "YEAR(start_date) = ?";
            $stats_params[] = $selected_session;
        }

        if (!empty($selected_month)) {
            $stats_where_conditions[] = "MONTH(start_date) = ?";
            $stats_params[] = $selected_month;
        }

        $stats_where_clause = implode(" AND ", $stats_where_conditions);

        $stmt = $pdo->prepare("SELECT status, COUNT(*) as count FROM teacher_leaves WHERE {$stats_where_clause} GROUP BY status");
        $stmt->execute($stats_params);
        $stats_result = $stmt->fetchAll(PDO::FETCH_ASSOC);
        $stats = [];
        foreach ($stats_result as $row) {
            $stats[$row['status']] = $row['count'];
        }

        $leave_stats['pending'] = $stats['pending'] ?? 0;
        $leave_stats['approved'] = $stats['approved'] ?? 0;
        $leave_stats['rejected'] = $stats['rejected'] ?? 0;

        // Count total days taken for approved leaves in the selected/filtered period
        $approved_where = ["teacher_id = ?", "status = 'approved'"];
        $approved_params = [$teacher_info['id']];

        if (!empty($selected_session)) {
            $approved_where[] = "YEAR(start_date) = ?";
            $approved_params[] = $selected_session;
        }

        if (!empty($selected_month)) {
            $approved_where[] = "MONTH(start_date) = ?";
            $approved_params[] = $selected_month;
        }

        $approved_where_clause = implode(" AND ", $approved_where);
        $stmt = $pdo->prepare("SELECT SUM(DATEDIFF(end_date, start_date) + 1) as total_days FROM teacher_leaves WHERE {$approved_where_clause}");
        $stmt->execute($approved_params);
        $filtered_days_taken = $stmt->fetch()['total_days'] ?? 0;

        $leave_stats['total_taken'] = $filtered_days_taken;

        // Get total all-time approved leaves (unfiltered)
        $stmt = $pdo->prepare("SELECT COUNT(*) as count FROM teacher_leaves WHERE teacher_id = ? AND status = 'approved'");
        $stmt->execute([$teacher_info['id']]);
        $leave_stats['total_all_time'] = $stmt->fetch()['count'] ?? 0;

        // Annual leave: 20 days per year (or filtered period)
        $leave_stats['remaining'] = max(0, 20 - $leave_stats['total_taken']);

    } catch (Exception $e) {
        $error_message = "ছুটির ইতিহাস লোড করতে সমস্যা হয়েছে: " . htmlspecialchars($e->getMessage());
        // Log detailed error for debugging
        error_log("Leave Application Error: " . $e->getMessage());
        if (isset($where_clause)) {
            error_log("Query: SELECT * FROM teacher_leaves WHERE {$where_clause}");
            error_log("Params: " . json_encode($params ?? []));
        }
    }
}
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ছুটির আবেদন - শিক্ষক পোর্টাল</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <!-- Bangla Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@300;400;500;600;700&family=Noto+Sans+Bengali:wght@300;400;500;600;700&family=SolaimanLipi:wght@400&display=swap" rel="stylesheet">
    <!-- Additional Bangla font fallbacks -->
    <link rel="preconnect" href="https://fonts.gstatic.com">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Baloo+Da+2:wght@400;500;600;700&display=swap');
    </style>
    <style>
        body {
            background-color: #f8f9fa;
            direction: ltr;
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', 'SolaimanLipi', 'Baloo Da 2', 'Siyam Rupali', 'Vrinda', Arial, sans-serif;
            font-size: 16px;
            line-height: 1.6;
            font-weight: 400;
        }
        .form-control, .form-select, .btn {
            text-align: left;
        }
        .form-label {
            text-align: left;
            display: block;
        }
        .table {
            direction: ltr;
        }
        .table th, .table td {
            text-align: left;
        }
        .leave-card {
            box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
            border: 1px solid rgba(0, 0, 0, 0.125);
        }
        .status-pending { background-color: #fff3cd; color: #856404; padding: 0.25rem 0.5rem; border-radius: 0.25rem; }
        .status-approved { background-color: #d4edda; color: #155724; padding: 0.25rem 0.5rem; border-radius: 0.25rem; }
        .status-rejected { background-color: #f8d7da; color: #721c24; padding: 0.25rem 0.5rem; border-radius: 0.25rem; }

        /* Enhanced Bangla typography */
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', 'Baloo Da 2', sans-serif;
            font-weight: 600;
            line-height: 1.4;
        }

        .card-title, .card-header h3, .card-header h4 {
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', 'Baloo Da 2', sans-serif;
            font-weight: 600;
        }

        .btn {
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', sans-serif;
            font-weight: 500;
        }

        .form-label, .table th {
            font-family: 'Hind Siliguri', 'Noto Sans Bengali', sans-serif;
            font-weight: 500;
        }

        /* Better text rendering for Bangla */
        * {
            text-rendering: optimizeLegibility;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
        }
    </style>
</head>
<body>
    <!-- Navigation Bar -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-success">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-chalkboard-teacher me-2"></i>
                শিক্ষক পোর্টাল
            </a>
            <div class="navbar-nav ms-auto">
                <a class="nav-link" href="../index.php">
                    <i class="fas fa-home"></i> হোম
                </a>
                <a class="nav-link" href="../logout.php">
                    <i class="fas fa-sign-out-alt"></i> লগআউট
                </a>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row">
            <div class="col-md-8 mx-auto">
                <div class="card leave-card">
                    <div class="card-header bg-primary text-white text-center">
                        <h3><i class="fas fa-calendar-plus"></i> ছুটির আবেদন</h3>
                    </div>
                    <div class="card-body">
                        <?php if (!empty($error_message)): ?>
                            <div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div>
                        <?php endif; ?>

                        <?php if (!empty($success_message)): ?>
                            <div class="alert alert-success"><?php echo htmlspecialchars($success_message); ?></div>
                        <?php endif; ?>

                        <?php if ($teacher_info): ?>
                            <form method="POST">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">ছুটির ধরন <span class="text-danger">*</span></label>
                                        <select class="form-control" name="leave_type" required>
                                            <option value="">ছুটির ধরন নির্বাচন করুন</option>
                                            <option value="sick">অসুস্থতা জনিত</option>
                                            <option value="casual">অস্থায়ী</option>
                                            <option value="annual">বার্ষিক</option>
                                            <option value="maternity">মাতৃত্ব জনিত</option>
                                            <option value="other">অন্যান্য</option>
                                        </select>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">কর্মচারী আইডি</label>
                                        <input type="text" class="form-control" value="<?php echo htmlspecialchars($teacher_info['employee_id']); ?>" readonly>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">ছুটি শুরুর তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" name="start_date" required>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">ছুটি শেষের তারিখ <span class="text-danger">*</span></label>
                                        <input type="date" class="form-control" name="end_date" required>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label class="form-label">ছুটির কারণ <span class="text-danger">*</span></label>
                                    <textarea class="form-control" name="reason" rows="4" placeholder="ছুটির কারণ লিখুন..." required></textarea>
                                </div>

                                <div class="text-center">
                                    <button type="submit" class="btn btn-primary btn-lg">
                                        <i class="fas fa-paper-plane"></i> আবেদন জমা দিন
                                    </button>
                                </div>
                            </form>
                        <?php else: ?>
                            <div class="alert alert-warning text-center">
                                <i class="fas fa-exclamation-triangle"></i> শিক্ষক তথ্য পাওয়া যায়নি।
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if ($teacher_info): ?>
                <!-- Leave Statistics -->
                <div class="card leave-card mt-4">
                    <div class="card-header bg-info text-white">
                        <h4><i class="fas fa-chart-bar"></i> ছুটির পরিসংখ্যান</h4>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-md-3">
                                <div class="p-3 bg-success text-white rounded">
                                    <h3><?php echo $leave_stats['total_taken']; ?></h3>
                                    <p class="mb-0">চলতি বছর নেওয়া</p>
                                    <small><?php echo date('Y'); ?> সাল</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="p-3 bg-warning text-white rounded">
                                    <h3><?php echo $leave_stats['remaining']; ?></h3>
                                    <p class="mb-0">বাকি ছুটি</p>
                                    <small>প্রতি বছর ২০ দিন</small>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="p-3 bg-primary text-white rounded">
                                    <h3><?php echo $leave_stats['pending']; ?></h3>
                                    <p class="mb-0">অমীমাংসিত</p>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="p-3 bg-danger text-white rounded">
                                    <h3><?php echo $leave_stats['total_all_time']; ?></h3>
                                    <p class="mb-0">মোট অনুমোদিত</p>
                                    <small>সারাজীবন</small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Search/Filter Form -->
                <div class="card leave-card mt-4">
                    <div class="card-header bg-light">
                        <h5><i class="fas fa-search"></i> অনুসন্ধান এবং ফিল্টার</h5>
                    </div>
                    <div class="card-body">
                        <form method="GET" class="row g-3">
                            <div class="col-md-4">
                                <label class="form-label">একাডেমিক সেশন</label>
                                <select class="form-control" name="session">
                                    <option value="">সব সেশন</option>
                                    <?php
                                    // Add current year as fallback if no sessions available
                                    if (empty($available_sessions)) {
                                        $current_year = date('Y');
                                        echo "<option value='{$current_year}' " . ($selected_session == $current_year ? 'selected' : '') . ">{$current_year}</option>";
                                    } else {
                                        foreach ($available_sessions as $session):
                                    ?>
                                        <option value="<?php echo $session['session_name']; ?>" <?php echo ($selected_session == $session['session_name']) ? 'selected' : ''; ?>>
                                            <?php echo htmlspecialchars($session['session_name']); ?>
                                        </option>
                                    <?php
                                        endforeach;
                                    }
                                    ?>
                                </select>
                            </div>
                            <div class="col-md-4">
                                <label class="form-label">মাস</label>
                                <select class="form-control" name="month">
                                    <option value="">সব মাস</option>
                                    <option value="1" <?php echo ($selected_month == '1') ? 'selected' : ''; ?>>জানুয়ারি</option>
                                    <option value="2" <?php echo ($selected_month == '2') ? 'selected' : ''; ?>>ফেব্রুয়ারি</option>
                                    <option value="3" <?php echo ($selected_month == '3') ? 'selected' : ''; ?>>মার্চ</option>
                                    <option value="4" <?php echo ($selected_month == '4') ? 'selected' : ''; ?>>এপ্রিল</option>
                                    <option value="5" <?php echo ($selected_month == '5') ? 'selected' : ''; ?>>মে</option>
                                    <option value="6" <?php echo ($selected_month == '6') ? 'selected' : ''; ?>>জুন</option>
                                    <option value="7" <?php echo ($selected_month == '7') ? 'selected' : ''; ?>>জুলাই</option>
                                    <option value="8" <?php echo ($selected_month == '8') ? 'selected' : ''; ?>>আগস্ট</option>
                                    <option value="9" <?php echo ($selected_month == '9') ? 'selected' : ''; ?>>সেপ্টেম্বর</option>
                                    <option value="10" <?php echo ($selected_month == '10') ? 'selected' : ''; ?>>অক্টোবর</option>
                                    <option value="11" <?php echo ($selected_month == '11') ? 'selected' : ''; ?>>নভেম্বর</option>
                                    <option value="12" <?php echo ($selected_month == '12') ? 'selected' : ''; ?>>ডিসেম্বর</option>
                                </select>
                            </div>
                            <div class="col-md-4 d-flex align-items-end">
                                <div class="d-grid gap-2 d-md-flex">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-search"></i> অনুসন্ধান
                                    </button>
                                    <a href="?" class="btn btn-secondary">
                                        <i class="fas fa-times"></i> পরিষ্কার
                                    </a>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <?php if (!empty($leave_history) || $show_rejected): ?>
                <div class="card leave-card mt-4">
                    <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                        <div>
                            <h4><i class="fas fa-history"></i> আপনার ছুটির ইতিহাস</h4>
                            <?php
                            $filter_info = [];
                            if (!empty($selected_session)) {
                                $filter_info[] = "সেশন: {$selected_session}";
                            }
                            if (!empty($selected_month)) {
                                $month_names = [
                                    1 => 'জানুয়ারি', 2 => 'ফেব্রুয়ারি', 3 => 'মার্চ', 4 => 'এপ্রিল', 5 => 'মে', 6 => 'জুন',
                                    7 => 'জুলাই', 8 => 'আগস্ট', 9 => 'সেপ্টেম্বর', 10 => 'অক্টোবর', 11 => 'নভেম্বর', 12 => 'ডিসেম্বর'
                                ];
                                $filter_info[] = "মাস: {$month_names[$selected_month]}";
                            }
                            if (!empty($filter_info)) {
                                echo '<small class="text-light-emphasis">' . implode(' | ', $filter_info) . '</small>';
                            }
                            ?>
                        </div>
                        <div>
                            <?php
                            // Build URL parameters for filter preservation
                            $url_params = [];
                            if (!empty($selected_session)) $url_params[] = "session={$selected_session}";
                            if (!empty($selected_month)) $url_params[] = "month={$selected_month}";
                            $base_url = '?' . implode('&', $url_params);

                            if (!$show_rejected && $leave_stats['rejected'] > 0): ?>
                                <a href="<?php echo $base_url . (!empty($base_url) ? '&' : '?') . 'show_rejected=1'; ?>" class="btn btn-outline-light btn-sm">
                                    <i class="fas fa-eye"></i> প্রত্যাখ্যাত দেখান (<?php echo $leave_stats['rejected']; ?>)
                                </a>
                            <?php elseif ($show_rejected): ?>
                                <a href="<?php echo $base_url; ?>" class="btn btn-outline-light btn-sm">
                                    <i class="fas fa-eye-slash"></i> প্রত্যাখ্যাত লুকান
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>তারিখ</th>
                                        <th>ধরন</th>
                                        <th>তারিখসমূহ</th>
                                        <th>কারণ</th>
                                        <th>অবস্থা</th>
                                        <th>কার্যক্রম</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($leave_history as $leave): ?>
                                    <tr>
                                        <td><?php echo date('d/m/Y', strtotime($leave['applied_date'])); ?></td>
                                        <td><?php echo htmlspecialchars(ucfirst($leave['leave_type'])); ?></td>
                                        <td><?php echo date('d/m/Y', strtotime($leave['start_date'])); ?> - <?php echo date('d/m/Y', strtotime($leave['end_date'])); ?></td>
                                        <td><?php echo htmlspecialchars(substr($leave['reason'], 0, 50)) . (strlen($leave['reason']) > 50 ? '...' : ''); ?></td>
                                        <td>
                                            <?php
                                            $status_class = '';
                                            $status_text = '';
                                            switch($leave['status']) {
                                                case 'approved':
                                                    $status_class = 'status-approved';
                                                    $status_text = 'অনুমোদিত';
                                                    break;
                                                case 'rejected':
                                                    $status_class = 'status-rejected';
                                                    $status_text = 'প্রত্যাখ্যাত';
                                                    break;
                                                case 'pending':
                                                default:
                                                    $status_class = 'status-pending';
                                                    $status_text = 'অমীমাংসিত';
                                                    break;
                                            }
                                            ?>
                                            <span class="<?php echo $status_class; ?>"><?php echo $status_text; ?></span>
                                        </td>
                                        <td>
                                            <?php if ($leave['status'] === 'pending'): ?>
                                                <!-- Edit Button -->
                                                <button type="button" class="btn btn-primary btn-sm me-1" data-bs-toggle="modal" data-bs-target="#editModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-leave-type="<?php echo $leave['leave_type']; ?>"
                                                        data-start-date="<?php echo $leave['start_date']; ?>"
                                                        data-end-date="<?php echo $leave['end_date']; ?>"
                                                        data-reason="<?php echo htmlspecialchars($leave['reason'], ENT_QUOTES); ?>">
                                                    <i class="fas fa-edit"></i> এডিট
                                                </button>

                                                <!-- Delete Button -->
                                                <button type="button" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#deleteModal"
                                                        data-leave-id="<?php echo $leave['id']; ?>"
                                                        data-leave-dates="<?php echo date('d/m/Y', strtotime($leave['start_date'])) . ' - ' . date('d/m/Y', strtotime($leave['end_date'])); ?>">
                                                    <i class="fas fa-trash"></i> ডিলেট
                                                </button>
                                            <?php else: ?>
                                                <span class="text-muted">কোন কার্যক্রম নেই</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
                <?php else: ?>
                    <div class="card leave-card mt-4">
                        <div class="card-header bg-secondary text-white d-flex justify-content-between align-items-center">
                            <div>
                                <h4><i class="fas fa-history"></i> আপনার ছুটির ইতিহাস</h4>
                                <?php
                                $filter_info = [];
                                if (!empty($selected_session)) {
                                    $filter_info[] = "সেশন: {$selected_session}";
                                }
                                if (!empty($selected_month)) {
                                    $month_names = [
                                        1 => 'জানুয়ারি', 2 => 'ফেব্রুয়ারি', 3 => 'মার্চ', 4 => 'এপ্রিল', 5 => 'মে', 6 => 'জুন',
                                        7 => 'জুলাই', 8 => 'আগস্ট', 9 => 'সেপ্টেম্বর', 10 => 'অক্টোবর', 11 => 'নভেম্বর', 12 => 'ডিসেম্বর'
                                    ];
                                    $filter_info[] = "মাস: {$month_names[$selected_month]}";
                                }
                                if (!empty($filter_info)) {
                                    echo '<small class="text-light-emphasis">' . implode(' | ', $filter_info) . '</small>';
                                }
                                ?>
                            </div>
                        </div>
                        <div class="card-body">
                            <div class="alert alert-info text-center">
                                <?php
                                $has_filters = !empty($selected_session) || !empty($selected_month);
                                $base_url = '?';
                                if (!empty($selected_session)) $base_url .= "session={$selected_session}&";
                                if (!empty($selected_month)) $base_url .= "month={$selected_month}&";

                                if ($has_filters): ?>
                                    নির্বাচিত ফিল্টারের জন্য কোনো ছুটির আবেদন পাওয়া যায়নি।
                                    <br><small><a href="?" class="text-decoration-none">সব ফিল্টার পরিষ্কার করে দেখুন</a></small>
                                <?php elseif (!$show_rejected): ?>
                                    কোনো অমীমাংসিত বা অনুমোদিত ছুটির আবেদন নেই।
                                    <?php if ($leave_stats['rejected'] > 0): ?>
                                        <br><small><a href="<?php echo $base_url; ?>show_rejected=1" class="text-decoration-none">প্রত্যাখ্যাত আবেদন দেখতে এখানে ক্লিক করুন</a></small>
                                    <?php endif; ?>
                                <?php else: ?>
                                    কোনো ছুটির আবেদন নেই।
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>

    <!-- Edit Modal -->
    <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="editModalLabel"><i class="fas fa-edit text-primary"></i> ছুটির আবেদন এডিট করুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <input type="hidden" name="action" value="edit">
                    <input type="hidden" name="leave_id" id="edit_leave_id" value="">
                    <div class="modal-body">
                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_leave_type" class="form-label">ছুটির ধরন <span class="text-danger">*</span></label>
                                    <select class="form-select" id="edit_leave_type" name="leave_type" required>
                                        <option value="sick">অসুস্থতা জনিত</option>
                                        <option value="casual">অস্থায়ী</option>
                                        <option value="annual">বার্ষিক</option>
                                        <option value="maternity">মাতৃত্ব জনিত</option>
                                        <option value="medical">চিকিৎসা সনদ সহ</option>
                                        <option value="other">অন্যান্য</option>
                                    </select>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_start_date" class="form-label">শুরুর তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="edit_start_date" name="start_date" required>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="mb-3">
                                    <label for="edit_end_date" class="form-label">শেষ তারিখ <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="edit_end_date" name="end_date" required>
                                </div>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label for="edit_reason" class="form-label">কারণ <span class="text-danger">*</span></label>
                            <textarea class="form-control" id="edit_reason" name="reason" rows="3" required placeholder="ছুটির কারণ লিখুন..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-primary">
                            <i class="fas fa-save"></i> আপডেট করুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Delete Modal -->
    <div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="deleteModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="deleteModalLabel"><i class="fas fa-trash text-danger"></i> ছুটির আবেদন মুছে ফেলুন</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <input type="hidden" name="action" value="delete">
                        <input type="hidden" name="leave_id" id="delete_leave_id" value="">

                        <div class="alert alert-danger">
                            <i class="fas fa-exclamation-triangle"></i>
                            <strong>সতর্কতা!</strong> এই অ্যাকশন পূর্বাবস্থায় ফেরানো যাবে না।
                        </div>

                        <p>আপনি কি নিশ্চিত যে ছুটির আবেদন (<strong id="delete_leave_dates"></strong>) মুছে ফেলতে চান?</p>

                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" id="confirm_delete" required>
                            <label class="form-check-label" for="confirm_delete">
                                হ্যাঁ, আমি নিশ্চিত যে এই ছুটির আবেদন মুছে ফেলতে চাই
                            </label>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">বাতিল</button>
                        <button type="submit" class="btn btn-danger" id="deleteBtn" disabled>
                            <i class="fas fa-trash"></i> মুছে ফেলুন
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Handle modal data passing
        document.querySelectorAll('[data-bs-toggle="modal"]').forEach(button => {
            button.addEventListener('click', function() {
                if (this.getAttribute('data-bs-target') === '#editModal') {
                    // Populate edit modal
                    document.getElementById('edit_leave_id').value = this.getAttribute('data-leave-id');
                    document.getElementById('edit_leave_type').value = this.getAttribute('data-leave-type');
                    document.getElementById('edit_start_date').value = this.getAttribute('data-start-date');
                    document.getElementById('edit_end_date').value = this.getAttribute('data-end-date');
                    document.getElementById('edit_reason').value = this.getAttribute('data-reason').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/&quot;/g, '"').replace(/&#039;/g, "'");
                } else if (this.getAttribute('data-bs-target') === '#deleteModal') {
                    // Populate delete modal
                    document.getElementById('delete_leave_id').value = this.getAttribute('data-leave-id');
                    document.getElementById('delete_leave_dates').textContent = this.getAttribute('data-leave-dates');
                    document.getElementById('confirm_delete').checked = false;
                    document.getElementById('deleteBtn').disabled = true;
                }
            });
        });

        // Handle delete confirmation checkbox
        document.getElementById('confirm_delete').addEventListener('change', function() {
            document.getElementById('deleteBtn').disabled = !this.checked;
        });

        // Clear delete confirmation when modal is closed
        document.getElementById('deleteModal').addEventListener('hidden.bs.modal', function() {
            document.getElementById('confirm_delete').checked = false;
            document.getElementById('deleteBtn').disabled = true;
        });
    </script>
</body>
</html>
