<?php
declare(strict_types=1);

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

require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../system/auth.php';

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

$user = require_auth($pdo);

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

$id   = $data['id'] ?? null;
$name = trim($data['name'] ?? '');

if(!$name){
echo json_encode([
"status"=>"error",
"message"=>"Department name required"
]);
exit;
}

try{

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

if($id){

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

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

}

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

else{

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

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

$id = $pdo->lastInsertId();

}

echo json_encode([
"status"=>"success",
"id"=>$id
]);

}catch(Throwable $e){

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

echo json_encode([
"status"=>"error",
"message"=>"Server error saving department"
]);

}