<?php
session_start();
require __DIR__ . '/../../config/auth.php';
require __DIR__ . '/../../config/db2.php';
require __DIR__ . '/../../lib/helpers.php';

// ── Acciones ──────────────────────────────────────────────────────────────────
if (isset($_GET['eliminar'])) {
    $pdo->prepare("UPDATE juez_rol SET deleted_at=NOW() WHERE id=?")->execute([(int)$_GET['eliminar']]);
    header('Location: listarJuezRol.php');
    exit;
}

// ── Filtros ───────────────────────────────────────────────────────────────────
$fJuez  = trim($_GET['f_juez']  ?? '');
$fRol   = trim($_GET['f_rol']   ?? '');
$fVig   = $_GET['f_vig'] ?? '';

$roles = $pdo->query("SELECT id, nombre FROM roles_juez WHERE deleted_at IS NULL AND activo=1 ORDER BY nombre")->fetchAll(PDO::FETCH_KEY_PAIR);

$where  = ["jr.deleted_at IS NULL"];
$params = [];
if ($fJuez !== '') { $where[] = "j.nombre LIKE ?"; $params[] = "%$fJuez%"; }
if ($fRol  !== '') { $where[] = "jr.rolJuez_id = ?"; $params[] = (int)$fRol; }
if ($fVig === '1') {
    $where[] = "(jr.fecha_hasta IS NULL OR jr.fecha_hasta >= CURDATE()) AND jr.fecha_desde <= CURDATE()";
}

$sql = "
    SELECT jr.id, jr.juez_id, j.nombre AS juez_nombre, rj.nombre AS rol_nombre,
           jr.fecha_desde, jr.fecha_hasta, jr.observaciones
    FROM juez_rol jr
    JOIN mrbs_juez j ON j.juez_id = jr.juez_id
    JOIN roles_juez rj ON rj.id = jr.rolJuez_id
    WHERE " . implode(' AND ', $where) . "
    ORDER BY jr.fecha_desde DESC, j.nombre
";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

$paginaActual = 'litigantes';
require __DIR__ . '/../../config/menu.php';

?>
<div class="ph">
  <div>
    <h1>Autoridades de Jueces</h1>
    <div class="bc"><a href="listarJuezRol.php">Litigantes</a> › Autoridades</div>
  </div>
  <a href="crearJuezRol.php" class="btn btn-p">+ Nueva Autoridad</a>
</div>

<?php if (isset($_GET['ok'])): ?>
<div class="msg msg-ok">Guardado correctamente.</div>
<?php endif; ?>

<form id="fForm" method="get" class="fb">
  <div class="fi"><label>Juez</label>
    <input type="text" name="f_juez" value="<?=htmlspecialchars($fJuez)?>">
  </div>
  <div class="fi"><label>Rol</label>
    <select name="f_rol">
      <option value="">Todos</option>
      <?php foreach ($roles as $rid => $rnom): ?>
      <option value="<?=$rid?>" <?=$fRol==(string)$rid?'selected':''?>><?=htmlspecialchars($rnom)?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="fi"><label>Vigencia</label>
    <select name="f_vig">
      <option value="">Todos</option>
      <option value="1" <?=$fVig==='1'?'selected':''?>>Solo vigentes</option>
    </select>
  </div>
  <div class="fi" style="align-self:flex-end">
    <button type="submit" class="btn btn-p">Buscar</button>
    <a href="listarJuezRol.php" class="btn btn-g">Limpiar</a>
  </div>
</form>

<p style="font-size:12px;color:#64748b;margin-bottom:8px"><?=count($rows)?> resultado(s)</p>

<div class="tw"><table>
  <thead><tr>
    <th>Juez</th>
    <th>Rol</th>
    <th>Desde</th>
    <th>Hasta</th>
    <th>Observaciones</th>
    <th style="width:100px">Acciones</th>
  </tr></thead>
  <tbody>
    <?php foreach ($rows as $r): ?>
    <?php
      $hoy = date('Y-m-d');
      $vig = $r['fecha_desde'] <= $hoy && ($r['fecha_hasta'] === null || $r['fecha_hasta'] >= $hoy);
    ?>
    <tr>
      <td><?=htmlspecialchars($r['juez_nombre'])?></td>
      <td><?=htmlspecialchars($r['rol_nombre'])?></td>
      <td><?=fmtFecha($r['fecha_desde'])?></td>
      <td><?=$r['fecha_hasta'] ? fmtFecha($r['fecha_hasta']) : '<em style="color:#64748b">sin venc.</em>'?></td>
      <td class="w"><?=htmlspecialchars($r['observaciones'] ?? '')?></td>
      <td class="ac">
        <a href="crearJuezRol.php?id=<?=$r['id']?>" class="btn btn-i btn-sm">Editar</a>
        <a href="?eliminar=<?=$r['id']?>" class="btn btn-r btn-sm"
           onclick="return confirm('¿Eliminar autoridad?')">Eliminar</a>
      </td>
    </tr>
    <?php endforeach; ?>
  </tbody>
</table></div>

<script>
(function(){
  const f = document.getElementById('fForm');
  f.querySelectorAll('select').forEach(el => el.addEventListener('change', () => f.submit()));
  f.querySelectorAll('input[type=text]').forEach(el => {
    el.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); f.submit(); } });
    el.addEventListener('blur', () => f.submit());
  });
})();
</script>
</div></body></html>
