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

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

$filter = isset($_GET['filter']) ? $_GET['filter'] : '';
$filterColumn = '';

switch ($filter) {
    case 'SAE': $filterColumn = 'CAMPLIB1'; break;
    case 'COI': $filterColumn = 'CAMPLIB2'; break;
    case 'NOI': $filterColumn = 'CAMPLIB3'; break;
    case 'BANCO': $filterColumn = 'CAMPLIB6'; break;
    case 'PROD': $filterColumn = 'CAMPLIB8'; break;
    case 'CAJA': $filterColumn = 'CAMPLIB5'; break;
    case 'FACTURE': $filterColumn = 'CAMPLIB12'; break;
}

$sql = "SELECT c.CLAVE, c.NOMBRE, c.RFC, c.TELEFONO, c.EMAILPRED, 
               cl.CAMPLIB7 AS CONTACTO, cl.CAMPLIB10 AS USUARIO";
if ($filterColumn) {
    $sql .= ", cl.$filterColumn";
}
$sql .= " FROM CLIE01 c INNER JOIN CLIE_CLIB01 cl ON c.CLAVE = cl.CVE_CLIE";

if ($filterColumn) {
    $sql .= " WHERE cl.$filterColumn IS NOT NULL AND TRIM(cl.$filterColumn) != ''";
} else {
    $sql .= " WHERE (cl.CAMPLIB1 IS NOT NULL AND TRIM(cl.CAMPLIB1) != ''
               OR cl.CAMPLIB2 IS NOT NULL AND TRIM(cl.CAMPLIB2) != ''
               OR cl.CAMPLIB3 IS NOT NULL AND TRIM(cl.CAMPLIB3) != ''
               OR cl.CAMPLIB5 IS NOT NULL AND TRIM(cl.CAMPLIB5) != ''
               OR cl.CAMPLIB6 IS NOT NULL AND TRIM(cl.CAMPLIB6) != ''
               OR cl.CAMPLIB8 IS NOT NULL AND TRIM(cl.CAMPLIB8) != ''
               OR cl.CAMPLIB12 IS NOT NULL AND TRIM(cl.CAMPLIB12) != '')";
}

try {
    $dbh = new PDO("firebird:host=$host;dbname=$database;charset=UTF8", $username, $password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $stmt = $dbh->query($sql);

    $data = [];
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $data[] = $row;
    }

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