<?php
declare(strict_types=1);

require_once __DIR__ . '/../../security/auth_guard.php';
//require_once __DIR__ . '/../../security/csrf.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']) ||
    empty($data['status']) ||
    !in_array($data['status'], ['active', 'suspended'], true)
) {
    Response::error('Invalid request', 422);
}

$employeeId = (int)$data['employee_id'];
$newStatus  = $data['status'];

/**
 * Role check (simple)
 */
$role = $_SESSION['role'] ?? '';
if (!in_array($role, ['Admin', 'Super Admin'], true)) {
    Response::error('Permission denied', 403);
}

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

$db = Database::getInstance();

/**
 * Update status
 */
$stmt = $db->prepare("
    UPDATE employees
    SET status = :status,
        updated_by = :updated_by,
        updated_at = NOW()
    WHERE id = :id
");
$stmt->execute([
    'status'     => $newStatus,
    'updated_by'=> $_SESSION['employee_id'],
    'id'         => $employeeId
]);

Logger::auth('Employee status updated (simple)', [
    'employee_id' => $employeeId,
    'status'      => $newStatus,
    'updated_by'  => $_SESSION['employee_id']
]);

Response::success('Employee status updated');
