<?php

require_once __DIR__ . '/../../core/api_bootstrap.php';
require_once __DIR__ . '/../../core/permissions.php';

/* METHOD CHECK */
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(false, 'Invalid request method.', [], 405);
}

/* AUTH */
$user = authenticate($pdo);

/* RBAC */
require_permission($user, 'companies', 'create', $pdo);

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

if (
    !$input ||
    empty($input['company_name']) ||
    empty($input['rsp_id']) ||
    empty($input['type'])
) {
    json_response(false, 'Missing required fields.', [], 400);
}

$company_name = trim($input['company_name']);
$rsp_id       = (int)$input['rsp_id'];
$type         = $input['type'];

if (!in_array($type, ['fleet', 'sp'], true)) {
    json_response(false, 'Invalid company type.', [], 400);
}

/* TENANT ISOLATION */
enforce_rsp_isolation($user, $rsp_id);

/* INSERT */
$stmt = $pdo->prepare("
    INSERT INTO companies 
    (company_name, rsp_id, type, status, created_at)
    VALUES (?, ?, ?, 'active', NOW())
");

$stmt->execute([$company_name, $rsp_id, $type]);

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

/* AUDIT LOG */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'companies',
    'create',
    $newId
);

/* RESPONSE */
json_response(true, 'Company created successfully.', [
    'company_id' => $newId
]);