<?php
$host = 'localhost';
$database = 'C:\Program Files (x86)\Common Files\Aspel\Sistemas Aspel\SAE9.00\Empresa01\Datos\SAE90EMPRE01.FDB';
$username = 'SYSDBA';
$password = 'masterkey';

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

    try {
        $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password);

        $sqlDetalles = "
            SELECT 
                p.NUM_PAR, 
                p.CANT,
                p.NUM_ALM,
                p.CVE_ART, 
                p.COST, 
                p.TOT_PARTIDA, 
                o.STR_OBS 
            FROM PAR_COMPO01 p
            LEFT JOIN OBS_DOCC01 o ON p.CVE_OBS = o.CVE_OBS
            WHERE p.CVE_DOC = ?
        ";
        $stmtDetalles = $dbh->prepare($sqlDetalles);
        $stmtDetalles->execute([$cve_doc]);

        $detalles = "<table class='table table-hover'>";
        $detalles .= "<thead class='thead-dark'><tr><th>Partida</th><th>Cantidad</th><th>Almacen</th><th>Producto</th><th>Costo X Unidad</th><th>Subtotal</th><th>Observaciones</th></tr></thead><tbody>";

        while ($row = $stmtDetalles->fetch(PDO::FETCH_ASSOC)) {
            $detalles .= "<tr>";
            $detalles .= "<td>" . htmlspecialchars($row['NUM_PAR'], ENT_QUOTES, 'UTF-8') . "</td>";
            $detalles .= "<td>" . htmlspecialchars($row['CANT'], ENT_QUOTES, 'UTF-8') . "</td>";
            $detalles .= "<td>" . htmlspecialchars($row['NUM_ALM'], ENT_QUOTES, 'UTF-8') . "</td>";
            $detalles .= "<td>" . htmlspecialchars($row['CVE_ART'], ENT_QUOTES, 'UTF-8') . "</td>";
            $detalles .= "<td>" . number_format($row['COST'], 2, '.', ',') . "</td>";
            $detalles .= "<td>" . number_format($row['TOT_PARTIDA'], 2, '.', ',') . "</td>";
            $detalles .= "<td>" . htmlspecialchars($row['STR_OBS'], ENT_QUOTES, 'UTF-8') . "</td>";
            $detalles .= "</tr>";
        }

        $detalles .= "</tbody></table>";

        echo json_encode(['detalles' => $detalles]);
    } catch (PDOException $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
}
?>
