<?php
header('Content-Type: text/html; charset=UTF-8');

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

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

    $statusDescriptions = array(
        'A' => 'Activo',
        'B' => 'Baja',
        'S' => 'Suspendido'
    );

    // ✅ Mapeamos el filtro recibido por GET
    $statusMap = array(
        'activo' => 'A',
        'baja' => 'B',
        'suspendido' => 'S'
    );
    $statusFilter = isset($_GET['filter']) ? $_GET['filter'] : '';
    $filterCode = isset($statusMap[$statusFilter]) ? $statusMap[$statusFilter] : '';

    $sql = "SELECT * FROM PROV01";
    $conditions = [];

    // Condición fija
    $conditions[] = "CAST(SALDO AS FLOAT) > 0.01";

    // Condición opcional según botón
    if (!empty($filterCode)) {
        $conditions[] = "STATUS = :status";
    }

    if (!empty($conditions)) {
        $sql .= " WHERE " . implode(" AND ", $conditions);
    }

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

    if (!empty($filterCode)) {
        $stmt->bindParam(':status', $filterCode, PDO::PARAM_STR);
    }

    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        echo "<tr>";
        echo "<td>" . htmlspecialchars($row['CLAVE']) . "</td>";
        echo "<td>" . $statusDescriptions[$row['STATUS']] . "</td>";
        echo "<td>" . htmlspecialchars($row['NOMBRE']) . "</td>";
        echo "<td>" . htmlspecialchars($row['CALLE']) . "</td>";
        echo "<td>" . htmlspecialchars($row['TELEFONO']) . "</td>";
        echo "<td>" . htmlspecialchars($row['CLASIFIC']) . "</td>";
        $saldo = number_format($row['SALDO'], 2, '.', ',');
        echo "<td>" . $saldo . "</td>";
        echo "</tr>";
    }

} catch (PDOException $e) {
    echo "<tr><td colspan='7'>Error de conexión: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
}
?>
