<?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'] ?? '')));

/* =========================
   PERMISSIONS
   ========================= */
if (!in_array($role, ['super_admin', 'platform_admin', 'rsp_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');
}

$companyId   = (int)($input['company_id'] ?? 0);
$companyName = trim($input['company_name'] ?? '');

if ($companyId <= 0) {
    error_bad_request('Invalid company_id');
}

if ($companyName === '' || mb_strlen($companyName) < 3) {
    error_bad_request('Company name must be at least 3 characters');
}

/* =========================
   LOAD COMPANY
   ========================= */
$stmt = $pdo->prepare("
    SELECT id, rsp_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');
}

/* =========================
   RSP SCOPING
   ========================= */
if (
    $role === 'rsp_admin' &&
    (int)$company['rsp_id'] !== (int)$actor['company_id']
) {
    error_forbidden('Forbidden');
}

/* =========================
   UPDATE
   ========================= */
$stmt = $pdo->prepare("
    UPDATE companies
    SET company_name = :company_name
    WHERE id = :id
");
$stmt->execute([
    'company_name' => $companyName,
    'id'           => $companyId
]);

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

/* =========================
   AUDIT
   ========================= */
   
audit_log(
    $pdo,
    $user,
    'update',
    'company',
    (int)$companyId,
    ['changed' => $changedFields]
);

