<?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');

/* =========================
   AUTH
   ========================= */

$user = require_auth($pdo);

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

if (!in_array($role, [
    'super_admin',
    'platform_admin',
], true)) {
    error_forbidden('Insufficient privileges');
}

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

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

if (!is_array($input)) {
    error_bad_request('Invalid JSON');
}

$name = trim((string)($input['name'] ?? ''));

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

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

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

if ($user['role_key'] === 'super_admin' || $user['role_key'] === 'platform_admin') {

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

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

}

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

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

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

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

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