<?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  = $actor['role_key'];

/* =========================
   PERMISSIONS (rank-based)
   ========================= */
/*
Allowed:
super_admin
platform_admin
rsp_owner
rsp_admin
*/
if ($actor['role_rank'] > 5) {
    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');
}

$companyName = trim((string)($input['company_name'] ?? ''));
$rspIdInput  = isset($input['rsp_id']) ? (int)$input['rsp_id'] : null;
$productInput = isset($input['product_id']) ? (int)$input['product_id'] : null;

if ($companyName === '') {
    error_bad_request('Company name is required');
}

/* =========================
   PRODUCT CONTEXT
   ========================= */

if ($actor['is_global']) {

    if ($productInput === null) {
        error_bad_request('Product required');
    }

    $productId = $productInput;

} else {

    $productId = $actor['product_id'];

}

/* =========================
   RSP CONTEXT
   ========================= */

$rspId = null;

/* Creating RSP (rsp_id null) */
if ($rspIdInput === null) {

    if (!$actor['is_global']) {
        error_forbidden('Only global roles may create RSP');
    }

} else {

    /* Validate RSP exists */
    $stmt = $pdo->prepare("
        SELECT id, product_id
        FROM companies
        WHERE id = :id
          AND deleted_at IS NULL
        LIMIT 1
    ");
    $stmt->execute(['id' => $rspIdInput]);
    $rsp = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$rsp) {
        error_bad_request('Invalid RSP');
    }

    if ((int)$rsp['product_id'] !== $productId) {
        error_forbidden('Product mismatch');
    }

    /* rsp_admin locked to their own RSP */
    if (!$actor['is_global'] && $actor['company_id'] !== $rspIdInput) {
        error_forbidden('Cannot create outside your RSP');
    }

    $rspId = $rspIdInput;
}

/* =========================
   INSERT
   ========================= */

$stmt = $pdo->prepare("
    INSERT INTO companies (
        company_name,
        rsp_id,
        product_id,
        created_at
    ) VALUES (
        :company_name,
        :rsp_id,
        :product_id,
        NOW()
    )
");

$stmt->execute([
    'company_name' => $companyName,
    'rsp_id'       => $rspId,
    'product_id'   => $productId
]);

$companyId = (int)$pdo->lastInsertId();

/* =========================
   AUDIT
   ========================= */

audit_log(
    $pdo,
    $actor,
    'create',
    'company',
    $companyId,
    [
        'company_name' => $companyName,
        'rsp_id'       => $rspId,
        'product_id'   => $productId
    ]
);

/* =========================
   RESPONSE
   ========================= */

success('Company created', [
    'company_id' => $companyId
]);
