<?php
header('Content-Type: application/json');

$host = 'localhost';
$database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\SAE7.00\Empresa01\Datos\SAE70EMPRE01.FDB';
$username = 'SYSDBA';
$password = 'masterkey';

if (isset($_POST['id'])) {
    $clienteId = $_POST['id'];

    try {
        $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password);
        
        $sqlFacturas = "SELECT PAGA_DET01.CVE_PROV, CONP01.DESCR, PAGA_DET01.REFER, PAGA_DET01.NUM_CARGO, 
                               PAGA_DET01.FECHA_APLI, PAGA_DET01.FECHA_VENC, PAGA_DET01.IMPORTE, COMPC01.SU_REFER
                        FROM PAGA_DET01
                        INNER JOIN CONP01 ON PAGA_DET01.NUM_CPTO = CONP01.NUM_CPTO
                        INNER JOIN COMPC01 ON PAGA_DET01.REFER = COMPC01.CVE_DOC
                        WHERE CVE_PROV = ?";
        
        $stmtFacturas = $dbh->prepare($sqlFacturas);
        $stmtFacturas->execute([$clienteId]);
        
        $facturas = "<table class='table table-hover'>";
        $facturas .= "<thead class='thead-dark'><tr><th>Referencia</th><th>Fecha Vencimiento</th><th>1-30</th><th>31-60</th><th>61-90</th><th>Más de 90</th></tr></thead><tbody>";
        
        while ($row = $stmtFacturas->fetch(PDO::FETCH_ASSOC)) {
            $facturas .= "<tr data-id='" . htmlspecialchars($row['CVE_PROV'], ENT_QUOTES, 'UTF-8') . "'>";
            $facturas .= "<td>" . htmlspecialchars($row['DESCR'], ENT_QUOTES, 'UTF-8') . "</td>";
            $facturas .= "<td>" . htmlspecialchars($row['REFER'], ENT_QUOTES, 'UTF-8') . "</td>";
            $facturas .= "<td>" . htmlspecialchars($row['DOCTO'], ENT_QUOTES, 'UTF-8') . "</td>";
            $facturas .= "<td>" . date('d/m/Y', strtotime($row['FECHA_APLI'])) . "</td>";
            $facturas .= "<td>" . date('d/m/Y', strtotime($row['FECHA_VENC'])) . "</td>";
            $facturas .= "<td>" . number_format($row['IMPORTE'], 2, '.', ',') . "</td>";
            $facturas .= "</tr>";
        }
        $facturas .= "</tbody></table>";

        echo json_encode(['detalles' => $facturas]); // Cambia 'facturas' por 'detalles'
    } catch (PDOException $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
} else {
    echo json_encode(['error' => 'ID del cliente no especificado.']);
}
?>
