<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../core/Response.php';

$db = Database::getInstance();

/**
 * Pagination params
 */
$page  = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
$limit = isset($_GET['limit']) ? max(1, min(100, (int)$_GET['limit'])) : 10;
$offset = ($page - 1) * $limit;

/**
 * Get current user's role level
 */
$stmt = $db->prepare("
    SELECT r.level
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $_SESSION['employee_id']]);
$current = $stmt->fetch();

if (!$current) {
    Response::error('Unauthorized', 401);
}

$currentLevel = (int)$current['level'];

/**
 * Count total employees visible to current user
 */
$countStmt = $db->prepare("
    SELECT COUNT(*) AS total
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE r.level < :current_level
");
$countStmt->execute(['current_level' => $currentLevel]);
$total = (int)$countStmt->fetch()['total'];

/**
 * Fetch employees
 */
$listStmt = $db->prepare("
    SELECT
        e.id,
        e.first_name,
        e.last_name,
        e.email,
        e.mobile,
        e.status,
        e.last_login_at,
        e.created_at,
        r.id   AS role_id,
        r.name AS role_name,
        r.level AS role_level
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE r.level < :current_level
    ORDER BY e.created_at DESC
    LIMIT :limit OFFSET :offset
");

$listStmt->bindValue(':current_level', $currentLevel, PDO::PARAM_INT);
$listStmt->bindValue(':limit', $limit, PDO::PARAM_INT);
$listStmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$listStmt->execute();

$employees = $listStmt->fetchAll();

Response::success('Employee list fetched successfully', [
    'pagination' => [
        'page'  => $page,
        'limit'=> $limit,
        'total'=> $total
    ],
    'employees' => $employees
]);
