<?php
declare(strict_types=1);

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

$data = json_decode(file_get_contents('php://input'), true);

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

$employeeId = (int)$data['employee_id'];
$db = Database::getInstance();

/**
 * Prevent self delete
 */
if ($employeeId === (int)$_SESSION['employee_id']) {
    Response::error('You cannot delete your own account', 403);
}

/**
 * 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);
}

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

/**
 * Get target employee
 */
$stmt = $db->prepare("
    SELECT e.id, r.level, r.name AS role_name
    FROM employees e
    JOIN roles r ON r.id = e.role_id
    WHERE e.id = :id
");
$stmt->execute(['id' => $employeeId]);
$target = $stmt->fetch();

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

/**
 * Protect Super Admin
 */
if ($target['role_name'] === 'Super Admin') {
    Response::error('Super Admin cannot be deleted', 403);
}

/**
 * Role hierarchy enforcement
 */
if ((int)$target['level'] >= $currentLevel) {
    Response::error('You cannot delete an employee with equal or higher role', 403);
}

/**
 * HARD DELETE
 */
$stmt = $db->prepare("DELETE FROM employees WHERE id = :id");
$stmt->execute(['id' => $employeeId]);

Logger::auth('Employee hard deleted', [
    'employee_id' => $employeeId,
    'deleted_by'  => $_SESSION['employee_id']
]);

Response::success('Employee deleted permanently');
