<?php
header('Content-Type: application/json; charset=utf-8');

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

$almacen = $_GET['almacen'] ?? '';

try {
    $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    ]);

    $stmtMulti = $dbh->query("SELECT MULTIALMACEN FROM PARAM_INVENTARIO01");
    $multiRow = $stmtMulti->fetch();
    $usaMulti = isset($multiRow['MULTIALMACEN']) && strtoupper($multiRow['MULTIALMACEN']) === 'T';

    if ($usaMulti && $almacen !== '') {
        $stmt = $dbh->prepare("
            SELECT M.CVE_ART, I.DESCR, I.EXIST, I.UNI_MED, I.LIN_PROD, I.TIPO_ELE
            FROM MULT01 M
            JOIN INVE01 I ON M.CVE_ART = I.CVE_ART
            WHERE I.STATUS = 'A' AND M.CVE_ALM = :almacen
            ORDER BY M.CVE_ART ASC
        ");
        $stmt->bindParam(':almacen', $almacen);
    } elseif ($usaMulti && $almacen === '') {
        $stmt = $dbh->prepare("
            SELECT I.CVE_ART, I.DESCR, SUM(M.EXIST) AS EXIST, I.UNI_MED, I.LIN_PROD, I.TIPO_ELE
            FROM MULT01 M
            JOIN INVE01 I ON M.CVE_ART = I.CVE_ART
            WHERE I.STATUS = 'A'
            GROUP BY I.CVE_ART, I.DESCR, I.UNI_MED, I.LIN_PROD, I.TIPO_ELE
            ORDER BY I.CVE_ART ASC
        ");
    } else {
        $stmt = $dbh->prepare("
            SELECT I.CVE_ART, I.DESCR, I.EXIST, I.UNI_MED, I.LIN_PROD, I.TIPO_ELE
            FROM INVE01 I
            WHERE I.STATUS = 'A'
            ORDER BY I.CVE_ART ASC
        ");
    }

    $stmt->execute();
    $productos = $stmt->fetchAll();

    // Agregar URL imagen
    foreach ($productos as &$p) {
        $p['URL_IMAGEN'] = '/imagenes-productos/' . $p['CVE_ART'] . '.jpg';
    }
    unset($p); // romper referencia

    echo json_encode($productos, JSON_UNESCAPED_UNICODE);
} catch (PDOException $e) {
    echo json_encode(['error' => $e->getMessage()]);
}
