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

requireApiAuth();

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

$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"] ?? ""));
$positionId = (int)($data["position_id"] ?? 0);
$name = trim((string)($data["name"] ?? ""));
$isActive = (int)($data["is_active"] ?? 1) ? 1 : 0;

try {
    if ($action === "delete") {
        if ($positionId <= 0) {
            throw new Exception("invalid_position");
        }
        $del = $pdo->prepare("DELETE FROM positions WHERE id = ?");
        $del->execute([$positionId]);
        echo json_encode(["success" => true]);
        exit;
    }

    if ($action === "toggle") {
        if ($positionId <= 0) {
            throw new Exception("invalid_position");
        }
        $upd = $pdo->prepare("UPDATE positions SET is_active = ?, updated_at = NOW() WHERE id = ?");
        $upd->execute([$isActive, $positionId]);
        echo json_encode(["success" => true]);
        exit;
    }

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

    $ins = $pdo->prepare("INSERT INTO positions (name, is_active) VALUES (?, 1)");
    $ins->execute([$name]);
    echo json_encode(["success" => true, "data" => ["position_id" => (int)$pdo->lastInsertId()]]);
} catch (Throwable $e) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => $e->getMessage()]);
}
