<?php
require_once "../config/database.php";
require_once "../includes/auth.php";
require_once "../includes/csrf.php";
require_once "../includes/rbac.php";

header("Content-Type: application/json; charset=utf-8");

if ($_SERVER["REQUEST_METHOD"] === "GET") {
    requireApiAuth();
    $stmt = $pdo->query("SELECT id, name FROM skills ORDER BY name");
    echo json_encode(["success" => true, "data" => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
    exit;
}

requireApiAuth();

$roleId = (int)($_SESSION["user"]["role_id"] ?? 0);
if (!hasPermission("manage_users") && $roleId !== 5) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "forbidden"]);
    exit;
}

if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    http_response_code(405);
    echo json_encode(["success" => false, "error" => "method_not_allowed"]);
    exit;
}

$data = json_decode(file_get_contents("php://input"), true) ?: [];
if (!requireCsrfFromPayload($data, "csrf")) {
    http_response_code(419);
    echo json_encode(["success" => false, "error" => "csrf_failed"]);
    exit;
}

$action = trim((string)($data["action"] ?? ""));
$name = trim((string)($data["name"] ?? ""));
$nameEn = trim((string)($data["name_en"] ?? ""));
$nameSr = trim((string)($data["name_sr"] ?? ""));
$skillId = (int)($data["skill_id"] ?? 0);

$pdo->beginTransaction();
try {
    if ($action === 'delete') {
        if ($skillId <= 0) {
            throw new Exception("invalid_skill");
        }
        $del = $pdo->prepare("DELETE FROM skills WHERE id = ?");
        $del->execute([$skillId]);
        $pdo->commit();
        echo json_encode(["success" => true]);
        exit;
    }

    // add
    $finalName = $name;
    if ($nameEn !== "" || $nameSr !== "") {
        if (strlen($nameEn) < 2 || strlen($nameSr) < 2) {
            throw new Exception("invalid_name");
        }
        $finalName = $nameEn . " / " . $nameSr;
    }

    if (strlen($finalName) < 2 || strlen($finalName) > 100) {
        throw new Exception("invalid_name");
    }

    $ins = $pdo->prepare("INSERT INTO skills (name) VALUES (?)");
    $ins->execute([$finalName]);
    $pdo->commit();
    echo json_encode(["success" => true, "data" => ["skill_id" => $pdo->lastInsertId()]]);
} catch (Throwable $e) {
    $pdo->rollBack();
    http_response_code(422);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
?>

