<?php
declare(strict_types=1);

ini_set('display_errors',1);
error_reporting(E_ALL);

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

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

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

$id           = (int)($input['id'] ?? 0);
$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');
}

try{

/* ================= UPDATE ================= */

if($id > 0){

$stmt = $pdo->prepare("
UPDATE sections
SET
name = :name,
department_id = :department_id
WHERE id = :id
");

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

success('Section updated');

}

/* ================= CREATE ================= */

else{

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

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

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

}

}catch(Throwable $e){

error_log("SECTION SAVE ERROR: ".$e->getMessage());

error_server('Failed to save section');

}