<?php
$authApp = 'litigantes';
session_start();
require __DIR__ . '/../../config/auth.php';
require __DIR__ . '/../../../../../config/db2.php';
require __DIR__ . '/../../lib/db_helpers.php';

$orden  = in_array($_GET['orden']??'',['nombre','tipo','mail'],true) ? $_GET['orden'] : 'nombre';
$dir    = strtoupper($_GET['dir']??'ASC')==='DESC'?'DESC':'ASC';
$filtros= ['nombre'=>trim($_GET['f_nombre']??''),'tipo'=>$_GET['f_tipo']??''];

$where=['p.deleted_at IS NULL','p.activo=1']; $params=[];
if(!empty($filtros['nombre'])){$where[]="p.nombre LIKE ?"; $params[]='%'.$filtros['nombre'].'%';}
if(!empty($filtros['tipo']))  {$where[]="p.tipo = ?";       $params[]=$filtros['tipo'];}
$wSql="WHERE ".implode(' AND ',$where);

$stmt=$pdo->prepare("SELECT p.*, (SELECT COUNT(*) FROM agj_agendamiento_personas ap JOIN agj_agendamientos ag ON ap.agendamiento_id=ag.id WHERE ap.persona_id=p.id AND ag.estado IN('programado','en_curso') AND ag.deleted_at IS NULL AND ap.deleted_at IS NULL) as juicios_activos FROM agj_personas p $wSql ORDER BY p.$orden $dir");
$stmt->execute($params);
$personas=$stmt->fetchAll();

$paginaActual='personas';
require __DIR__ . '/../../config/menu.php';
?>
  <div class="page-header">
    <div><h1>👤 Personas</h1><div class="breadcrumb"><?= count($personas) ?> registros</div></div>
    <a href="crearPersona.php" class="btn btn-success">➕ Nueva Persona</a>
  </div>

  <form method="GET" id="filtrosForm" class="filtros-box">
    <div class="filtro-item">
      <label>Nombre / Apellido</label>
      <input type="text" name="f_nombre" value="<?= htmlspecialchars($filtros['nombre']) ?>" class="auto-submit" placeholder="Buscar…">
    </div>
    <div class="filtro-item">
      <label>Tipo</label>
      <select name="f_tipo" class="auto-submit">
        <option value="">Todos</option>
        <?php foreach(['juez'=>'Juez','fiscal'=>'Fiscal','defensor'=>'Defensor','querellante'=>'Querellante'] as $v=>$l): ?>
          <option value="<?= $v ?>" <?= $filtros['tipo']===$v?'selected':'' ?>><?= $l ?></option>
        <?php endforeach; ?>
      </select>
    </div>
    <div class="filtro-item" style="align-self:flex-end">
      <button type="submit" class="btn btn-primary">🔍 Buscar</button>
      <a href="listarPersonas.php" class="btn btn-secondary">Limpiar</a>
    </div>
    <input type="hidden" name="orden" value="<?= htmlspecialchars($orden) ?>">
    <input type="hidden" name="dir"   value="<?= htmlspecialchars($dir) ?>">
  </form>

  <?php if(isset($_GET['msg'])): ?><div class="mensaje mensaje-exito"><?= htmlspecialchars($_GET['msg']) ?></div><?php endif; ?>

  <div style="background:#fff;border:1px solid #e2e8f0;border-radius:8px;overflow:auto">
  <table>
    <thead>
      <tr>
        <th style="width:35%"><?= ordenLink('nombre','Nombre',$orden,$dir) ?></th>
        <th style="width:12%"><?= ordenLink('tipo','Tipo',$orden,$dir) ?></th>
        <th style="width:28%"><?= ordenLink('mail','Email',$orden,$dir) ?></th>
        <th style="width:12%">Juicios activos</th>
        <th style="width:13%">Acciones</th>
      </tr>
    </thead>
    <tbody>
      <?php foreach($personas as $p):
        $cols=['juez'=>'#1e40af','fiscal'=>'#065f46','defensor'=>'#78350f','querellante'=>'#6b21a8'];
        $c=$cols[$p['tipo']]??'#334155';
      ?>
        <tr>
          <td><strong><?= htmlspecialchars($p['nombre']) ?></strong></td>
          <td><span style="background:<?= $c ?>20;color:<?= $c ?>;padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700"><?= ucfirst($p['tipo']) ?></span></td>
          <td><?= htmlspecialchars($p['mail']??'—') ?></td>
          <td style="text-align:center">
            <?php if($p['juicios_activos']>0): ?>
              <span style="background:#fef3c7;color:#d97706;padding:2px 8px;border-radius:10px;font-size:12px;font-weight:700"><?= $p['juicios_activos'] ?></span>
            <?php else: ?>
              <span style="color:#94a3b8">0</span>
            <?php endif; ?>
          </td>
          <td class="acciones">
            <a href="editarPersona.php?id=<?= $p['id'] ?>" class="btn btn-warning btn-sm">✏️ Editar</a>
            <a href="licencias.php?persona_id=<?= $p['id'] ?>" class="btn btn-info btn-sm">📋 Licencias</a>
          </td>
        </tr>
      <?php endforeach; ?>
      <?php if(empty($personas)): ?>
        <tr><td colspan="5" style="text-align:center;color:#64748b;padding:20px">No se encontraron personas</td></tr>
      <?php endif; ?>
    </tbody>
  </table>
  </div>

</div>
</body>
</html>
<script>
document.querySelectorAll('.auto-submit').forEach(el=>{
  el.addEventListener('change',()=>document.getElementById('filtrosForm').submit());
  if(el.tagName==='INPUT')el.addEventListener('blur',function(){if(this.value!==this.defaultValue)document.getElementById('filtrosForm').submit();this.defaultValue=this.value;});
});
</script>
