<?php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';
$user   = requireRole([1, 5]);
$db     = getDB();
$p      = getPagination();
$status = post('status', '');
$empId  = (int)post('employee_id', 0);
$year   = (int)post('year', date('Y'));
$type   = post('leave_type', '');

$where = ['YEAR(el.start_date) = ?'];
$params = [$year];
if ($status) { $where[] = 'el.status = ?'; $params[] = $status; }
if ($empId)  { $where[] = 'el.employee_id = ?'; $params[] = $empId; }
if ($type)   { $where[] = 'el.leave_type = ?'; $params[] = $type; }
$ws = implode(' AND ', $where);

$countStmt = $db->prepare("SELECT COUNT(*) FROM employee_leave el WHERE $ws");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

$stmt = $db->prepare("
    SELECT el.*, CONCAT(e.first_name,' ',e.last_name) AS employee_name, e.employee_number, e.department,
           CONCAT(au.full_name) AS approved_by_name
    FROM employee_leave el
    JOIN employees e ON e.id = el.employee_id
    LEFT JOIN users au ON au.id = el.approved_by
    WHERE $ws
    ORDER BY el.created_at DESC
    LIMIT {$p['limit']} OFFSET {$p['offset']}
");
$stmt->execute($params);
apiSuccess([
    'leaves'     => $stmt->fetchAll(),
    'pagination' => ['total'=>$total,'page'=>$p['page'],'limit'=>$p['limit'],'pages'=>ceil($total/$p['limit'])]
]);
