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

setlocale(LC_MONETARY, 'es_MX');

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

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

  $statusFilter = $_GET['filter'] ?? '';

  $statusMap = array(
    'activo' => 'A',
    'baja' => 'B',
    'moroso' => 'M',
    'suspendido' => 'S'
  );
  $filterCode = $statusMap[$statusFilter] ?? '';

  $sql = "SELECT * FROM CLIE01";
  if (!empty($filterCode)) {
    $sql .= " WHERE STATUS = :status";
  }

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

  // ⬇️ Solo devolvemos el <tbody> para AJAX
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "<tr>";
    echo "<td class='num'>" . htmlspecialchars($row['CLAVE'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($statusDescriptions[$row['STATUS']], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['NOMBRE'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['RFC'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['CALLE'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . htmlspecialchars($row['TELEFONO'], ENT_QUOTES, 'UTF-8') . "</td>";
    echo "<td>" . number_format($row['SALDO'], 2, '.', ',') . "</td>";
echo "<td>
  <button class='btn btn-primary detallesClienteBtn'
          data-toggle='modal'
          data-target='#clienteModal'
          data-id='" . $row['CLAVE'] . "'
          data-nombre='" . htmlspecialchars($row['NOMBRE'], ENT_QUOTES, 'UTF-8') . "'
          data-saldo='" . number_format($row['SALDO'], 2, '.', ',') . "'>
    Ver
  </button>
</td>";    echo "</tr>";
  }
} catch (PDOException $e) {
  echo "<tr><td colspan='8'>Error de conexión: " . htmlspecialchars($e->getMessage()) . "</td></tr>";
}
