<?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';

try {

    $bodyRequest = file_get_contents("php://input");
    $datos = json_decode($bodyRequest, true);

    if (!isset($datos[0], $datos[1])) {
        throw new Exception("Par¨¢metros insuficientes.");
    }

    $cfecha  = $datos[0];
    $ccuenta = (int) $datos[1];

    /*
     * Busca espec¨ªficamente aperturas ANTERIORES
     * que todav¨ªa NO hayan sido cerradas.
     */
    $sql = "
        SELECT
            fecha,
            monto_cierre,
            cerrado
        FROM apertura_cierre_caja
        WHERE fecha < :fecha
          AND cuenta_id = :cuenta_id
          AND COALESCE(cerrado, false) = false
        ORDER BY fecha DESC
        LIMIT 1
    ";

    $stmt = $conn->prepare($sql);

    $stmt->bindParam(':fecha', $cfecha, PDO::PARAM_STR);
    $stmt->bindParam(':cuenta_id', $ccuenta, PDO::PARAM_INT);

    $stmt->execute();

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

    print_json($rows);

} catch (Exception $e) {

    error_response("Error: " . $e->getMessage());

} finally {

    $conn = null;
}


function print_json($data)
{
    echo json_encode($data, 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 error');
            break;
    }
}


function error_response($message)
{
    http_response_code(500);

    echo json_encode(
        ['error' => $message],
        JSON_UNESCAPED_UNICODE
    );

    exit();
}

?>