<?php

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

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

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

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

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

if (!$input || empty($input['company_id'])) {
    json_response(false, 'Company ID required.', [], 400);
}

$company_id = (int)$input['company_id'];

/* FETCH COMPANY */
$stmt = $pdo->prepare("
    SELECT id, status, rsp_id
    FROM companies
    WHERE id = ?
    LIMIT 1
");
$stmt->execute([$company_id]);
$company = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$company) {
    json_response(false, 'Company not found.', [], 404);
}

/* TENANT ISOLATION */
if (!empty($user['rsp_id'])) {
    enforce_rsp_isolation($user, (int)$company['rsp_id']);
}

/* TOGGLE STATUS */
$new_status = ($company['status'] === 'active') ? 'inactive' : 'active';

$stmt = $pdo->prepare("
    UPDATE companies
    SET status = ?
    WHERE id = ?
");
$stmt->execute([$new_status, $company_id]);

/* AUDIT */
log_admin_action(
    $pdo,
    (int)$user['id'],
    'companies',
    'status_toggle',
    $company_id
);

/* RESPONSE */
json_response(true, 'Company status updated.', [
    'company_id' => $company_id,
    'new_status' => $new_status
]);