<?php
require_once 'config/database.php';
require_once 'config/session.php';

// Check if user is logged in
redirectIfNotLoggedIn();

// Get current page
$current_page = 'leave';

// Check if user has permission to view this page
if (!checkPageAccess($current_page)) {
    echo "<div class='alert alert-danger'>Access Denied. You don't have permission to view this page.</div>";
    exit();
}

// Initialize variables
$success_msg = '';
$error_msg = '';
$employee_id = $_SESSION['employee_id'] ?? null;

// Handle leave approval/rejection (admin/manager)
if (isAdmin() || isManager()) {
    if (isset($_GET['approve_leave'])) {
        $leave_id = $_GET['approve_leave'];
        try {
            approveLeave($pdo, $leave_id, $_SESSION['user_id']);
            $success_msg = "Leave approved successfully!";
        } catch (Exception $e) {
            $error_msg = "Error approving leave: " . $e->getMessage();
        }
    } elseif (isset($_GET['reject_leave'])) {
        $leave_id = $_GET['reject_leave'];
        try {
            rejectLeave($pdo, $leave_id, $_SESSION['user_id']);
            $success_msg = "Leave rejected successfully!";
        } catch (Exception $e) {
            $error_msg = "Error rejecting leave: " . $e->getMessage();
        }
    }
    
    // Handle bulk actions
    if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['bulk_action'])) {
        $action = $_POST['action'];
        $leave_ids = $_POST['leave_ids'] ?? [];
        
        if (!empty($leave_ids)) {
            foreach ($leave_ids as $leave_id) {
                try {
                    if ($action == 'approve') {
                        approveLeave($pdo, $leave_id, $_SESSION['user_id']);
                    } elseif ($action == 'reject') {
                        rejectLeave($pdo, $leave_id, $_SESSION['user_id']);
                    }
                } catch (Exception $e) {
                    $error_msg = "Error processing leave ID $leave_id: " . $e->getMessage();
                }
            }
            if (empty($error_msg)) {
                $success_msg = "Bulk $action completed successfully!";
            }
        }
    }
    
    // Handle leave type management (Admin only)
    if (isAdmin() && $_SERVER['REQUEST_METHOD'] == 'POST') {
        if (isset($_POST['add_leave_type'])) {
            $type_name = $_POST['type_name'];
            $days_per_year = $_POST['days_per_year'];
            $description = $_POST['description'];
            $is_paid = isset($_POST['is_paid']) ? 1 : 0;
            $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;
            
            try {
                $stmt = $pdo->prepare("INSERT INTO leave_types (type_name, days_per_year, description, is_paid, requires_approval) 
                                      VALUES (?, ?, ?, ?, ?)");
                $stmt->execute([$type_name, $days_per_year, $description, $is_paid, $requires_approval]);
                $success_msg = "Leave type added successfully!";
            } catch (Exception $e) {
                $error_msg = "Error adding leave type: " . $e->getMessage();
            }
        }
        
        if (isset($_POST['update_leave_type'])) {
            $id = $_POST['id'];
            $type_name = $_POST['type_name'];
            $days_per_year = $_POST['days_per_year'];
            $description = $_POST['description'];
            $is_paid = isset($_POST['is_paid']) ? 1 : 0;
            $requires_approval = isset($_POST['requires_approval']) ? 1 : 0;
            
            try {
                $stmt = $pdo->prepare("UPDATE leave_types SET type_name = ?, days_per_year = ?, description = ?, 
                                      is_paid = ?, requires_approval = ? WHERE id = ?");
                $stmt->execute([$type_name, $days_per_year, $description, $is_paid, $requires_approval, $id]);
                $success_msg = "Leave type updated successfully!";
            } catch (Exception $e) {
                $error_msg = "Error updating leave type: " . $e->getMessage();
            }
        }
        
        if (isset($_POST['delete_leave_type'])) {
            $id = $_POST['id'];
            
            try {
                $stmt = $pdo->prepare("DELETE FROM leave_types WHERE id = ?");
                $stmt->execute([$id]);
                $success_msg = "Leave type deleted successfully!";
            } catch (Exception $e) {
                $error_msg = "Error deleting leave type: " . $e->getMessage();
            }
        }
    }
}

// Handle employee leave application
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['apply_leave'])) {
    $employee_id = $_POST['employee_id'];
    $leave_type = $_POST['leave_type'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $reason = $_POST['reason'];
    
    // Calculate total days
    $start = new DateTime($start_date);
    $end = new DateTime($end_date);
    $interval = $start->diff($end);
    $total_days = $interval->days + 1; // Include both start and end dates
    
    try {
        $stmt = $pdo->prepare("INSERT INTO leaves (employee_id, leave_type, start_date, end_date, total_days, reason) 
                              VALUES (?, ?, ?, ?, ?, ?)");
        $stmt->execute([$employee_id, $leave_type, $start_date, $end_date, $total_days, $reason]);
        $success_msg = "Leave application submitted successfully! Waiting for approval.";
    } catch (Exception $e) {
        $error_msg = "Error submitting leave application: " . $e->getMessage();
    }
}

// Handle leave cancellation (employee)
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['cancel_leave'])) {
    $leave_id = $_POST['leave_id'];
    $employee_id = $_POST['employee_id'];
    
    // Verify that the leave belongs to the employee
    $stmt = $pdo->prepare("SELECT * FROM leaves WHERE id = ? AND employee_id = ?");
    $stmt->execute([$leave_id, $employee_id]);
    $leave = $stmt->fetch();
    
    if ($leave && $leave['status'] == 'pending') {
        try {
            $stmt = $pdo->prepare("UPDATE leaves SET status = 'cancelled' WHERE id = ?");
            $stmt->execute([$leave_id]);
            $success_msg = "Leave application cancelled successfully!";
        } catch (Exception $e) {
            $error_msg = "Error cancelling leave: " . $e->getMessage();
        }
    } else {
        $error_msg = "Cannot cancel this leave application.";
    }
}

// Functions for leave approval/rejection
function approveLeave($pdo, $leave_id, $approved_by) {
    try {
        $pdo->beginTransaction();
        
        // Get leave details
        $stmt = $pdo->prepare("SELECT * FROM leaves WHERE id = ?");
        $stmt->execute([$leave_id]);
        $leave = $stmt->fetch();
        
        if (!$leave) {
            throw new Exception("Leave not found!");
        }
        
        // Update leave status
        $stmt = $pdo->prepare("UPDATE leaves SET status = 'approved', approved_by = ?, approved_date = NOW() WHERE id = ?");
        $stmt->execute([$approved_by, $leave_id]);
        
        // Create attendance records for each day of leave
        $start_date = new DateTime($leave['start_date']);
        $end_date = new DateTime($leave['end_date']);
        $end_date->modify('+1 day'); // Include end date
        
        $employee_id = $leave['employee_id'];
        
        while ($start_date < $end_date) {
            $attendance_date = $start_date->format('Y-m-d');
            
            // Skip weekends (Saturday=6, Sunday=0)
            $day_of_week = $start_date->format('w');
            if ($day_of_week != 0 && $day_of_week != 6) {
                
                // Check if attendance record already exists
                $stmt = $pdo->prepare("SELECT id FROM attendance WHERE employee_id = ? AND attendance_date = ?");
                $stmt->execute([$employee_id, $attendance_date]);
                $existing_attendance = $stmt->fetch();
                
                if ($existing_attendance) {
                    // Update existing attendance record
                    $stmt = $pdo->prepare("UPDATE attendance SET 
                        status = 'leave', 
                        notes = CONCAT(COALESCE(notes, ''), '\nLeave approved: {$leave['leave_type']}'),
                        updated_at = NOW()
                        WHERE id = ?");
                    $stmt->execute([$existing_attendance['id']]);
                } else {
                    // Create new attendance record for leave
                    $stmt = $pdo->prepare("INSERT INTO attendance 
                        (employee_id, attendance_date, status, notes, updated_at) 
                        VALUES (?, ?, 'leave', ?, NOW())");
                    $stmt->execute([
                        $employee_id, 
                        $attendance_date,
                        "Leave approved: {$leave['leave_type']} - {$leave['reason']}"
                    ]);
                }
            }
            
            $start_date->modify('+1 day');
        }
        
        // Update leave balance for paid leaves
        if (in_array($leave['leave_type'], ['Casual Leave', 'Sick Leave', 'Annual Leave'])) {
            $column_map = [
                'Casual Leave' => 'casual',
                'Sick Leave' => 'sick',
                'Annual Leave' => 'annual'
            ];
            
            $type = $column_map[$leave['leave_type']];
            $used_column = "used_{$type}";
            
            $stmt = $pdo->prepare("UPDATE leave_balance SET $used_column = $used_column + ? WHERE employee_id = ?");
            $stmt->execute([$leave['total_days'], $leave['employee_id']]);
        }
        
        $pdo->commit();
        
        // Send approval notification
        sendApprovalNotification($pdo, $leave['employee_id'], $leave_id, true);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

function rejectLeave($pdo, $leave_id, $rejected_by) {
    try {
        $pdo->beginTransaction();
        
        // Get leave details
        $stmt = $pdo->prepare("SELECT * FROM leaves WHERE id = ?");
        $stmt->execute([$leave_id]);
        $leave = $stmt->fetch();
        
        if (!$leave) {
            throw new Exception("Leave not found!");
        }
        
        // Update leave status
        $stmt = $pdo->prepare("UPDATE leaves SET status = 'rejected', approved_by = ?, approved_date = NOW() WHERE id = ?");
        $stmt->execute([$rejected_by, $leave_id]);
        
        // Remove leave attendance records if they exist
        $start_date = new DateTime($leave['start_date']);
        $end_date = new DateTime($leave['end_date']);
        $end_date->modify('+1 day'); // Include end date
        
        $employee_id = $leave['employee_id'];
        
        while ($start_date < $end_date) {
            $attendance_date = $start_date->format('Y-m-d');
            
            // Check if attendance record exists and status is 'leave'
            $stmt = $pdo->prepare("SELECT id FROM attendance WHERE employee_id = ? AND attendance_date = ? AND status = 'leave'");
            $stmt->execute([$employee_id, $attendance_date]);
            $attendance = $stmt->fetch();
            
            if ($attendance) {
                // Delete leave attendance record
                $stmt = $pdo->prepare("DELETE FROM attendance WHERE id = ?");
                $stmt->execute([$attendance['id']]);
            }
            
            $start_date->modify('+1 day');
        }
        
        $pdo->commit();
        
        // Send rejection notification
        sendApprovalNotification($pdo, $leave['employee_id'], $leave_id, false);
        
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }
}

function sendApprovalNotification($pdo, $employee_id, $leave_id, $approved) {
    // Get employee details
    $stmt = $pdo->prepare("SELECT e.full_name, u.email FROM employees e 
                          JOIN users u ON e.user_id = u.id 
                          WHERE e.id = ?");
    $stmt->execute([$employee_id]);
    $employee = $stmt->fetch();
    
    if ($employee) {
        $status = $approved ? "APPROVED" : "REJECTED";
        error_log("Leave $status: {$employee['full_name']} (Leave ID: $leave_id)");
    }
}

// Get pending leaves for approval (admins/managers)
$pending_leaves = [];
$leave_statistics = [];

if (isAdmin() || isManager()) {
    // Get pending leaves with employee details
    $stmt = $pdo->prepare("SELECT l.*, e.full_name, e.department, e.contact_number 
                          FROM leaves l 
                          JOIN employees e ON l.employee_id = e.id 
                          WHERE l.status = 'pending' 
                          ORDER BY l.applied_date DESC");
    $stmt->execute();
    $pending_leaves = $stmt->fetchAll();
    
    // Get leave statistics
    $stmt = $pdo->query("SELECT 
                        COUNT(*) as total_leaves,
                        COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
                        COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_count,
                        COUNT(CASE WHEN status = 'rejected' THEN 1 END) as rejected_count,
                        COUNT(CASE WHEN status = 'cancelled' THEN 1 END) as cancelled_count,
                        SUM(CASE WHEN status = 'approved' THEN total_days ELSE 0 END) as total_approved_days
                        FROM leaves");
    $leave_statistics = $stmt->fetch();
}

// Get leave types (for admin editing)
$leave_types = [];
if (isAdmin()) {
    $stmt = $pdo->query("SELECT * FROM leave_types ORDER BY type_name");
    $leave_types = $stmt->fetchAll();
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leave Management</title>
   
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css">
    <style>
        .card-stat {
            transition: transform 0.2s;
        }
        .card-stat:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .leave-badge {
            font-size: 0.75em;
        }
        .progress-container {
            height: 25px;
            border-radius: 15px;
            overflow: hidden;
        }
        .leave-type-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }
        .settings-card {
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <div class="container-fluid mt-4">
        <!-- Messages -->
        <?php if ($success_msg): ?>
        <div class="alert alert-success alert-dismissible fade show">
            <i class="bi bi-check-circle"></i> <?php echo $success_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <?php if ($error_msg): ?>
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="bi bi-exclamation-triangle"></i> <?php echo $error_msg; ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="bi bi-calendar-event me-2"></i>Leave Management System</h5>
                    </div>
                    <div class="card-body">
                        
                        <!-- Statistics for Admins/Managers -->
                        <?php if (isAdmin() || isManager()): ?>
                        <div class="row mb-4">
                            <div class="col-md-3">
                                <div class="card card-stat bg-warning text-white">
                                    <div class="card-body text-center">
                                        <h6>Pending Leaves</h6>
                                        <h2><?php echo $leave_statistics['pending_count'] ?? 0; ?></h2>
                                        <small>Waiting Approval</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card card-stat bg-success text-white">
                                    <div class="card-body text-center">
                                        <h6>Approved</h6>
                                        <h2><?php echo $leave_statistics['approved_count'] ?? 0; ?></h2>
                                        <small>Total Approved</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card card-stat bg-danger text-white">
                                    <div class="card-body text-center">
                                        <h6>Rejected</h6>
                                        <h2><?php echo $leave_statistics['rejected_count'] ?? 0; ?></h2>
                                        <small>Total Rejected</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <div class="card card-stat bg-info text-white">
                                    <div class="card-body text-center">
                                        <h6>Total Days</h6>
                                        <h2><?php echo $leave_statistics['total_approved_days'] ?? 0; ?></h2>
                                        <small>Approved Days</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Tabs Navigation - Different for Admin/Manager vs Employee -->
                        <ul class="nav nav-tabs mb-4" id="leaveTab" role="tablist">
                            <?php if (isAdmin()): ?>
                            <!-- Admin Tabs -->
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="approvals-tab" data-bs-toggle="tab" data-bs-target="#approvals" type="button" role="tab">
                                    <i class="bi bi-shield-check"></i> Approvals
                                    <?php if (count($pending_leaves) > 0): ?>
                                    <span class="badge bg-danger"><?php echo count($pending_leaves); ?></span>
                                    <?php endif; ?>
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="types-tab" data-bs-toggle="tab" data-bs-target="#types" type="button" role="tab">
                                    <i class="bi bi-gear"></i> Manage Leave Types
                                </button>
                            </li>
                            <?php elseif (isManager()): ?>
                            <!-- Manager Tabs -->
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="approvals-tab" data-bs-toggle="tab" data-bs-target="#approvals" type="button" role="tab">
                                    <i class="bi bi-shield-check"></i> Approvals
                                    <?php if (count($pending_leaves) > 0): ?>
                                    <span class="badge bg-danger"><?php echo count($pending_leaves); ?></span>
                                    <?php endif; ?>
                                </button>
                            </li>
                            <?php else: ?>
                            <!-- Employee Tabs -->
                            <li class="nav-item" role="presentation">
                                <button class="nav-link active" id="apply-tab" data-bs-toggle="tab" data-bs-target="#apply" type="button" role="tab">
                                    <i class="bi bi-plus-circle"></i> Apply Leave
                                </button>
                            </li>
                            <li class="nav-item" role="presentation">
                                <button class="nav-link" id="my-leaves-tab" data-bs-toggle="tab" data-bs-target="#my-leaves" type="button" role="tab">
                                    <i class="bi bi-clock-history"></i> My Leaves
                                </button>
                            </li>
                           
                            <?php endif; ?>
                        </ul>
                        
                        <!-- Tab Content -->
                        <div class="tab-content" id="leaveTabContent">
                            
                            <?php if (!isAdmin() && !isManager()): ?>
                            <!-- Employee Tabs Content -->
                            
                            <!-- Apply Leave Tab (Employee only) -->
                            <div class="tab-pane fade show active" id="apply" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="mb-0">Apply for New Leave</h6>
                                            </div>
                                            <div class="card-body">
                                                <?php 
                                                // Get leave types for employee
                                                $stmt = $pdo->query("SELECT * FROM leave_types ORDER BY type_name");
                                                $employee_leave_types = $stmt->fetchAll();
                                                ?>
                                                <form method="POST" id="leaveForm">
                                                    <input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>">
                                                    <input type="hidden" name="apply_leave" value="1">
                                                    
                                                    <div class="row">
                                                        <div class="col-md-6 mb-3">
                                                            <label>Leave Type *</label>
                                                            <select name="leave_type" class="form-control" required onchange="updateLeaveBalance(this.value)">
                                                                <option value="">Select Leave Type</option>
                                                                <?php foreach ($employee_leave_types as $type): ?>
                                                                <option value="<?php echo htmlspecialchars($type['type_name']); ?>">
                                                                    <?php echo htmlspecialchars($type['type_name']); ?>
                                                                </option>
                                                                <?php endforeach; ?>
                                                            </select>
                                                        </div>
                                                        
                                                        <div class="col-md-6 mb-3">
                                                            <label>Available Balance</label>
                                                            <input type="text" id="availableBalance" class="form-control" readonly>
                                                        </div>
                                                        
                                                        <div class="col-md-6 mb-3">
                                                            <label>Start Date *</label>
                                                            <input type="date" name="start_date" class="form-control" required 
                                                                   min="<?php echo date('Y-m-d'); ?>" onchange="calculateDays()">
                                                        </div>
                                                        
                                                        <div class="col-md-6 mb-3">
                                                            <label>End Date *</label>
                                                            <input type="date" name="end_date" class="form-control" required 
                                                                   min="<?php echo date('Y-m-d'); ?>" onchange="calculateDays()">
                                                        </div>
                                                        
                                                        <div class="col-md-6 mb-3">
                                                            <label>Total Working Days</label>
                                                            <input type="text" id="totalDays" class="form-control" readonly>
                                                        </div>
                                                        
                                                        <div class="col-md-6 mb-3">
                                                            <label>Return Date</label>
                                                            <input type="text" id="returnDate" class="form-control" readonly>
                                                        </div>
                                                        
                                                        <div class="col-12 mb-3">
                                                            <label>Reason for Leave *</label>
                                                            <textarea name="reason" class="form-control" rows="4" required 
                                                                      placeholder="Please provide detailed reason for your leave..."></textarea>
                                                        </div>
                                                        
                                                        <div class="col-12">
                                                            <div class="alert alert-info">
                                                                <i class="bi bi-info-circle"></i> 
                                                                Leave applications require approval from administration. 
                                                                You can cancel pending applications anytime.
                                                            </div>
                                                        </div>
                                                        
                                                        <div class="col-12">
                                                            <button type="submit" class="btn btn-primary">
                                                                <i class="bi bi-send"></i> Submit Application
                                                            </button>
                                                            <button type="button" class="btn btn-secondary" onclick="resetForm()">
                                                                <i class="bi bi-arrow-clockwise"></i> Reset
                                                            </button>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="mb-0">Leave Policy</h6>
                                            </div>
                                            <div class="card-body">
                                                <?php foreach ($employee_leave_types as $type): ?>
                                                <div class="mb-3">
                                                    <h6><?php echo htmlspecialchars($type['type_name']); ?></h6>
                                                    <p class="small text-muted mb-1">Max: <?php echo $type['days_per_year']; ?> days per year</p>
                                                    <?php if ($type['description']): ?>
                                                    <p class="small text-muted"><?php echo htmlspecialchars($type['description']); ?></p>
                                                    <?php endif; ?>
                                                    <?php if ($type['requires_approval']): ?>
                                                    <small class="text-warning"><i class="bi bi-exclamation-triangle"></i> Requires approval</small>
                                                    <?php else: ?>
                                                    <small class="text-success"><i class="bi bi-check-circle"></i> Auto-approved</small>
                                                    <?php endif; ?>
                                                </div>
                                                <?php if ($type !== end($employee_leave_types)): ?><hr><?php endif; ?>
                                                <?php endforeach; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- My Leaves Tab (Employee only) -->
                            <div class="tab-pane fade" id="my-leaves" role="tabpanel">
                                <?php
                                // Get leave history for current user
                                $my_leaves = [];
                                if ($employee_id) {
                                    $stmt = $pdo->prepare("SELECT l.*, u.username as approved_by_name 
                                                          FROM leaves l 
                                                          LEFT JOIN users u ON l.approved_by = u.id 
                                                          WHERE l.employee_id = ? 
                                                          ORDER BY l.applied_date DESC");
                                    $stmt->execute([$employee_id]);
                                    $my_leaves = $stmt->fetchAll();
                                }
                                ?>
                                <div class="card">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">My Leave History</h6>
                                            <span class="badge bg-primary">
                                                Total: <?php echo count($my_leaves); ?> applications
                                            </span>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($my_leaves)): ?>
                                        <div class="text-center py-5">
                                            <i class="bi bi-calendar-x display-1 text-muted"></i>
                                            <h5 class="mt-3">No leave applications found</h5>
                                            <p class="text-muted">You haven't applied for any leaves yet.</p>
                                            <a href="#apply" class="btn btn-primary" onclick="switchTab('apply-tab')">
                                                <i class="bi bi-plus-circle"></i> Apply for Leave
                                            </a>
                                        </div>
                                        <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Applied Date</th>
                                                        <th>Type</th>
                                                        <th>Period</th>
                                                        <th>Days</th>
                                                        <th>Status</th>
                                                        <th>Approved By</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($my_leaves as $leave): ?>
                                                    <tr>
                                                        <td><?php echo date('d M Y', strtotime($leave['applied_date'])); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php 
                                                                echo $leave['leave_type'] == 'Casual Leave' ? 'primary' : 
                                                                     ($leave['leave_type'] == 'Sick Leave' ? 'info' : 
                                                                     ($leave['leave_type'] == 'Annual Leave' ? 'success' : 'warning'));
                                                            ?>">
                                                                <?php echo htmlspecialchars($leave['leave_type']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php echo date('d M', strtotime($leave['start_date'])) . ' to ' . 
                                                                  date('d M Y', strtotime($leave['end_date'])); ?>
                                                        </td>
                                                        <td><?php echo $leave['total_days']; ?> days</td>
                                                        <td>
                                                            <span class="badge bg-<?php 
                                                                echo $leave['status'] == 'approved' ? 'success' : 
                                                                     ($leave['status'] == 'rejected' ? 'danger' : 
                                                                     ($leave['status'] == 'cancelled' ? 'secondary' : 'warning'));
                                                            ?>">
                                                                <?php echo ucfirst($leave['status']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php if ($leave['approved_by_name']): ?>
                                                            <?php echo htmlspecialchars($leave['approved_by_name']); ?>
                                                            <?php else: ?>
                                                            <span class="text-muted">Pending</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-outline-info" onclick="viewLeaveDetails(<?php echo $leave['id']; ?>)">
                                                                <i class="bi bi-eye"></i> View
                                                            </button>
                                                            <?php if ($leave['status'] == 'pending'): ?>
                                                            <form method="POST" style="display:inline;" 
                                                                  onsubmit="return confirm('Are you sure you want to cancel this leave application?');">
                                                                <input type="hidden" name="leave_id" value="<?php echo $leave['id']; ?>">
                                                                <input type="hidden" name="employee_id" value="<?php echo $employee_id; ?>">
                                                                <input type="hidden" name="cancel_leave" value="1">
                                                                <button type="submit" class="btn btn-sm btn-outline-danger">
                                                                    <i class="bi bi-x-circle"></i> Cancel
                                                                </button>
                                                            </form>
                                                            <?php endif; ?>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>

                            <!-- Leave Balance Tab (Employee only) -->
                            <div class="tab-pane fade" id="balance" role="tabpanel">
                                <?php
                                // Get leave balance for current user
                                $leave_balance = [];
                                if ($employee_id) {
                                    $stmt = $pdo->prepare("SELECT * FROM leave_balance WHERE employee_id = ?");
                                    $stmt->execute([$employee_id]);
                                    $leave_balance = $stmt->fetch();
                                    
                                    if (!$leave_balance) {
                                        // Initialize leave balance
                                        $stmt = $pdo->prepare("INSERT INTO leave_balance (employee_id) VALUES (?)");
                                        $stmt->execute([$employee_id]);
                                        $leave_balance = [
                                            'casual_leaves' => 14, 'used_casual' => 0,
                                            'sick_leaves' => 7, 'used_sick' => 0,
                                            'annual_leaves' => 21, 'used_annual' => 0
                                        ];
                                    }
                                }
                                ?>
                                <div class="row">
                                    <div class="col-md-8">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="mb-0">My Leave Balance</h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <!-- Casual Leave -->
                                                    <div class="col-md-6 mb-4">
                                                        <div class="card">
                                                            <div class="card-body">
                                                                <div class="d-flex align-items-center mb-3">
                                                                    <div class="leave-type-icon bg-primary text-white">
                                                                        <i class="bi bi-emoji-smile"></i>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="mb-0">Casual Leave</h5>
                                                                        <small class="text-muted">For personal matters</small>
                                                                    </div>
                                                                </div>
                                                                <div class="progress-container mb-2">
                                                                    <?php 
                                                                    $casual_used = $leave_balance['used_casual'] ?? 0;
                                                                    $casual_total = $leave_balance['casual_leaves'] ?? 14;
                                                                    $casual_percent = $casual_total > 0 ? ($casual_used / $casual_total) * 100 : 0;
                                                                    $casual_remaining = $casual_total - $casual_used;
                                                                    ?>
                                                                    <div class="progress h-100">
                                                                        <div class="progress-bar bg-primary" style="width: <?php echo $casual_percent; ?>%"></div>
                                                                    </div>
                                                                </div>
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Used: <?php echo $casual_used; ?> days</span>
                                                                    <span>Remaining: <?php echo $casual_remaining; ?> days</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Sick Leave -->
                                                    <div class="col-md-6 mb-4">
                                                        <div class="card">
                                                            <div class="card-body">
                                                                <div class="d-flex align-items-center mb-3">
                                                                    <div class="leave-type-icon bg-info text-white">
                                                                        <i class="bi bi-heart-pulse"></i>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="mb-0">Sick Leave</h5>
                                                                        <small class="text-muted">Medical certificates required</small>
                                                                    </div>
                                                                </div>
                                                                <div class="progress-container mb-2">
                                                                    <?php 
                                                                    $sick_used = $leave_balance['used_sick'] ?? 0;
                                                                    $sick_total = $leave_balance['sick_leaves'] ?? 7;
                                                                    $sick_percent = $sick_total > 0 ? ($sick_used / $sick_total) * 100 : 0;
                                                                    $sick_remaining = $sick_total - $sick_used;
                                                                    ?>
                                                                    <div class="progress h-100">
                                                                        <div class="progress-bar bg-info" style="width: <?php echo $sick_percent; ?>%"></div>
                                                                    </div>
                                                                </div>
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Used: <?php echo $sick_used; ?> days</span>
                                                                    <span>Remaining: <?php echo $sick_remaining; ?> days</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Annual Leave -->
                                                    <div class="col-md-6 mb-4">
                                                        <div class="card">
                                                            <div class="card-body">
                                                                <div class="d-flex align-items-center mb-3">
                                                                    <div class="leave-type-icon bg-success text-white">
                                                                        <i class="bi bi-airplane"></i>
                                                                    </div>
                                                                    <div>
                                                                        <h5 class="mb-0">Annual Leave</h5>
                                                                        <small class="text-muted">Paid vacation leave</small>
                                                                    </div>
                                                                </div>
                                                                <div class="progress-container mb-2">
                                                                    <?php 
                                                                    $annual_used = $leave_balance['used_annual'] ?? 0;
                                                                    $annual_total = $leave_balance['annual_leaves'] ?? 21;
                                                                    $annual_percent = $annual_total > 0 ? ($annual_used / $annual_total) * 100 : 0;
                                                                    $annual_remaining = $annual_total - $annual_used;
                                                                    ?>
                                                                    <div class="progress h-100">
                                                                        <div class="progress-bar bg-success" style="width: <?php echo $annual_percent; ?>%"></div>
                                                                    </div>
                                                                </div>
                                                                <div class="d-flex justify-content-between">
                                                                    <span>Used: <?php echo $annual_used; ?> days</span>
                                                                    <span>Remaining: <?php echo $annual_remaining; ?> days</span>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                    
                                                    <!-- Summary -->
                                                    <div class="col-md-6 mb-4">
                                                        <div class="card bg-light">
                                                            <div class="card-body text-center">
                                                                <h5 class="mb-3">Total Available</h5>
                                                                <div class="display-4 text-primary mb-2">
                                                                    <?php echo ($casual_remaining + $sick_remaining + $annual_remaining); ?>
                                                                </div>
                                                                <p class="text-muted mb-0">Total leave days available</p>
                                                                <hr class="my-3">
                                                                <div class="row">
                                                                    <div class="col-4">
                                                                        <div class="text-primary"><?php echo $casual_remaining; ?></div>
                                                                        <small class="text-muted">Casual</small>
                                                                    </div>
                                                                    <div class="col-4">
                                                                        <div class="text-info"><?php echo $sick_remaining; ?></div>
                                                                        <small class="text-muted">Sick</small>
                                                                    </div>
                                                                    <div class="col-4">
                                                                        <div class="text-success"><?php echo $annual_remaining; ?></div>
                                                                        <small class="text-muted">Annual</small>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <div class="card">
                                            <div class="card-header">
                                                <h6 class="mb-0">Leave Summary</h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="mb-4">
                                                    <h6>Leave Year: <?php echo date('Y'); ?></h6>
                                                    <p class="small text-muted mb-0">
                                                        <i class="bi bi-calendar-check"></i> 
                                                        Leave year runs from January to December
                                                    </p>
                                                </div>
                                                
                                                <div class="mb-4">
                                                    <h6>Important Notes</h6>
                                                    <ul class="small text-muted">
                                                        <li>Leave applications must be submitted at least 3 days in advance</li>
                                                        <li>Sick leave requires medical certificate for 3+ days</li>
                                                        <li>Annual leave can be taken in minimum 3-day blocks</li>
                                                        <li>Unused casual leave cannot be carried forward</li>
                                                        <li>Annual leave can be encashed up to 50%</li>
                                                    </ul>
                                                </div>
                                                
                                                <div class="alert alert-warning">
                                                    <h6><i class="bi bi-exclamation-triangle"></i> Reminder</h6>
                                                    <p class="small mb-0">
                                                        Plan your leaves wisely. Balance will reset on 1st January <?php echo date('Y') + 1; ?>.
                                                    </p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <?php else: ?>
                            <!-- Admin/Manager Tabs Content -->
                            
                            <!-- Approvals Tab (Admin/Manager only) -->
                            <div class="tab-pane fade show <?php echo isAdmin() ? 'active' : ''; ?>" id="approvals" role="tabpanel">
                                <div class="card">
                                    <div class="card-header">
                                        <div class="d-flex justify-content-between align-items-center">
                                            <h6 class="mb-0">Leave Approvals</h6>
                                            <?php if (count($pending_leaves) > 0): ?>
                                            <form method="POST" id="bulkForm" class="d-flex align-items-center">
                                                <select name="action" class="form-control form-control-sm me-2" style="width: auto;">
                                                    <option value="">Bulk Action</option>
                                                    <option value="approve">Approve Selected</option>
                                                    <option value="reject">Reject Selected</option>
                                                </select>
                                                <input type="hidden" name="bulk_action" value="1">
                                                <button type="submit" class="btn btn-sm btn-primary" disabled>
                                                    Apply
                                                </button>
                                            </form>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                    <div class="card-body">
                                        <?php if (empty($pending_leaves)): ?>
                                        <div class="text-center py-5">
                                            <i class="bi bi-check-circle display-1 text-success"></i>
                                            <h5 class="mt-3">No pending leaves</h5>
                                            <p class="text-muted">All leave applications have been processed.</p>
                                        </div>
                                        <?php else: ?>
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th width="30">
                                                            <input type="checkbox" id="selectAll">
                                                        </th>
                                                        <th>Employee</th>
                                                        <th>Department</th>
                                                        <th>Leave Type</th>
                                                        <th>Period</th>
                                                        <th>Days</th>
                                                        <th>Applied On</th>
                                                        <th>Contact</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($pending_leaves as $leave): ?>
                                                    <tr>
                                                        <td>
                                                            <input type="checkbox" name="leave_ids[]" value="<?php echo $leave['id']; ?>" 
                                                                   class="leave-checkbox" onchange="updateBulkButton()">
                                                        </td>
                                                        <td>
                                                            <strong><?php echo htmlspecialchars($leave['full_name']); ?></strong>
                                                        </td>
                                                        <td><?php echo htmlspecialchars($leave['department']); ?></td>
                                                        <td>
                                                            <span class="badge bg-<?php 
                                                                echo $leave['leave_type'] == 'Casual Leave' ? 'primary' : 
                                                                     ($leave['leave_type'] == 'Sick Leave' ? 'info' : 
                                                                     ($leave['leave_type'] == 'Annual Leave' ? 'success' : 'warning'));
                                                            ?>">
                                                                <?php echo htmlspecialchars($leave['leave_type']); ?>
                                                            </span>
                                                        </td>
                                                        <td>
                                                            <?php echo date('d M', strtotime($leave['start_date'])) . ' - ' . 
                                                                  date('d M', strtotime($leave['end_date'])); ?>
                                                        </td>
                                                        <td><?php echo $leave['total_days']; ?> days</td>
                                                        <td><?php echo date('d M Y', strtotime($leave['applied_date'])); ?></td>
                                                        <td><?php echo htmlspecialchars($leave['contact_number'] ?? 'N/A'); ?></td>
                                                        <td>
                                                            <div class="btn-group btn-group-sm" role="group">
                                                                <a href="?page=leave&approve_leave=<?php echo $leave['id']; ?>" 
                                                                   class="btn btn-outline-success"
                                                                   onclick="return confirm('Approve this leave application?')">
                                                                    <i class="bi bi-check-lg"></i> Approve
                                                                </a>
                                                                <a href="?page=leave&reject_leave=<?php echo $leave['id']; ?>" 
                                                                   class="btn btn-outline-danger"
                                                                   onclick="return confirm('Reject this leave application?')">
                                                                    <i class="bi bi-x-lg"></i> Reject
                                                                </a>
                                                                <button type="button" class="btn btn-outline-info" 
                                                                        onclick="viewLeaveDetails(<?php echo $leave['id']; ?>, true)">
                                                                    <i class="bi bi-eye"></i> View
                                                                </button>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Manage Leave Types Tab (Admin only) -->
                            <?php if (isAdmin()): ?>
                            <div class="tab-pane fade" id="types" role="tabpanel">
                                <div class="row">
                                    <div class="col-md-12">
                                        <!-- Add New Leave Type Form -->
                                        <div class="card settings-card mb-4">
                                            <div class="card-header bg-light">
                                                <h6 class="mb-0"><i class="bi bi-plus-circle me-2"></i>Add New Leave Type</h6>
                                            </div>
                                            <div class="card-body">
                                                <form method="POST" class="row g-3">
                                                    <div class="col-md-3">
                                                        <label>Leave Type Name *</label>
                                                        <input type="text" name="type_name" class="form-control" required>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label>Days Per Year *</label>
                                                        <input type="number" name="days_per_year" class="form-control" min="0" step="0.5" required>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label>Description</label>
                                                        <input type="text" name="description" class="form-control">
                                                    </div>
                                                    <div class="col-md-1">
                                                        <label>Paid Leave?</label>
                                                        <div class="form-check mt-2">
                                                            <input type="checkbox" name="is_paid" class="form-check-input" checked>
                                                            <label class="form-check-label">Yes</label>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-1">
                                                        <label>Requires Approval?</label>
                                                        <div class="form-check mt-2">
                                                            <input type="checkbox" name="requires_approval" class="form-check-input" checked>
                                                            <label class="form-check-label">Yes</label>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-1 d-flex align-items-end">
                                                        <button type="submit" name="add_leave_type" class="btn btn-primary">
                                                            <i class="bi bi-plus"></i> Add
                                                        </button>
                                                    </div>
                                                </form>
                                            </div>
                                        </div>
                                        
                                        <!-- Leave Types List -->
                                        <div class="card settings-card">
                                            <div class="card-header bg-light">
                                                <h6 class="mb-0"><i class="bi bi-list-ul me-2"></i>Existing Leave Types</h6>
                                            </div>
                                            <div class="card-body">
                                                <?php if (empty($leave_types)): ?>
                                                <div class="text-center py-5">
                                                    <i class="bi bi-calendar-x display-1 text-muted"></i>
                                                    <h5 class="mt-3">No leave types found</h5>
                                                    <p class="text-muted">Add new leave types using the form above.</p>
                                                </div>
                                                <?php else: ?>
                                                <div class="table-responsive">
                                                    <table class="table table-hover">
                                                        <thead>
                                                            <tr>
                                                                <th>Leave Type</th>
                                                                <th>Days/Year</th>
                                                                <th>Description</th>
                                                                <th>Paid</th>
                                                                <th>Approval Required</th>
                                                                <th>Actions</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <?php foreach ($leave_types as $type): ?>
                                                            <tr>
                                                                <td>
                                                                    <strong><?php echo htmlspecialchars($type['type_name']); ?></strong>
                                                                </td>
                                                                <td>
                                                                    <span class="badge bg-primary"><?php echo $type['days_per_year']; ?> days</span>
                                                                </td>
                                                                <td><?php echo htmlspecialchars($type['description']); ?></td>
                                                                <td>
                                                                    <?php if ($type['is_paid']): ?>
                                                                    <span class="badge bg-success">Yes</span>
                                                                    <?php else: ?>
                                                                    <span class="badge bg-secondary">No</span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <?php if ($type['requires_approval']): ?>
                                                                    <span class="badge bg-warning">Required</span>
                                                                    <?php else: ?>
                                                                    <span class="badge bg-info">Not Required</span>
                                                                    <?php endif; ?>
                                                                </td>
                                                                <td>
                                                                    <button type="button" class="btn btn-sm btn-outline-primary" 
                                                                            data-bs-toggle="modal" data-bs-target="#editModal<?php echo $type['id']; ?>">
                                                                        <i class="bi bi-pencil"></i> Edit
                                                                    </button>
                                                                    <form method="POST" style="display:inline;" 
                                                                          onsubmit="return confirm('Are you sure you want to delete this leave type?');">
                                                                        <input type="hidden" name="id" value="<?php echo $type['id']; ?>">
                                                                        <button type="submit" name="delete_leave_type" class="btn btn-sm btn-outline-danger">
                                                                            <i class="bi bi-trash"></i> Delete
                                                                        </button>
                                                                    </form>
                                                                </td>
                                                            </tr>
                                                            
                                                            <!-- Edit Modal -->
                                                            <div class="modal fade" id="editModal<?php echo $type['id']; ?>" tabindex="-1">
                                                                <div class="modal-dialog">
                                                                    <div class="modal-content">
                                                                        <div class="modal-header bg-primary text-white">
                                                                            <h5 class="modal-title">Edit Leave Type</h5>
                                                                            <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                                                                        </div>
                                                                        <form method="POST">
                                                                            <div class="modal-body">
                                                                                <input type="hidden" name="id" value="<?php echo $type['id']; ?>">
                                                                                
                                                                                <div class="mb-3">
                                                                                    <label>Leave Type Name *</label>
                                                                                    <input type="text" name="type_name" class="form-control" 
                                                                                           value="<?php echo htmlspecialchars($type['type_name']); ?>" required>
                                                                                </div>
                                                                                <div class="mb-3">
                                                                                    <label>Days Per Year *</label>
                                                                                    <input type="number" name="days_per_year" class="form-control" 
                                                                                           value="<?php echo $type['days_per_year']; ?>" min="0" step="0.5" required>
                                                                                </div>
                                                                                <div class="mb-3">
                                                                                    <label>Description</label>
                                                                                    <input type="text" name="description" class="form-control" 
                                                                                           value="<?php echo htmlspecialchars($type['description']); ?>">
                                                                                </div>
                                                                                <div class="mb-3">
                                                                                    <div class="form-check">
                                                                                        <input type="checkbox" name="is_paid" class="form-check-input" 
                                                                                               id="is_paid<?php echo $type['id']; ?>" 
                                                                                               <?php echo $type['is_paid'] ? 'checked' : ''; ?>>
                                                                                        <label class="form-check-label" for="is_paid<?php echo $type['id']; ?>">
                                                                                            Paid Leave
                                                                                        </label>
                                                                                    </div>
                                                                                </div>
                                                                                <div class="mb-3">
                                                                                    <div class="form-check">
                                                                                        <input type="checkbox" name="requires_approval" class="form-check-input" 
                                                                                               id="requires_approval<?php echo $type['id']; ?>" 
                                                                                               <?php echo $type['requires_approval'] ? 'checked' : ''; ?>>
                                                                                        <label class="form-check-label" for="requires_approval<?php echo $type['id']; ?>">
                                                                                            Requires Approval
                                                                                        </label>
                                                                                    </div>
                                                                                </div>
                                                                            </div>
                                                                            <div class="modal-footer">
                                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                                                                                <button type="submit" name="update_leave_type" class="btn btn-primary">Update</button>
                                                                            </div>
                                                                        </form>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <?php endforeach; ?>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <?php endif; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- View Leave Details Modal -->
    <div class="modal fade" id="viewLeaveModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title"><i class="bi bi-eye"></i> Leave Details</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body" id="leaveDetailsContent">
                    Loading...
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>

    
    <script>
    // Switch tabs
    function switchTab(tabId) {
        const tab = new bootstrap.Tab(document.getElementById(tabId));
        tab.show();
    }
    
    <?php if (!isAdmin() && !isManager()): ?>
    // Update available balance based on leave type (Employee only)
    function updateLeaveBalance(leaveType) {
        const balanceInput = document.getElementById('availableBalance');
        
        <?php 
        $casual_bal = ($leave_balance['casual_leaves'] ?? 14) - ($leave_balance['used_casual'] ?? 0);
        $sick_bal = ($leave_balance['sick_leaves'] ?? 7) - ($leave_balance['used_sick'] ?? 0);
        $annual_bal = ($leave_balance['annual_leaves'] ?? 21) - ($leave_balance['used_annual'] ?? 0);
        ?>
        
        switch(leaveType) {
            case 'Casual Leave':
                balanceInput.value = '<?php echo $casual_bal; ?> days available';
                break;
            case 'Sick Leave':
                balanceInput.value = '<?php echo $sick_bal; ?> days available';
                break;
            case 'Annual Leave':
                balanceInput.value = '<?php echo $annual_bal; ?> days available';
                break;
            case 'Maternity Leave':
                balanceInput.value = '90 days (Special Leave)';
                break;
            case 'Paternity Leave':
                balanceInput.value = '7 days (Special Leave)';
                break;
            case 'Unpaid Leave':
                balanceInput.value = 'No limit (Subject to approval)';
                break;
            default:
                balanceInput.value = 'Select leave type';
        }
        calculateDays();
    }
    
    // Calculate working days between dates (Employee only)
    function calculateDays() {
        const startDate = document.querySelector('input[name="start_date"]').value;
        const endDate = document.querySelector('input[name="end_date"]').value;
        const totalDaysInput = document.getElementById('totalDays');
        const returnDateInput = document.getElementById('returnDate');
        
        if (startDate && endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            
            if (start > end) {
                totalDaysInput.value = 'Invalid date range';
                returnDateInput.value = '';
                return;
            }
            
            // Calculate working days (Monday to Friday)
            let workingDays = 0;
            const current = new Date(start);
            
            while (current <= end) {
                const dayOfWeek = current.getDay();
                if (dayOfWeek !== 0 && dayOfWeek !== 6) { // Not Sunday (0) or Saturday (6)
                    workingDays++;
                }
                current.setDate(current.getDate() + 1);
            }
            
            totalDaysInput.value = workingDays + ' working day(s)';
            
            // Calculate return to work date (next working day after end date)
            const returnDate = new Date(end);
            returnDate.setDate(returnDate.getDate() + 1);
            
            // Skip weekends
            while (returnDate.getDay() === 0 || returnDate.getDay() === 6) {
                returnDate.setDate(returnDate.getDate() + 1);
            }
            
            returnDateInput.value = returnDate.toLocaleDateString('en-US', {
                weekday: 'long', 
                year: 'numeric', 
                month: 'long', 
                day: 'numeric'
            });
        } else {
            totalDaysInput.value = '';
            returnDateInput.value = '';
        }
    }
    
    // Reset form (Employee only)
    function resetForm() {
        document.getElementById('leaveForm').reset();
        document.getElementById('availableBalance').value = '';
        document.getElementById('totalDays').value = '';
        document.getElementById('returnDate').value = '';
    }
    <?php endif; ?>
    
    // View leave details
    function viewLeaveDetails(leaveId, isAdmin = false) {
        fetch(`ajax/get_leave_details.php?id=${leaveId}&admin=${isAdmin ? '1' : '0'}`)
            .then(response => response.text())
            .then(html => {
                document.getElementById('leaveDetailsContent').innerHTML = html;
                const modal = new bootstrap.Modal(document.getElementById('viewLeaveModal'));
                modal.show();
            })
            .catch(error => {
                document.getElementById('leaveDetailsContent').innerHTML = 
                    '<div class="alert alert-danger">Error loading leave details</div>';
            });
    }
    
    // Bulk actions for admins
    document.getElementById('selectAll')?.addEventListener('change', function() {
        const checkboxes = document.querySelectorAll('.leave-checkbox');
        checkboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
        updateBulkButton();
    });
    
    function updateBulkButton() {
        const checkboxes = document.querySelectorAll('.leave-checkbox:checked');
        const bulkButton = document.querySelector('#bulkForm button[type="submit"]');
        const bulkForm = document.getElementById('bulkForm');
        
        if (checkboxes.length > 0 && bulkButton) {
            bulkButton.disabled = false;
            
            // Create hidden inputs for checked leaves
            const existingInputs = bulkForm.querySelectorAll('input[name="leave_ids[]"]');
            existingInputs.forEach(input => input.remove());
            
            checkboxes.forEach(checkbox => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'leave_ids[]';
                input.value = checkbox.value;
                bulkForm.appendChild(input);
            });
        } else if (bulkButton) {
            bulkButton.disabled = true;
        }
    }
    
    // Initialize
    document.addEventListener('DOMContentLoaded', function() {
        // Add event listeners to checkboxes
        document.querySelectorAll('.leave-checkbox').forEach(checkbox => {
            checkbox.addEventListener('change', updateBulkButton);
        });
        
        <?php if (!isAdmin() && !isManager()): ?>
        // Initialize employee form
        const leaveTypeSelect = document.querySelector('select[name="leave_type"]');
        if (leaveTypeSelect) {
            updateLeaveBalance(leaveTypeSelect.value);
        }
        <?php endif; ?>
    });
    </script>
</body>
</html>  