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

if (isset($_GET['toggle'])) {
    $pdo->prepare("UPDATE mrbs_defensor SET activo = 1 - activo WHERE defensor_id=? AND publico='S'")->execute([$_GET['toggle']]);
    $fRedir = ['f_nombre' => trim($_GET['f_nombre'] ?? ''), 'f_activo' => $_GET['f_activo'] ?? '1'];
    header('Location: listarDefensoresPublicos.php?' . http_build_query($fRedir));
    exit;
}

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

$cols_ok = ['defensor_id','nombre','apellido','activo'];
$sort    = in_array($_GET['sort'] ?? '', $cols_ok, true) ? $_GET['sort'] : 'defensor_id';
$dir     = strtoupper($_GET['dir'] ?? 'ASC') === 'DESC' ? 'DESC' : 'ASC';
$nextDir = $dir === 'ASC' ? 'DESC' : 'ASC';
$ind     = $dir === 'ASC' ? '▲' : '▼';
function sl($col,$lbl,$sort,$dir,$nextDir,$ind,$f){
    $d=$sort===$col?$nextDir:'ASC';
    return '<a href="?'.http_build_query(array_merge($f,['sort'=>$col,'dir'=>$d])).'">'.$lbl.($sort===$col?' '.$ind:'').'</a>';
}

$f = [
    'f_nombre' => trim($_GET['f_nombre'] ?? ''),
    'f_activo' => $_GET['f_activo'] ?? '1',
];

$where  = ["publico = 'S'"];
$params = [];
if ($f['f_nombre']) { $where[] = "(nombre LIKE ? OR apellido LIKE ? OR nombreOrig LIKE ?)"; $params=array_merge($params,array_fill(0,3,'%'.$f['f_nombre'].'%')); }
if ($f['f_activo'] !== '') { $where[] = "activo=?"; $params[] = (int)$f['f_activo']; }

$wSql = 'WHERE '.implode(' AND ',$where);
$stmt = $pdo->prepare("SELECT * FROM mrbs_defensor $wSql ORDER BY $sort $dir");
$stmt->execute($params);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);


$total = $pdo->query("SELECT COUNT(*) FROM mrbs_defensor WHERE publico='S'")->fetchColumn();
?>
<div class="ph">
  <div>
    <h1>Defensores</h1>
    <div class="bc"><a href="<?=BASE_URL?>/index.php">Inicio</a> › Litigantes › Defensores</div>
  </div>
</div>

<!-- Tabs -->
<div style="display:flex;gap:0;margin-bottom:16px;border-bottom:2px solid #e2e8f0">
  <a href="listarDefensoresPublicos.php"
     style="padding:10px 20px;font-weight:700;font-size:14px;text-decoration:none;border-bottom:3px solid #2563eb;color:#2563eb;margin-bottom:-2px;background:#fff">
    🏛️ Defensoría Pública <span style="background:#e0e7ff;color:#3730a3;border-radius:10px;padding:1px 8px;font-size:12px"><?=$total?></span>
  </a>
  <a href="listarDefensoresPrivados.php"
     style="padding:10px 20px;font-weight:600;font-size:14px;text-decoration:none;color:#64748b;border-bottom:3px solid transparent;margin-bottom:-2px">
    👤 Defensores Privados
  </a>
</div>

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

<div style="display:flex;justify-content:flex-end;margin-bottom:8px">
  <?php if (perm('litigantes','agregar')): ?><a href="crearDefensorPublico.php" class="btn btn-p">+ Nuevo Defensor Público</a><?php endif; ?>
</div>

<div class="card">
  <form method="GET" class="fb">
    <div class="fi"><label>Nombre</label>
      <input type="text" name="f_nombre" value="<?=htmlspecialchars($f['f_nombre'])?>" placeholder="Buscar..."></div>
    <div class="fi"><label>Activo</label>
      <select name="f_activo">
        <option value="">Todos</option>
        <option value="1" <?=$f['f_activo']==='1'?'selected':''?>>Sí</option>
        <option value="0" <?=$f['f_activo']==='0'?'selected':''?>>No</option>
      </select></div>
    <div class="fi" style="display:flex;align-items:flex-end;gap:6px">
      <button class="btn btn-p">Filtrar</button>
      <a href="listarDefensoresPublicos.php" class="btn btn-g">Limpiar</a>
    </div>
    <input type="hidden" name="sort" value="<?=htmlspecialchars($sort)?>">
    <input type="hidden" name="dir"  value="<?=htmlspecialchars($dir)?>">
  </form>
</div>

<div style="margin-bottom:6px;font-size:13px;color:#475569"><?=count($rows)?> resultado(s)</div>
<div class="tw"><table>
  <thead><tr>
    <th style="width:70px"><?=sl('defensor_id','ID',$sort,$dir,$nextDir,$ind,$f)?></th>
    <th style="width:120px"><?=sl('apellido','Apellido',$sort,$dir,$nextDir,$ind,$f)?></th>
    <th style="width:100px"><?=sl('nombre','Nombre corto',$sort,$dir,$nextDir,$ind,$f)?></th>
    <th>En Grilla</th>
    <th style="width:200px">Mail</th>
    <th style="width:110px">Teléfono</th>
    <th style="width:70px"><?=sl('activo','Activo',$sort,$dir,$nextDir,$ind,$f)?></th>
    <th style="width:165px">Acciones</th>
  </tr></thead>
  <tbody>
  <?php foreach ($rows as $r): ?>
    <tr>
      <td><?=htmlspecialchars($r['defensor_id'])?></td>
      <td><?=htmlspecialchars($r['apellido']??'')?></td>
      <td><?=htmlspecialchars($r['nombre']??'')?></td>
      <td><?=htmlspecialchars($r['nombreOrig']??'')?></td>
      <td style="font-size:12px"><?=htmlspecialchars($r['mail']??'')?></td>
      <td><?=htmlspecialchars($r['telefono']??'')?></td>
      <td style="text-align:center"><?=$r['activo']?'<span class="bp bp-l">Sí</span>':'<span class="bp bp-r">No</span>'?></td>
      <td><div class="ac">
        <?php if (perm('litigantes','editar')): ?><a href="crearDefensorPublico.php?id=<?=urlencode($r['defensor_id'])?>" class="btn btn-i btn-sm">Editar</a><?php endif; ?>
        <?php if (perm('litigantes','editar')): ?>
        <?php if ($r['activo']): ?>
        <a href="?toggle=<?=urlencode($r['defensor_id'])?>&<?=http_build_query($f)?>"
           class="btn btn-r btn-sm" onclick="return confirm('¿Confirma la desactivación del defensor?')">Desactivar</a>
        <?php else: ?>
        <a href="?toggle=<?=urlencode($r['defensor_id'])?>&<?=http_build_query($f)?>"
           class="btn btn-s btn-sm" onclick="return confirm('¿Confirma la activación del defensor?')">Activar</a>
        <?php endif; ?>
        <?php endif; ?>
      </div></td>
    </tr>
  <?php endforeach; ?>
  <?php if (!$rows): ?><tr><td colspan="8" style="text-align:center;color:#94a3b8">Sin resultados</td></tr><?php endif; ?>
  </tbody>
</table></div>
</div></body></html>
