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

$user_id = $_SESSION['user_id'];

$start_date = $_GET['start_date'] ?? '';
$end_date = $_GET['end_date'] ?? '';

$where = "WHERE user_id = $user_id";

if ($start_date && $end_date) {
    $where .= " AND start_date >= '$start_date' AND end_date <= '$end_date'";
}

$sql = "SELECT * FROM leave_applications $where ORDER BY apply_date DESC";
$result = $conn->query($sql);

$data = [];
while ($row = $result->fetch_assoc()) {
    $data[] = [
        'leave_type' => ucfirst($row['leave_type']),
        'start_date' => date('Y-m-d', strtotime($row['start_date'])),
        'end_date' => date('Y-m-d', strtotime($row['end_date'])),
        'number_of_days' => $row['number_of_days'],
        'reason' => $row['reason'],
        'apply_date' => date('Y-m-d H:i', strtotime($row['apply_date'])),
        'status' => $row['status']
    ];
}

header('Content-Type: application/json');
echo json_encode($data);
?>
