<?php
error_reporting(E_ALL ^ E_NOTICE);

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE");

include_once '../conexion.php';
include_once '../clases/TokenValidator.php';

// Llama la validación antes de cualquier consulta
$usuarioId = TokenValidator::validar($conn);

$bodyRequest = file_get_contents("php://input");
$datos = json_decode($bodyRequest, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    print_json(['error' => 'Invalid JSON']);
    exit();
}

if (!isset($datos[0], $datos[1], $datos[2], $datos[3], $datos[4])) {
    http_response_code(400);
    print_json(['error' => 'Parámetros incompletos']);
    exit();
}

// Asignar con nombres reales
$ccodigo_sunat = (int) $datos[0];
$crpta_sunat   = trim($datos[1]);
$chash_sunat   = trim($datos[2]);
$chash_cpe     = trim($datos[3]);
$iidgrt        = (int) $datos[4];

try {
    $sql = "SELECT actualiza_guiart_enviosunat(:ccodigo_sunat, :crpta_sunat, :chash_sunat, :chash_cpe, :_iidgrt) AS id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':ccodigo_sunat', $ccodigo_sunat, PDO::PARAM_INT);
    $stmt->bindParam(':crpta_sunat', $crpta_sunat, PDO::PARAM_STR);
    $stmt->bindParam(':chash_sunat', $chash_sunat, PDO::PARAM_STR);
    $stmt->bindParam(':chash_cpe', $chash_cpe, PDO::PARAM_STR);
    $stmt->bindParam(':_iidgrt', $iidgrt, PDO::PARAM_INT);
    $stmt->execute();

    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result && isset($result['id'])) {
        print_json([
            'estado' => 'success',
            'idventa' => (int)$result['id'],
            'mensaje' => 'Guía actualizada correctamente'
        ]);
    } else {
        print_json([
            'estado' => 'error',
            'mensaje' => 'No se pudo actualizar la guía',
            'idventa' => 0
        ]);
    }

} catch (PDOException $e) {
    http_response_code(500);
    print_json([
        'estado' => 'error',
        'mensaje' => 'Error en la ejecución',
        'detalles' => $e->getMessage()
    ]);
    error_log("❌ Error en la ejecución: " . $e->getMessage());
}

function print_json($data) {
    header("Content-Type: application/json; charset=utf-8");
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
}