<?php

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Content-Type: application/json; charset=utf-8");

// 🔥 PREFLIGHT
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

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

require_once(__DIR__ . '/../config.php');
require_once(__DIR__ . '/../auth_guard.php');

// ===================== HELPERS =====================
function cleanText($v) {
    $v = trim((string)$v);
    return $v === "" ? null : $v;
}

function jsonInput(): array {
    $raw = file_get_contents("php://input");
    $data = json_decode($raw, true);
    return is_array($data) ? $data : [];
}

function respond($arr, int $code = 200) {
    http_response_code($code);
    echo json_encode($arr, JSON_UNESCAPED_UNICODE);
    exit;
}

// ===================== AUTH =====================
$authUser = requireAuth($JWT_KEY);
$activeUser = requireActiveUser($mysqli, $authUser);

// ===================== ROUTER =====================
$method = $_SERVER['REQUEST_METHOD'];

try {

    // ---------- GET ----------
    if ($method === 'GET') {
        $id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;

        if ($id > 0) {
            $sql = "SELECT *
                    FROM MATRIZ_GENERAL_DEFINICIONES
                    WHERE ID_DEFINICIONES_ITEMS = ?
                    LIMIT 1";
            $stmt = $mysqli->prepare($sql);
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $row = $stmt->get_result()->fetch_assoc();

            if (!$row) {
                respond(["success" => false, "message" => "Registro no encontrado"], 404);
            }

            respond(["success" => true, "data" => $row]);
        }

        $sql = "SELECT *
                FROM MATRIZ_GENERAL_DEFINICIONES
                ORDER BY ID_DEFINICIONES_ITEMS DESC";
        $res = $mysqli->query($sql);

        $rows = [];
        while ($r = $res->fetch_assoc()) {
            $rows[] = $r;
        }

        respond([
            "success" => true,
            "total" => count($rows),
            "data" => $rows
        ]);
    }

    // ---------- POST ----------
    if ($method === 'POST') {
        $b = jsonInput();

        $P1 = cleanText($b["DEFINICION_PREGUNTA_1"] ?? null);
        $P2 = cleanText($b["DEFINICION_PREGUNTA_2"] ?? null);
        $P3 = cleanText($b["DEFINICION_PREGUNTA_3"] ?? null);
        $P4 = cleanText($b["DEFINICION_PREGUNTA_4"] ?? null);

        $sql = "INSERT INTO MATRIZ_GENERAL_DEFINICIONES
                (DEFINICION_PREGUNTA_1, DEFINICION_PREGUNTA_2,
                 DEFINICION_PREGUNTA_3, DEFINICION_PREGUNTA_4)
                VALUES (?,?,?,?)";

        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("ssss", $P1, $P2, $P3, $P4);
        $stmt->execute();

        respond([
            "success" => true,
            "id" => $mysqli->insert_id,
            "message" => "Definiciones creadas correctamente"
        ]);
    }

    // ---------- PUT ----------
    if ($method === 'PUT') {
        $b = jsonInput();

        $ID = (int)($b["ID_DEFINICIONES_ITEMS"] ?? 0);
        if ($ID <= 0) {
            respond(["success" => false, "message" => "ID_DEFINICIONES_ITEMS requerido"], 400);
        }

        $P1 = cleanText($b["DEFINICION_PREGUNTA_1"] ?? null);
        $P2 = cleanText($b["DEFINICION_PREGUNTA_2"] ?? null);
        $P3 = cleanText($b["DEFINICION_PREGUNTA_3"] ?? null);
        $P4 = cleanText($b["DEFINICION_PREGUNTA_4"] ?? null);

        $sql = "UPDATE MATRIZ_GENERAL_DEFINICIONES SET
                  DEFINICION_PREGUNTA_1 = ?,
                  DEFINICION_PREGUNTA_2 = ?,
                  DEFINICION_PREGUNTA_3 = ?,
                  DEFINICION_PREGUNTA_4 = ?
                WHERE ID_DEFINICIONES_ITEMS = ?";

        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("ssssi", $P1, $P2, $P3, $P4, $ID);
        $stmt->execute();

        respond([
            "success" => true,
            "message" => "Definiciones actualizadas correctamente"
        ]);
    }

    // ---------- DELETE ----------
    if ($method === 'DELETE') {
        $id = isset($_GET["id"]) ? (int)$_GET["id"] : 0;
        if ($id <= 0) {
            respond(["success" => false, "message" => "id requerido"], 400);
        }

        $sql = "DELETE FROM MATRIZ_GENERAL_DEFINICIONES
                WHERE ID_DEFINICIONES_ITEMS = ?";
        $stmt = $mysqli->prepare($sql);
        $stmt->bind_param("i", $id);
        $stmt->execute();

        respond([
            "success" => true,
            "message" => "Registro eliminado"
        ]);
    }

    respond(["success" => false, "message" => "Método no permitido"], 405);

} catch (Throwable $e) {
    respond([
        "success" => false,
        "message" => "Error interno",
        "error" => $e->getMessage()
    ], 500);
}
