<?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/Validator.php';
require_once __DIR__ . '/../../core/Logger.php';

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

Validator::required($data, ['employee_id']);

$targetEmployeeId = (int)$data['employee_id'];

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

$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);
}

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

/**
 * Get target employee role & status
 */
$stmt = $db->prepare("
    SELECT e.status, 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' => $targetEmployeeId]);
$target = $stmt->fetch();

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

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

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

/**
 * Already inactive?
 */
if ($target['status'] !== 'active') {
    Response::error('Employee is already inactive', 409);
}

/**
 * Deactivate employee
 */
$stmt = $db->prepare("
    UPDATE employees
    SET status = 'inactive',
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");

$stmt->execute([
    'updated_by' => $_SESSION['employee_id'],
    'id'         => $targetEmployeeId
]);

Logger::auth('Employee deactivated', [
    'deactivated_employee_id' => $targetEmployeeId,
    'by' => $_SESSION['employee_id']
]);

Response::success('Employee deactivated successfully');
