<?php
declare(strict_types=1);

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

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

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

/* =========================
   LEGAL HOLD
   ========================= */
if (legal_hold_enabled($pdo)) {
    error_forbidden('Legal hold active. Operation not permitted.');
}

/* =========================
   PERMISSIONS
   ========================= */
if (!in_array($role, ['super_admin', 'platform_admin'], true)) {
    error_forbidden('Only platform or super administrators may delete companies');
}

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

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

/* =========================
   LOAD COMPANY
   ========================= */
$stmt = $pdo->prepare("
    SELECT id
    FROM companies
    WHERE id = :id
      AND deleted_at IS NULL
    LIMIT 1
");
$stmt->execute(['id' => $companyId]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    error_not_found('Company not found');
}

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

try {

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

    $pdo->commit();

} catch (Throwable $e) {
    $pdo->rollBack();
    error_server('Failed to delete company');
}


/* =========================
   RESPONSE
   ========================= */
success('Company deleted', [
    'company_id' => $companyId
]);

/* =========================
   AUDIT
   ========================= */
audit_log(
    $pdo,
    $user,
    'delete',
    'company',
    (int)$companyId
);

