<?php
declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| TechStackBase – Delete User (Soft Delete)
|--------------------------------------------------------------------------
*/

require_once __DIR__ . '/../system/bootstrap.php';
require_once __DIR__ . '/../system/response.php';
require_once __DIR__ . '/../system/auth.php';
require_once __DIR__ . '/../system/audit.php';

header('Content-Type: application/json');

try {

    /* =========================
       AUTH
       ========================= */
    $actor = require_auth($pdo);
    $actorRole = strtolower(trim((string)($actor['role_key'] ?? '')));

    if (!in_array($actorRole, ['super_admin', 'platform_admin', 'company_admin'], true)) {
        error_forbidden('Forbidden');
    }

    /* =========================
       METHOD
       ========================= */
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        error_bad_request('Invalid method');
    }

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

    if (!is_array($input)) {
        error_bad_request('Invalid JSON');
    }

    $userId = (int)($input['id'] ?? 0);
    if ($userId <= 0) {
        error_bad_request('Invalid user id');
    }

    // Prevent self-delete
    if ((int)$actor['id'] === $userId) {
        error_bad_request('You cannot delete your own account');
    }

    /* =========================
       LOAD TARGET USER
       ========================= */
    $stmt = $pdo->prepare("
        SELECT id, company_id
        FROM users
        WHERE id = :id
          AND deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute(['id' => $userId]);
    $target = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$target) {
        error_not_found('User not found or already deleted');
    }

    /* =========================
       COMPANY ISOLATION
       ========================= */
    if (
        $actorRole === 'company_admin' &&
        (int)$actor['company_id'] !== (int)$target['company_id']
    ) {
        error_forbidden('Forbidden');
    }

    /* =========================
       DELETE (SOFT)
       ========================= */
    $pdo->beginTransaction();

    try {

        $pdo->prepare("
            UPDATE users
            SET deleted_at = NOW()
            WHERE id = :id
        ")->execute(['id' => $userId]);

        // Revoke all tokens
        $pdo->prepare("
            DELETE FROM auth_tokens
            WHERE user_id = :id
        ")->execute(['id' => $userId]);

        $pdo->commit();

    } catch (Throwable $e) {
        $pdo->rollBack();
        error_server('Delete failed');
    }

    /* =========================
       RESPONSE
       ========================= */
    success('User deleted');
    
    /* =========================
       AUDIT
       ========================= */
       
    audit_log(
    $pdo,
    $user,
    'create',
    'user',
    (int)$newUserId
);


} catch (Throwable $e) {
    error_server('Delete failed');
}
