<?php
declare(strict_types=1);

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

if (empty($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    Response::error('Valid employee id required', 422);
}

$employeeId = (int)$_GET['id'];
$db = Database::getInstance();

/**
 * Get current user 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']]);
$currentUser = $stmt->fetch();

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

/**
 * Fetch employee
 */
$stmt = $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.name  AS role_name,
        r.level AS role_level
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $employeeId]);
$employee = $stmt->fetch();

if (!$employee) {
    Response::error('Employee not found', 404);
}

/**
 * Role hierarchy enforcement
 */
if ((int)$employee['role_level'] >= (int)$currentUser['level']) {
    Response::error('Access denied', 403);
}

unset($employee['role_level']);

Response::success('Employee fetched', $employee);
