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

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

$search  = post('search', '');
$status  = post('status', '');
$dept    = post('department', '');
$where   = ['1=1'];
$params  = [];

if ($search) {
    $where[]  = '(e.first_name LIKE ? OR e.last_name LIKE ? OR e.employee_number LIKE ? OR e.work_email LIKE ?)';
    $params   = array_merge($params, ["%$search%", "%$search%", "%$search%", "%$search%"]);
}
if ($status) { $where[] = 'e.status = ?';     $params[] = $status; }
if ($dept)   { $where[] = 'e.department = ?'; $params[] = $dept; }

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

$countStmt = $db->prepare("SELECT COUNT(*) FROM employees e WHERE $whereStr");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();

$stmt = $db->prepare("
    SELECT e.id, e.employee_number, e.first_name, e.last_name,
           e.job_title, e.department, e.employment_type,
           e.work_email, e.phone, e.status, e.start_date, e.user_id,
           u.username AS linked_username, u.full_name AS linked_user_name,
           (SELECT es.basic_salary FROM employee_salaries es WHERE es.employee_id = e.id ORDER BY es.effective_date DESC LIMIT 1) AS current_salary
    FROM employees e
    LEFT JOIN users u ON u.id = e.user_id
    WHERE $whereStr
    ORDER BY e.first_name ASC, e.last_name ASC
    LIMIT {$p['limit']} OFFSET {$p['offset']}
");
$stmt->execute($params);
$employees = $stmt->fetchAll();

apiSuccess([
    'employees'  => $employees,
    'pagination' => [
        'total' => $total,
        'page'  => $p['page'],
        'limit' => $p['limit'],
        'pages' => ceil($total / $p['limit']),
    ]
]);
