<?php
error_reporting(E_ALL ^ E_NOTICE);

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

include_once '../conexion.php';
include_once '../clases/TokenValidator.php';

// Llama la validación antes de cualquier consulta
$usuarioId = TokenValidator::validar($conn);

try {
    // Leer y decodificar el cuerpo de la solicitud
    $bodyRequest = file_get_contents("php://input");
    $datos = json_decode($bodyRequest, true);

    if (!isset($datos[0], $datos[1], $datos[2])) {
        throw new Exception("Faltan parámetros obligatorios.");
    }

    $empresaId = (int) $datos[0];
    $sucursalId = (int) $datos[1];
    $numero = trim($datos[2]);

    // Consulta SQL preparada
    $sql = "SELECT cara_lado FROM cara_lado WHERE empresa_id = :empresaId AND sucursal_id = :sucursalId AND cara_lado = :numero LIMIT 1";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':empresaId', $empresaId, PDO::PARAM_INT);
    $stmt->bindParam(':sucursalId', $sucursalId, PDO::PARAM_INT);
    $stmt->bindParam(':numero', $numero, PDO::PARAM_STR);
    $stmt->execute();

    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode($rows, JSON_UNESCAPED_UNICODE);
    
    switch (json_last_error()) {
        case JSON_ERROR_NONE:
            break;
        case JSON_ERROR_DEPTH:
            error_response('Maximum stack depth exceeded');
            break;
        case JSON_ERROR_STATE_MISMATCH:
            error_response('Underflow or the modes mismatch');
            break;
        case JSON_ERROR_CTRL_CHAR:
            error_response('Unexpected control character found');
            break;
        case JSON_ERROR_SYNTAX:
            error_response('Syntax error, malformed JSON');
            break;
        case JSON_ERROR_UTF8:
            error_response('Malformed UTF-8 characters, possibly incorrectly encoded');
            break;
        default:
            error_response('Unknown JSON error');
            break;
    }

} catch (Exception $e) {
    error_response("Error: " . $e->getMessage());
} finally {
    $conn = null;
}

function error_response($message) {
    http_response_code(500);
    echo json_encode(['error' => $message], JSON_UNESCAPED_UNICODE);
    exit();
}
?>
