<?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, 'service_providers', 'edit', $pdo);

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

if (!$input || empty($input['company_id']) || !isset($input['divisions']) || !is_array($input['divisions'])) {
    json_response(false, 'Invalid input.', [], 400);
}

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

/* Division limit */
if (count($divisions) > 50) {
    json_response(false, 'Too many divisions (max 50).', [], 400);
}

$pdo->beginTransaction();

try {

    /*
    |----------------------------------------------------------
    | Fetch Company + Isolation
    |----------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        SELECT id, rsp_id, type
        FROM companies
        WHERE id = ?
        FOR UPDATE
    ");

    $stmt->execute([$company_id]);
    $company = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$company) {
        throw new Exception('Company not found.');
    }

    /* Must be SP */
    if ($company['type'] !== 'sp') {
        throw new Exception('Divisions can only be set for service providers.');
    }

    /* Tenant Isolation */
    if (!empty($user['rsp_id']) && (int)$company['rsp_id'] !== (int)$user['rsp_id']) {
        throw new Exception('RSP isolation violation.');
    }

    /*
    |----------------------------------------------------------
    | Clear Existing
    |----------------------------------------------------------
    */

    $pdo->prepare("
        DELETE FROM service_company_divisions
        WHERE company_id = ?
    ")->execute([$company_id]);

    /*
    |----------------------------------------------------------
    | Insert New
    |----------------------------------------------------------
    */

    $stmt = $pdo->prepare("
        INSERT INTO service_company_divisions (company_id, division)
        VALUES (?, ?)
    ");

    foreach ($divisions as $division) {

        $division = trim($division);

        if ($division === '') {
            continue;
        }

        /* Length limit */
        if (strlen($division) > 100) {
            throw new Exception('Division name too long.');
        }

        $stmt->execute([$company_id, $division]);
    }

    $pdo->commit();

} catch (Throwable $e) {

    $pdo->rollBack();
    json_response(false, $e->getMessage(), [], 400);
}

json_response(true, 'Divisions updated securely.');