<?php
require_once 'config.php';
require_once 'auth_functions.php';
requireLogin();

$user_id      = $_SESSION['user_id'];
$employee_id  = $_SESSION['employee_id'];
$current_year = date('Y');
$current_month = date('n');

$message = '';
$error   = '';

// 1) Handle delete request (must be before main apply logic)
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_leave_id'])) {
    $delete_id = (int)$_POST['delete_leave_id'];

    // Only delete if it belongs to this user and still pending
    $sql_delete = "DELETE FROM leave_applications 
                   WHERE id = $delete_id 
                     AND user_id = $user_id 
                     AND status = 'pending'";
    if ($conn->query($sql_delete)) {
        if ($conn->affected_rows > 0) {
            $message = "Leave application deleted successfully.";
        } else {
            $error = "Leave cannot be deleted. It may already be approved or rejected.";
        }
    } else {
        $error = "Error deleting leave application: " . $conn->error;
    }
}

// 2) Handle new leave application
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !isset($_POST['delete_leave_id'])) {
    $leave_type       = $_POST['leave_type'];
    $start_date       = $_POST['start_date'];
    $end_date         = $_POST['end_date'];
    $reason           = $conn->real_escape_string($_POST['reason']);
    $is_half_day      = isset($_POST['is_half_day']) ? 1 : 0;
    $half_day_session = $_POST['half_day_session'] ?? 'none';
    $short_leave_time = $_POST['short_leave_time'] ?? '';

    // Get number of days from user input
    $number_of_days = floatval($_POST['leave_days'] ?? 0);

    // If half day is selected, force number_of_days to 0.5 and dates equal
    if ($is_half_day) {
        $number_of_days = 0.5;
        $end_date = $start_date;
    }

    $year  = date('Y', strtotime($start_date));
    $month = date('n', strtotime($start_date));

    // Validation checks
    $can_apply = true;

    if ($number_of_days <= 0) {
        $error = "Please enter a valid number of leave days.";
        $can_apply = false;
    }

    // Get current leave balance
    if ($can_apply) {
        $sql_balance = "SELECT * FROM leave_balance WHERE user_id = $user_id AND year = $year";
        $balance_result = $conn->query($sql_balance);

        if ($balance_result->num_rows === 0) {
            $sql_create = "INSERT INTO leave_balance (user_id, year) VALUES ($user_id, $year)";
            $conn->query($sql_create);
            $balance_result = $conn->query($sql_balance);
        }

        $balance = $balance_result->fetch_assoc();

        // Check leave limits
        if ($leave_type === 'casual') {
            if (($balance['casual_leaves_used'] + $number_of_days) > 20) {
                $error = "You have exceeded your casual leave limit (20 per year)";
                $can_apply = false;
            }

            // Daily casual leave limit (max 5 employees per day)
            $sql_daily_check = "SELECT COUNT(DISTINCT user_id) as count FROM leave_applications 
                                WHERE leave_type = 'casual' 
                                  AND status = 'approved'
                                  AND '$start_date' BETWEEN start_date AND end_date";
            $daily_result = $conn->query($sql_daily_check);
            $daily_count  = $daily_result->fetch_assoc()['count'];

            if ($daily_count >= 5) {
                $error = "Maximum 5 employees can take casual leave on this date. Please choose another date.";
                $can_apply = false;
            }
        } elseif ($leave_type === 'medical') {
            if (($balance['medical_leaves_used'] + $number_of_days) > 21) {
                $error = "You have exceeded your medical leave limit (21 per year)";
                $can_apply = false;
            }
        } elseif ($leave_type === 'short') {
            // Short leave monthly limit (max 2 per month)
            $sql_short_check = "SELECT * FROM short_leave_tracking 
                                WHERE user_id = $user_id AND year = $year AND month = $month";
            $short_result = $conn->query($sql_short_check);

            if ($short_result->num_rows === 0) {
                $sql_create_short = "INSERT INTO short_leave_tracking (user_id, year, month, short_leaves_count) 
                                     VALUES ($user_id, $year, $month, 0)";
                $conn->query($sql_create_short);
                $short_result = $conn->query($sql_short_check);
            }

            $short_data = $short_result->fetch_assoc();
            if ($short_data['short_leaves_count'] >= 2) {
                $error = "You have exceeded your short leave limit (2 per month)";
                $can_apply = false;
            }
        }
    }

    if ($can_apply) {
        // Insert leave application
        $sql_insert = "INSERT INTO leave_applications 
                       (user_id, employee_id, leave_type, start_date, end_date, is_half_day, 
                        half_day_session, short_leave_time, reason, number_of_days, year, month) 
                       VALUES 
                       ($user_id, '$employee_id', '$leave_type', '$start_date', '$end_date', $is_half_day, 
                        '$half_day_session', '$short_leave_time', '$reason', $number_of_days, $year, $month)";

        if ($conn->query($sql_insert)) {
            $message = "Leave application submitted successfully!";
        } else {
            $error = "Error submitting leave application: " . $conn->error;
        }
    }
}

// 3) Load current user's leave applications for listing & delete
$sql_my_leaves = "SELECT id, leave_type, start_date, end_date, number_of_days, status 
                  FROM leave_applications 
                  WHERE user_id = $user_id 
                  ORDER BY apply_date DESC";
$my_leaves_result = $conn->query($sql_my_leaves);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Apply Leave - Leave Management System</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }
        .form-card {
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
    </style>
</head>
<body>
    <!-- Navbar -->
    <nav class="navbar navbar-expand-lg navbar-dark">
        <div class="container-fluid">
            <a class="navbar-brand" href="#">
                <i class="fas fa-calendar-check"></i> Leave Management System
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav ms-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="user_dashboard.php">
                            <i class="fas fa-home"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="apply_leave.php">
                            <i class="fas fa-plus-circle"></i> Apply Leave
                        </a>
                    </li>
                    <li class="nav-item dropdown">
                        <a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown">
                            <i class="fas fa-user"></i> <?php echo $_SESSION['full_name']; ?>
                        </a>
                        <ul class="dropdown-menu">
                            <li><a class="dropdown-item" href="logout.php"><i class="fas fa-sign-out-alt"></i> Logout</a></li>
                        </ul>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container mt-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="card form-card">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-plus-circle"></i> Apply for Leave</h5>
                    </div>
                    <div class="card-body">
                        <?php if ($message): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle"></i> <?php echo $message; ?>
                            </div>
                        <?php endif; ?>

                        <?php if ($error): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
                            </div>
                        <?php endif; ?>

                        <form method="POST" action="" id="leaveForm">
                            <div class="mb-3">
                                <label class="form-label">Leave Type <span class="text-danger">*</span></label>
                                <select class="form-select" name="leave_type" id="leave_type" required>
                                    <option value="">Select Leave Type</option>
                                    <option value="casual">Casual Leave</option>
                                    <option value="medical">Medical Leave</option>
                                    <option value="duty">Duty Leave</option>
                                    <option value="short">Short Leave</option>
                                </select>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Start Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="start_date" id="start_date" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">End Date <span class="text-danger">*</span></label>
                                <input type="date" class="form-control" name="end_date" id="end_date" required>
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Number of Days <span class="text-danger">*</span></label>
                                <input type="number" class="form-control" name="leave_days" id="leave_days"
                                       step="0.5" min="0.5" required>
                            </div>

                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" name="is_half_day" id="is_half_day">
                                    <label class="form-check-label" for="is_half_day">
                                        Half Day Leave
                                    </label>
                                </div>
                            </div>

                            <div class="mb-3" id="half_day_session_div" style="display: none;">
                                <label class="form-label">Half Day Session</label>
                                <select class="form-select" name="half_day_session" id="half_day_session">
                                    <option value="none">Select Session</option>
                                    <option value="first_half">First Half (Morning)</option>
                                    <option value="second_half">Second Half (Afternoon)</option>
                                </select>
                            </div>

                            <div class="mb-3" id="short_leave_time_div" style="display: none;">
                                <label class="form-label">Short Leave Time</label>
                                <input type="text" class="form-control" name="short_leave_time" 
                                       placeholder="e.g., 10:00 AM - 12:00 PM">
                            </div>

                            <div class="mb-3">
                                <label class="form-label">Reason <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="reason" rows="4" required></textarea>
                            </div>

                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane"></i> Submit Leave Application
                                </button>
                                <a href="user_dashboard.php" class="btn btn-secondary">
                                    <i class="fas fa-arrow-left"></i> Back to Dashboard
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- My Leaves section -->
                <div class="mt-5">
                    <h5><i class="fas fa-list"></i> My Leave Applications</h5>
                    <div class="table-responsive mt-3">
                        <table class="table table-striped table-hover align-middle">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Type</th>
                                    <th>From</th>
                                    <th>To</th>
                                    <th>Days</th>
                                    <th>Status</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            <?php if ($my_leaves_result && $my_leaves_result->num_rows > 0): ?>
                                <?php while ($row = $my_leaves_result->fetch_assoc()): ?>
                                    <tr>
                                        <td><?php echo $row['id']; ?></td>
                                        <td><?php echo ucfirst($row['leave_type']); ?></td>
                                        <td><?php echo $row['start_date']; ?></td>
                                        <td><?php echo $row['end_date']; ?></td>
                                        <td><?php echo $row['number_of_days']; ?></td>
                                        <td><?php echo ucfirst($row['status']); ?></td>
                                        <td>
                                            <?php if ($row['status'] === 'pending'): ?>
                                                <form method="POST" action=""
                                                      onsubmit="return confirm('Are you sure you want to delete this pending leave?');"
                                                      style="display:inline;">
                                                    <input type="hidden" name="delete_leave_id" value="<?php echo $row['id']; ?>">
                                                    <button type="submit" class="btn btn-sm btn-danger">
                                                        <i class="fas fa-trash"></i> Delete
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <span class="text-muted">No action</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                <?php endwhile; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="7" class="text-center text-muted">No leave applications yet.</td>
                                </tr>
                            <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

            </div>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        $(document).ready(function() {
            const today = new Date().toISOString().split('T')[0];
            $('#start_date').attr('min', today);
            $('#end_date').attr('min', today);

            $('#leave_type').change(function() {
                const leaveType = $(this).val();
                if (leaveType === 'short') {
                    $('#short_leave_time_div').show();
                    $('#start_date').val(today);
                    $('#end_date').val(today);
                    $('#start_date').prop('readonly', true);
                    $('#end_date').prop('readonly', true);
                } else {
                    $('#short_leave_time_div').hide();
                    $('#start_date').prop('readonly', false);
                    $('#end_date').prop('readonly', false);
                }
            });

            $('#is_half_day').change(function() {
                if ($(this).is(':checked')) {
                    $('#half_day_session_div').show();
                    const startDate = $('#start_date').val();
                    $('#end_date').val(startDate);
                    $('#leave_days').val(0.5);
                    $('#leave_days').prop('readonly', true);
                } else {
                    $('#half_day_session_div').hide();
                    $('#half_day_session').val('none');
                    $('#leave_days').prop('readonly', false);
                }
            });

            $('#start_date').change(function() {
                const startDate = $(this).val();
                $('#end_date').attr('min', startDate);
                if ($('#is_half_day').is(':checked')) {
                    $('#end_date').val(startDate);
                }
            });
        });
    </script>
</body>
</html>
