<?php
// api_poligrafia/tipo_documento/read.php

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

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

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

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

// Aseguramos charset
if ($mysqli instanceof mysqli) {
    $mysqli->set_charset('utf8mb4');
}

$sql = "SELECT 
            ID_DOCUMENTO,
            NOMBRE_DOCUMENTO
        FROM TIPO_DOCUMENTOS
        WHERE ESTADO_CODUMENTO = 1
        ORDER BY NOMBRE_DOCUMENTO ASC";

$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
    http_response_code(500);
    echo json_encode([
        "success" => false,
        "message" => "Error al preparar la consulta: " . $mysqli->error
    ], JSON_UNESCAPED_UNICODE);
    exit;
}

$stmt->execute();
$result = $stmt->get_result();

$tipos = [];
if ($result && $result->num_rows > 0) {
    $tipos = $result->fetch_all(MYSQLI_ASSOC);
}

echo json_encode([
    "success" => true,
    "data" => $tipos
], JSON_UNESCAPED_UNICODE);

$stmt->close();
$mysqli->close();
