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

$sql = "SELECT 
            la.id,
            u.full_name AS employee_name,
            la.leave_type,
            la.apply_date,              -- NEW
            la.start_date,
            la.end_date,
            la.number_of_days,
            la.reason,
            (
                SELECT COALESCE(SUM(number_of_days),0)
                FROM leave_applications
                WHERE user_id = la.user_id
                  AND status  = 'approved'
                  AND year    = la.year
            ) AS total_leaves
        FROM leave_applications la
        JOIN users u ON la.user_id = u.id
        WHERE la.status = 'pending'
        ORDER BY la.apply_date DESC";

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

$data = [];
while ($row = $result->fetch_assoc()) {
    // format apply_date if you want
    $row['apply_date'] = date('Y-m-d H:i', strtotime($row['apply_date']));
    $data[] = $row;
}

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