<?php
  if(!file_exists("clientes.txt")){
    echo "<p>No hay registros de clientes</p>";
    exit;
  }

  $filtro = $_GET["filtro"] ?? "todos";
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Listar Clientes</title>
    <style>
        body { font-family: Arial; padding: 15px; background: #f5f5f5; }
        h3 { color: #1a5276; }
        table { border-collapse: collapse; margin-top: 15px; width: 100%; }
        td, th { border: 1px solid #ccc; padding: 8px; text-align: left; }
        th { background: #1a5276; color: white; }
        .activo { color: green; font-weight: bold; }
        .baja { color: red; font-weight: bold; }
        a.filtro {
            display: inline-block; margin: 5px 3px; padding: 8px 15px;
            background: #2e86c1; color: white; text-decoration: none; border-radius: 4px;
        }
        a.filtro:hover { background: #1a5276; }
        a.filtro.activo-f { background: #1a5276; }
    </style>
</head>
<body>
    <h3>LISTADO DE CLIENTES</h3>
    <a href="listarClientes.php?filtro=activos" class="filtro <?php echo $filtro=='activos'?'activo-f':''; ?>">ACTIVOS</a>
    <a href="listarClientes.php?filtro=baja" class="filtro <?php echo $filtro=='baja'?'activo-f':''; ?>">DADOS DE BAJA</a>
    <a href="listarClientes.php?filtro=todos" class="filtro <?php echo $filtro=='todos'?'activo-f':''; ?>">TODOS</a>
    <br><br>
    <?php
      $recurso = fopen("clientes.txt","r");
      echo "<table>";
      echo "<tr><th>Cuenta</th><th>CI</th><th>Nombre</th><th>Celular</th><th>Direccion</th><th>Estado</th><th>Fecha</th></tr>";
      $total = 0;
      while(!feof($recurso)){
        $linea = fgets($recurso);
        if(trim($linea) != ""){
          $reg = explode("|",$linea);
          if(count($reg) >= 7){
            $estado = trim($reg[5]);
            $mostrar = false;
            if($filtro == "todos") $mostrar = true;
            elseif($filtro == "activos" && $estado == "ACTIVO") $mostrar = true;
            elseif($filtro == "baja" && $estado == "BAJA") $mostrar = true;

            if($mostrar){
              $clase = ($estado == "BAJA") ? "baja" : "activo";
              echo "<tr>";
              echo "<td>".htmlspecialchars($reg[0])."</td>";
              echo "<td>".htmlspecialchars($reg[1])."</td>";
              echo "<td>".htmlspecialchars($reg[2])."</td>";
              echo "<td>".htmlspecialchars($reg[3])."</td>";
              echo "<td>".htmlspecialchars($reg[4])."</td>";
              echo "<td class='$clase'>".htmlspecialchars($reg[5])."</td>";
              echo "<td>".htmlspecialchars($reg[6])."</td>";
              echo "</tr>";
              $total++;
            }
          }
        }
      }
      echo "</table>";
      fclose($recurso);
      echo "<p><strong>Total: $total clientes</strong></p>";
    ?>
</body>
</html>
