<?php
declare(strict_types=1);

require_once __DIR__.'/../system/bootstrap.php';
require_once __DIR__.'/../system/auth.php';
require_once __DIR__.'/../system/response.php';

header('Content-Type: application/json');

$user = require_auth($pdo);

$role = strtolower((string)$user['role_key']);

if (!in_array($role, [
    'super_admin',
    'platform_admin',
    'rsp_admin',
    'rsp_owner',
    'company_admin'
], true)) {
    error_forbidden('Forbidden');
}

/* =========================
   INPUT
   ========================= */

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

$name = trim((string)($input['name'] ?? ''));
$departmentId = (int)($input['department_id'] ?? 0);

if ($name === '') {
    error_bad_request('Section name required');
}

if ($departmentId <= 0) {
    error_bad_request('department_id required');
}

/* =========================
   COMPANY SCOPE
   ========================= */

$companyId = (int)$user['company_id'];

if ($role === 'super_admin' || $role === 'platform_admin') {

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

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

}

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

$stmt = $pdo->prepare("
INSERT INTO sections
(company_id,department_id,name,created_at)
VALUES
(:company_id,:department_id,:name,NOW())
");

$stmt->execute([
'company_id'=>$companyId,
'department_id'=>$departmentId,
'name'=>$name
]);

success('Section created',[
'id'=>$pdo->lastInsertId()
]);