<?php
// POST /api/employees/leave_list.php
require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../config/auth.php';

$user = requireRole([1, 5]);
$db   = getDB();
$p    = getPagination();

$status     = post('status', '');
$employeeId = (int)post('employee_id', 0);
$where      = ['1=1'];
$params     = [];

if ($status)     { $where[] = 'el.status = ?';      $params[] = $status; }
if ($employeeId) { $where[] = 'el.employee_id = ?'; $params[] = $employeeId; }

$whereStr = implode(' AND ', $where);

$countStmt = $db->prepare("SELECT COUNT(*) FROM employee_leave el WHERE $whereStr");
$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,
           u.full_name AS approved_by_name
    FROM employee_leave el
    JOIN employees e ON e.id = el.employee_id
    LEFT JOIN users u ON u.id = el.approved_by
    WHERE $whereStr
    ORDER BY el.created_at DESC
    LIMIT {$p['limit']} OFFSET {$p['offset']}
");
$stmt->execute($params);

apiSuccess([
    'leave'      => $stmt->fetchAll(),
    'pagination' => ['total' => $total, 'page' => $p['page'], 'limit' => $p['limit'], 'pages' => ceil($total / $p['limit'])]
]);
