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

// Optional date range for all employees
$start_date = $_REQUEST['start_date'] ?? '';
$end_date   = $_REQUEST['end_date'] ?? '';

$where = "WHERE 1=1";

if (!empty($start_date) && !empty($end_date)) {
    $start_date_sql = $conn->real_escape_string($start_date);
    $end_date_sql   = $conn->real_escape_string($end_date);
    $where .= " AND la.start_date >= '$start_date_sql' AND la.end_date <= '$end_date_sql'";
}

$sql = "SELECT 
            la.*,
            u.full_name      AS full_name,
            u.employee_id    AS emp_id,
            u.department     AS department
        FROM leave_applications la
        JOIN users u ON la.user_id = u.id
        $where
        ORDER BY la.apply_date DESC";

$result = $conn->query($sql);

$data = [];
if ($result) {
    while ($row = $result->fetch_assoc()) {
        $data[] = [
            'employee_id'    => $row['emp_id'],
            'employee_name'  => $row['full_name'],
            'department'     => $row['department'],
            '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);
exit;
?>
