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

// ── AJAX: guardar/borrar preferencias de layout ───────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['save_prefs'])) {
    $key   = preg_replace('/[^a-zA-Z_]/', '', $_GET['save_prefs']);
    $prefs = json_decode(file_get_contents('php://input'), true) ?? [];
    if ($key && $prefs) {
        try {
            $pdo->prepare("INSERT INTO agj_user_prefs (usuario,pref_key,pref_value)
                VALUES (?,?,?) ON DUPLICATE KEY UPDATE pref_value=VALUES(pref_value),updated_at=NOW()")
                ->execute([$_SESSION['usuario'], $key, json_encode($prefs)]);
        } catch(Throwable $e) {}
    }
    header('Content-Type: application/json'); echo '{"ok":true}'; exit;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_GET['delete_prefs'])) {
    $key = preg_replace('/[^a-zA-Z_]/', '', $_GET['delete_prefs']);
    if ($key) {
        try {
            $pdo->prepare("DELETE FROM agj_user_prefs WHERE usuario=? AND pref_key=?")
                ->execute([$_SESSION['usuario'], $key]);
        } catch(Throwable $e) {}
    }
    header('Content-Type: application/json'); echo '{"ok":true}'; exit;
}

// ── Parámetros ────────────────────────────────────────────────────────────────
$page         = max(1,(int)($_GET['page']??1));
$per_page_raw = isset($_GET['per_page']) ? (int)$_GET['per_page'] : 20;
$per_page     = in_array($per_page_raw, [10,20,50,100,9999], true) ? $per_page_raw : 20;
$todos        = $per_page === 9999;

$ordenWhitelist = [
    'ag.debate_desde','ag.debate_hasta','ag.estado','ag.condicion','ag.turno',
    'aa.cuij_principal','aa.imputados','ag.jornadas','aa.delitos','tipo_tribunal',
];
$orden = in_array($_GET['orden']??'', $ordenWhitelist, true)
    ? $_GET['orden'] : 'ag.debate_desde';
$dir = strtoupper($_GET['dir']??'ASC') === 'DESC' ? 'DESC' : 'ASC';

$f = [
    'cuij'      => trim($_GET['f_cuij']??''),
    'imputados' => trim($_GET['f_imputados']??''),
    'estado'    => $_GET['f_estado']??'',
    'condicion' => $_GET['f_condicion']??'',
    'turno'     => $_GET['f_turno']??'',
    'juez'      => trim($_GET['f_juez']??''),
    'fiscal'    => trim($_GET['f_fiscal']??''),
    'defensor'  => trim($_GET['f_defensor']??''),
    'desde'     => isset($_GET['f_desde']) ? $_GET['f_desde'] : date('Y-m-d', strtotime('-7 days')),
    'hasta'     => $_GET['f_hasta']??'',
];

// ── WHERE ─────────────────────────────────────────────────────────────────────
$where  = ["ag.deleted_at IS NULL"];
$params = [];
if ($f['cuij'])      { $where[] = "(aa.cuij_principal LIKE ? OR aa.otros_cuijs LIKE ?)"; $params[] = '%'.$f['cuij'].'%'; $params[] = '%'.$f['cuij'].'%'; }
if ($f['imputados']) { $where[] = "aa.imputados LIKE ?";    $params[] = '%'.$f['imputados'].'%'; }
if ($f['estado'])    { $where[] = "ag.estado = ?";          $params[] = $f['estado']; }
if ($f['condicion']) { $where[] = "ag.condicion = ?";       $params[] = $f['condicion']; }
if ($f['turno'])     { $where[] = "ag.turno = ?";           $params[] = $f['turno']; }
if ($f['desde'])     { $where[] = "ag.debate_desde >= ?";   $params[] = $f['desde']; }
if ($f['hasta'])     { $where[] = "ag.debate_desde <= ?";   $params[] = $f['hasta']; }
if ($f['juez'])      { $where[] = "(jPte.nombre LIKE ? OR jV1.nombre LIKE ? OR jV2.nombre LIKE ?)";
                       $params[] = '%'.$f['juez'].'%'; $params[] = '%'.$f['juez'].'%'; $params[] = '%'.$f['juez'].'%'; }
if ($f['fiscal'])    { $where[] = "EXISTS(SELECT 1 FROM agj_aa_litigantes al JOIN v_litigantes vl ON al.litigante_id=vl.litigante_id WHERE al.aa_id=aa.id AND al.rol_en_causa='Fiscal' AND vl.nombre LIKE ?)"; $params[] = '%'.$f['fiscal'].'%'; }
if ($f['defensor'])  { $where[] = "EXISTS(SELECT 1 FROM agj_aa_litigantes al JOIN v_litigantes vl ON al.litigante_id=vl.litigante_id WHERE al.aa_id=aa.id AND al.rol_en_causa='Defensor' AND vl.nombre LIKE ?)"; $params[] = '%'.$f['defensor'].'%'; }

$wSql = "WHERE " . implode(' AND ', $where);

$fromSql = "
FROM agj_agendamientos ag
JOIN agj_autos_apertura aa ON ag.aa_id = aa.id
LEFT JOIN mrbs_juez jPte ON ag.presidente_id = jPte.juez_id
LEFT JOIN mrbs_juez jV1  ON ag.vocal_1_id    = jV1.juez_id
LEFT JOIN mrbs_juez jV2  ON ag.vocal_2_id    = jV2.juez_id
$wSql";

$subF    = "(SELECT GROUP_CONCAT(vl.nombre ORDER BY al.orden,al.id SEPARATOR '\n') FROM agj_aa_litigantes al JOIN v_litigantes vl ON al.litigante_id=vl.litigante_id WHERE al.aa_id=aa.id AND al.rol_en_causa='Fiscal') AS fiscales";
$subD    = "(SELECT GROUP_CONCAT(vl.nombre ORDER BY al.orden,al.id SEPARATOR '\n') FROM agj_aa_litigantes al JOIN v_litigantes vl ON al.litigante_id=vl.litigante_id WHERE al.aa_id=aa.id AND al.rol_en_causa='Defensor') AS defensores";
$subQ    = "(SELECT GROUP_CONCAT(vl.nombre ORDER BY al.orden,al.id SEPARATOR '\n') FROM agj_aa_litigantes al JOIN v_litigantes vl ON al.litigante_id=vl.litigante_id WHERE al.aa_id=aa.id AND al.rol_en_causa='Querellante') AS querellantes";
$subJIPP = "(SELECT GROUP_CONCAT(mj.nombre ORDER BY ji.orden,ji.id SEPARATOR '\n') FROM agj_aa_jueces_ipp ji JOIN mrbs_juez mj ON ji.juez_id=mj.juez_id WHERE ji.aa_id=aa.id) AS jueces_intervinientes";

$selectSql = "ag.id AS ag_id, aa.id AS aa_id,
    aa.cuij_principal, aa.imputados, aa.estado_imputado, aa.prioridad,
    aa.vencimiento_pp_actual, aa.delitos AS delito, aa.testigos_aa,
    aa.observaciones, aa.medidas_juzgado_familia,
    DATEDIFF(aa.vencimiento_pp_actual, ag.debate_desde) AS plazo_pp_debate,
    ag.condicion, ag.sub_condicion, ag.turno, ag.estado, ag.tramite,
    ag.jornadas, ag.jornadas_extras, ag.dia_pre_alegatos, aa.duplicidad_plazos,
    ag.debate_desde_original, ag.debate_desde, ag.debate_hasta,
    ag.fecha_fallo, ag.fecha_fin_bloqueo, ag.apoyo_oam,
    CASE WHEN ag.vocal_1_id IS NOT NULL THEN 'Colegiado' ELSE 'Unipersonal' END AS tipo_tribunal,
    jPte.nombre AS presidente,
    jV1.nombre  AS vocal_1,
    jV2.nombre  AS vocal_2,
    $subJIPP, $subF, $subD, $subQ";

// ── CSV export ────────────────────────────────────────────────────────────────
if (($_GET['export']??'') === 'csv') {
    $stmtE = $pdo->prepare("SELECT $selectSql $fromSql ORDER BY $orden $dir");
    $stmtE->execute($params);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="agenda_'.date('Ymd').'.csv"');
    $out = fopen('php://output','w');
    fprintf($out, chr(0xEF).chr(0xBB).chr(0xBF));
    fputcsv($out, ['CUIJ','Imputados','Delito','Cond.','Turno','Estado','Tipo Tribunal','Jorn.','Extra','Pre-Aleg.','Testigos','Apoyo','Dup.','Debate Desde','Debate Hasta','Fallo','Fin Bloqueo','Días PP','Presidente','Vocal 1','Vocal 2','Fiscales','Defensores','Querellantes'], ';');
    while ($r = $stmtE->fetch()) fputcsv($out, [
        $r['cuij_principal'], $r['imputados'], $r['delito'],
        $r['condicion'], $r['turno'], $r['estado'], $r['tipo_tribunal'],
        $r['jornadas'], $r['jornadas_extras'], $r['dia_pre_alegatos'],
        $r['testigos_aa'], $r['apoyo_oam'], $r['duplicidad_plazos'] ? 'Sí' : 'No',
        $r['debate_desde'], $r['debate_hasta'], $r['fecha_fallo'], $r['fecha_fin_bloqueo'],
        $r['plazo_pp_debate'],
        $r['presidente'], $r['vocal_1'], $r['vocal_2'],
        str_replace("\n",' / ',$r['fiscales']??''),
        str_replace("\n",' / ',$r['defensores']??''),
        str_replace("\n",' / ',$r['querellantes']??''),
    ], ';');
    fclose($out); exit;
}

// ── Paginación ────────────────────────────────────────────────────────────────
$cnt = $pdo->prepare("SELECT COUNT(*) $fromSql"); $cnt->execute($params);
$total       = (int)$cnt->fetchColumn();
$total_pages = $todos ? 1 : (int)ceil($total / $per_page);
$lim         = $todos ? '' : "LIMIT $per_page OFFSET " . (($page-1)*$per_page);

$stmt = $pdo->prepare("SELECT $selectSql $fromSql ORDER BY $orden $dir $lim");
$stmt->execute($params);
$juicios = $stmt->fetchAll();

// ── Columnas configurables ────────────────────────────────────────────────────
$todasColsAg = [
    'imputados'         => 'Imputados',
    'delito'            => 'Delito',
    'condicion'         => 'Condición',
    'estado'            => 'Estado',
    'apoyo'             => 'Apoyo',
    'testigos'          => 'Testigos',
    'jornadas'          => 'Jornadas',
    'extras'            => 'Jorn. Extra',
    'prealegatos'       => 'Pre-Alegatos',
    'duplicidad'        => 'Dup. Plazos',
    'turno'             => 'Turno',
    'debate_desde'      => 'Desde',
    'debate_hasta'      => 'Hasta',
    'fecha_fallo'       => 'Fallo',
    'fecha_fin_bloqueo' => 'Fin Bloqueo',
    'presidente'        => 'Presidente',
    'vocal_1'           => 'Vocal 1',
    'vocal_2'           => 'Vocal 2',
    'fiscales'          => 'Fiscal/es',
    'defensores'        => 'Defensor/es',
    'querellantes'      => 'Querellante/s',
    'plazo_pp'          => 'PP+debate',
    'tipo_tribunal'     => 'Tipo Tribunal',
];
$defColsAg = array_keys($todasColsAg);

// ── Preferencias de layout (orden + anchos + hscroll) ────────────────────────
$layoutPrefs = [];
try {
    $s = $pdo->prepare("SELECT pref_value FROM agj_user_prefs WHERE usuario=? AND pref_key='layout_listarAgenda'");
    $s->execute([$_SESSION['usuario']]);
    $v = $s->fetchColumn();
    if ($v) $layoutPrefs = json_decode($v, true) ?? [];
} catch(Throwable $e) {}
$savedColOrder  = $layoutPrefs['order']  ?? [];
$savedColWidths = $layoutPrefs['widths'] ?? [];
$savedHScroll   = (bool)($layoutPrefs['hscroll'] ?? false);
$savedSavePrefs = !empty($savedColOrder);

// Aplicar orden guardado
if (!empty($savedColOrder)) {
    $reordered = [];
    foreach ($savedColOrder as $k) { if (isset($todasColsAg[$k])) $reordered[$k] = $todasColsAg[$k]; }
    foreach ($todasColsAg as $k => $v) { if (!isset($reordered[$k])) $reordered[$k] = $v; }
    $todasColsAg = $reordered;
}

// ── Columnas visibles ─────────────────────────────────────────────────────────
$visColsAg = !empty($_GET['ag_cols'])
    ? array_intersect(array_keys($todasColsAg), (array)$_GET['ag_cols'])
    : $defColsAg;

if (isset($_GET['ag_cols'])) {
    try {
        $pdo->prepare("INSERT INTO agj_user_prefs (usuario,pref_key,pref_value)
            VALUES (?,?,?) ON DUPLICATE KEY UPDATE pref_value=VALUES(pref_value),updated_at=NOW()")
            ->execute([$_SESSION['usuario'],'cols_listarAgenda',implode(',',$visColsAg)]);
    } catch(Throwable $ignored) {}
} elseif (!array_key_exists('ag_cols', $_GET)) {
    try {
        $s2 = $pdo->prepare("SELECT pref_value FROM agj_user_prefs WHERE usuario=? AND pref_key='cols_listarAgenda'");
        $s2->execute([$_SESSION['usuario']]);
        $saved = $s2->fetchColumn();
        if ($saved) {
            $loaded = array_intersect(array_keys($todasColsAg), explode(',', $saved));
            if (!empty($loaded)) $visColsAg = $loaded;
        }
    } catch(Throwable $ignored) {}
}

// Helper: ancho guardado
function colWidth(string $col, array $widths): string {
    return isset($widths[$col]) ? ';width:'.$widths[$col].'px' : '';
}

$paginaActual = 'juicios';
require __DIR__ . '/../../config/menu.php';
?>
<div class="ph">
  <div><h1>📅 Agenda de Juicios</h1><div class="bc"><?=$total?> agendamientos</div></div>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <?php if (perm('agenda','agregar')): ?><a href="crearAgendamiento.php" class="btn btn-s">➕ Agendar</a><?php endif; ?>
    <a href="?<?=http_build_query(array_merge($_GET,['export'=>'csv']))?>" class="btn btn-g">↓ CSV</a>
  </div>
</div>

<form method="GET" id="ff" class="fb">
  <div class="fi"><label>CUIJ</label><input type="text" name="f_cuij" value="<?=htmlspecialchars($f['cuij'])?>" class="as"></div>
  <div class="fi"><label>Imputado</label><input type="text" name="f_imputados" value="<?=htmlspecialchars($f['imputados'])?>" class="as"></div>
  <div class="fi"><label>Estado</label>
    <select name="f_estado" class="as">
      <option value="">Todos</option>
      <?php foreach(['Programado','Agendado','Realizado','Suspendido','Cancelado'] as $e): ?>
        <option value="<?=$e?>" <?=$f['estado']===$e?'selected':''?>><?=$e?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="fi"><label>Condición</label>
    <select name="f_condicion" class="as">
      <option value="">Todas</option>
      <option value="Titular"       <?=$f['condicion']==='Titular'      ?'selected':''?>>Titular</option>
      <option value="SobreAgendado" <?=$f['condicion']==='SobreAgendado'?'selected':''?>>SobreAgendado</option>
    </select>
  </div>
  <div class="fi"><label>Turno</label>
    <select name="f_turno" class="as">
      <option value="">Todos</option>
      <option value="Matutino"      <?=$f['turno']==='Matutino'     ?'selected':''?>>Matutino</option>
      <option value="Vespertino"    <?=$f['turno']==='Vespertino'   ?'selected':''?>>Vespertino</option>
      <option value="Doble Jornada" <?=$f['turno']==='Doble Jornada'?'selected':''?>>Doble Jornada</option>
    </select>
  </div>
  <div class="fi"><label>Juez (tribunal)</label><input type="text" name="f_juez" value="<?=htmlspecialchars($f['juez'])?>" class="as" placeholder="Apellido…"></div>
  <div class="fi"><label>Fiscal</label><input type="text" name="f_fiscal" value="<?=htmlspecialchars($f['fiscal'])?>" class="as" placeholder="Apellido…"></div>
  <div class="fi"><label>Defensor</label><input type="text" name="f_defensor" value="<?=htmlspecialchars($f['defensor'])?>" class="as" placeholder="Apellido…"></div>
  <div class="fi"><label>Debate desde</label><input type="date" name="f_desde" value="<?=$f['desde']?>" class="as"></div>
  <div class="fi"><label>Debate hasta</label><input type="date" name="f_hasta" value="<?=$f['hasta']?>" class="as"></div>
  <div class="fi"><label>Por página</label>
    <select name="per_page" class="as">
      <?php foreach([10,20,50,100,9999] as $pp): ?>
        <option value="<?=$pp?>" <?=$per_page==$pp?'selected':''?>><?=$pp===9999?'Todos':$pp?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="fi" style="align-self:flex-end;flex-wrap:wrap;gap:6px">
    <button type="submit" class="btn btn-p">🔍 Buscar</button>
    <a href="listarAgenda.php" class="btn btn-g">Limpiar</a>
    <span style="display:inline-flex;align-items:center;gap:12px;margin-left:6px;font-size:12px;color:#374151">
      <label style="display:inline-flex;align-items:center;gap:3px;cursor:pointer;white-space:nowrap"
             title="Guarda las preferencias de orden de columnas y tamaño">
        <input type="checkbox" id="chk-save-prefs" <?=$savedSavePrefs?'checked':''?>>Guardar preferencias ⓘ
      </label>
      <label style="display:inline-flex;align-items:center;gap:3px;cursor:pointer;white-space:nowrap">
        <input type="checkbox" id="chk-hscroll" <?=$savedHScroll?'checked':''?>>Scroll horizontal
      </label>
      <label style="display:inline-flex;align-items:center;gap:3px;cursor:pointer;white-space:nowrap"
             title="Vuelve al orden y visibilidad por defecto">
        <input type="checkbox" id="chk-reset-order">Orden por defecto
      </label>
    </span>
  </div>

  <!-- Selector de columnas -->
  <div class="fi" id="agColPickerWrap" style="position:relative;align-self:flex-end">
    <button type="button" class="btn btn-g"
            onclick="document.getElementById('agColPickerPanel').style.display=document.getElementById('agColPickerPanel').style.display==='none'?'block':'none'">
      Columnas (<?=count($visColsAg)?>) ▾
    </button>
    <div id="agColPickerPanel" style="display:none;position:absolute;top:100%;right:0;z-index:300;
         background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:10px 14px;
         min-width:210px;max-height:420px;overflow-y:auto;
         box-shadow:0 4px 16px rgba(0,0,0,.12);margin-top:2px">
      <?php foreach ($todasColsAg as $c => $l): ?>
        <label style="display:flex;align-items:center;justify-content:space-between;gap:16px;padding:4px 0;cursor:pointer;font-size:13px;min-width:190px">
          <span><?=$l?></span>
          <input type="checkbox" name="ag_cols[]" value="<?=$c?>" <?=in_array($c,$visColsAg,true)?'checked':''?>>
        </label>
      <?php endforeach; ?>
      <div style="margin-top:8px;padding-top:8px;border-top:1px solid #e2e8f0;display:flex;gap:6px">
        <button type="submit" class="btn btn-p btn-sm">Aplicar</button>
        <button type="button" class="btn btn-g btn-sm"
                onclick="document.getElementById('agColPickerPanel').style.display='none'">Cerrar</button>
      </div>
    </div>
  </div>

  <input type="hidden" name="orden" value="<?=htmlspecialchars($orden)?>">
  <input type="hidden" name="dir"   value="<?=htmlspecialchars($dir)?>">
  <input type="hidden" name="page"  value="1">
</form>

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

<div class="tw"><table id="tAgenda" style="table-layout:auto">
  <thead><tr>
    <th data-col="cuij_principal" style="<?= isset($savedColWidths['cuij_principal']) ? 'width:'.$savedColWidths['cuij_principal'].'px' : '' ?>"><?=ordenLink('aa.cuij_principal','CUIJ',$orden,$dir)?></th>
    <?php foreach ($todasColsAg as $col => $label):
      if (!in_array($col, $visColsAg)) continue;
      $wStyle = colWidth($col, $savedColWidths);
      switch ($col) {
        case 'presidente': case 'vocal_1': case 'vocal_2':
          $bg = 'background:#1e3a5f;'; break;
        case 'fiscales': case 'defensores': case 'querellantes':
          $bg = 'background:#374151;'; break;
        default: $bg = '';
      }
      $sortCol = match($col) {
        'debate_desde'   => 'ag.debate_desde',
        'debate_hasta'   => 'ag.debate_hasta',
        'estado'         => 'ag.estado',
        'condicion'      => 'ag.condicion',
        'turno'          => 'ag.turno',
        'imputados'      => 'aa.imputados',
        'delito'         => 'aa.delitos',
        'tipo_tribunal'  => 'tipo_tribunal',
        default          => null,
      };
    ?>
    <th data-col="<?=$col?>" style="<?=$bg?><?=$wStyle?>">
      <?= $sortCol ? ordenLink($sortCol, $label, $orden, $dir) : htmlspecialchars($label) ?>
    </th>
    <?php endforeach; ?>
    <th>Acc.</th>
  </tr></thead>
  <tbody>
  <?php
  $hoy = date('Y-m-d');
  foreach ($juicios as $j):
    $enCurso = !empty($j['debate_desde']) && $j['debate_desde'] <= $hoy
            && !empty($j['debate_hasta']) && $j['debate_hasta'] >= $hoy;
    $medFam  = !empty($j['medidas_juzgado_familia']);
  ?>
  <tr style="<?=$enCurso ? 'background:#fffbeb' : ($medFam ? 'background:#fef9c3' : '')?>">
    <td title="<?=htmlspecialchars($j['observaciones']??'')?>"><strong><?=htmlspecialchars($j['cuij_principal'])?></strong></td>
    <?php foreach ($todasColsAg as $col => $label):
      if (!in_array($col, $visColsAg)) continue;
    ?>
    <td data-col="<?=$col?>"<?php
      switch ($col) {
        case 'presidente': case 'vocal_1': case 'vocal_2':
          echo " style='white-space:normal;background:#f0f4ff'"; break;
        case 'fiscales': case 'defensores': case 'querellantes':
          echo " style='white-space:normal;background:#f9fafb'"; break;
        case 'imputados': case 'delito':
          echo " class='w' style='white-space:normal'"; break;
      }
    ?>>
    <?php switch ($col):
      case 'imputados': echo htmlspecialchars($j['imputados']); break;
      case 'condicion':
        echo badgeCondicion($j['condicion']);
        if (!empty($j['sub_condicion'])) echo '<br><small style="color:#64748b">'.htmlspecialchars($j['sub_condicion']).'</small>';
        break;
      case 'turno': echo htmlspecialchars($j['turno']??'—'); break;
      case 'tipo_tribunal':
        $ttColor = $j['tipo_tribunal']==='Colegiado' ? '#2563eb' : '#7c3aed';
        echo "<span style='font-size:11px;font-weight:600;color:{$ttColor}'>" . htmlspecialchars($j['tipo_tribunal']) . '</span>';
        break;
      case 'debate_desde':
        echo fmtFecha($j['debate_desde']); echo $enCurso?' 🔴':'';
        if (!empty($j['debate_desde_original']) && $j['debate_desde_original'] !== $j['debate_desde'])
          echo '<br><small style="color:#94a3b8;text-decoration:line-through">'.fmtFecha($j['debate_desde_original']).'</small>';
        break;
      case 'debate_hasta':  echo fmtFecha($j['debate_hasta']); break;
      case 'fecha_fallo':   echo fmtFecha($j['fecha_fallo']); break;
      case 'fecha_fin_bloqueo': echo fmtFecha($j['fecha_fin_bloqueo']); break;
      case 'jornadas':
        echo '<span style="text-align:center;display:block">' . ($j['jornadas']??'—') . '</span>';
        break;
      case 'extras':
        echo '<span style="text-align:center;display:block">' . ($j['jornadas_extras'] ?: '—') . '</span>';
        break;
      case 'prealegatos':
        echo '<span style="text-align:center;display:block">' . ($j['dia_pre_alegatos'] ?: '—') . '</span>';
        break;
      case 'testigos':
        echo '<span style="text-align:center;display:block">' . ($j['testigos_aa'] ?: '—') . '</span>';
        break;
      case 'apoyo':
        echo htmlspecialchars($j['apoyo_oam']??'—');
        break;
      case 'duplicidad':
        $dup = (bool)$j['duplicidad_plazos'];
        $dColor = $dup ? '#dc2626' : '#16a34a';
        echo "<span style='color:{$dColor};font-weight:600;font-size:12px'>" . ($dup ? 'Sí' : 'No') . '</span>';
        break;
      case 'plazo_pp':
        if ($j['plazo_pp_debate'] !== null && $j['estado_imputado'] === 'Preso'):
          $v = (int)$j['plazo_pp_debate'];
          $color = $v < 30 ? '#dc2626' : ($v < 90 ? '#d97706' : '#16a34a');
          echo "<span style='color:{$color};font-weight:700'>{$v}d</span>";
        else: echo '—'; endif;
        break;
      case 'presidente': echo htmlspecialchars($j['presidente']??'') ?: '<span style="color:#94a3b8;font-style:italic">—</span>'; break;
      case 'vocal_1':    echo htmlspecialchars($j['vocal_1']??'')    ?: '<span style="color:#94a3b8;font-style:italic">—</span>'; break;
      case 'vocal_2':    echo htmlspecialchars($j['vocal_2']??'')    ?: '<span style="color:#94a3b8;font-style:italic">—</span>'; break;
      case 'fiscales':      echo celdaLitigantes($j['fiscales']); break;
      case 'defensores':    echo celdaLitigantes($j['defensores']); break;
      case 'querellantes':  echo celdaLitigantes($j['querellantes']); break;
      case 'delito':
        $del = htmlspecialchars($j['delito']??'');
        $short = mb_strlen($del) > 60 ? mb_substr($del,0,60).'…' : $del;
        echo "<span title='{$del}'>{$short}</span>";
        break;
      case 'estado':
        $ec = ['Programado'=>'#7c3aed','Agendado'=>'#0891b2','Realizado'=>'#16a34a','Suspendido'=>'#d97706','Cancelado'=>'#dc2626'];
        $c = $ec[$j['estado']] ?? '#64748b';
        echo "<span style='background:{$c}20;color:{$c};padding:1px 7px;border-radius:10px;font-size:11px;font-weight:700'>".htmlspecialchars($j['estado'])."</span>";
        break;
    endswitch; ?>
    </td>
    <?php endforeach; ?>
    <td class="ac">
      <a href="verAgendamiento.php?id=<?=$j['ag_id']?>"    class="btn btn-i btn-sm">Ver</a>
      <?php if (perm('agenda','editar')): ?><a href="editarAgendamiento.php?id=<?=$j['ag_id']?>" class="btn btn-w btn-sm">✏️</a><?php endif; ?>
    </td>
  </tr>
  <?php endforeach; ?>
  <?php if (empty($juicios)): ?>
  <tr><td colspan="<?=count($visColsAg)+2?>" style="text-align:center;color:#64748b;padding:20px">Sin registros</td></tr>
  <?php endif; ?>
  </tbody>
</table></div>

<?php if (!$todos): ?>
<div style="display:flex;align-items:center;justify-content:space-between">
  <?=paginacion($page,$total_pages)?>
  <span class="pgi">Mostrando <?=min($per_page,max(0,$total-($page-1)*$per_page))?> de <?=$total?></span>
</div>
<?php endif; ?>

</div></body></html>
<script>
// Auto-submit filtros
document.querySelectorAll('.as').forEach(el => {
  el.addEventListener('change', () => document.getElementById('ff').submit());
  if (el.tagName === 'INPUT') el.addEventListener('blur', function() {
    if (this.value !== this.defaultValue) document.getElementById('ff').submit();
    this.defaultValue = this.value;
  });
});
// Cerrar colPicker al hacer clic afuera
document.addEventListener('click', function(e) {
  const wrap = document.getElementById('agColPickerWrap');
  if (wrap && !wrap.contains(e.target)) document.getElementById('agColPickerPanel').style.display = 'none';
});

// ── Resize, reorder, hscroll, guardar prefs ───────────────────────────────────
(function(){
  const PREF_KEY = 'layout_listarAgenda';
  const RZONE    = 10; // px desde el borde derecho para activar resize
  const table    = document.getElementById('tAgenda');
  if (!table) return;

  // Aplicar anchos guardados y fijar layout
  const initWidths = <?= json_encode((object)$savedColWidths) ?>;
  table.querySelectorAll('th[data-col]').forEach(th => {
    const w = initWidths[th.dataset.col];
    if (w) th.style.width = w + 'px';
  });
  table.querySelectorAll('th').forEach(th => {
    if (!th.style.width) th.style.width = th.offsetWidth + 'px';
  });
  table.style.tableLayout = 'fixed';

  // Resize por delegación: funciona en th y td de cualquier fila ─────────────
  let _resizing = false, _nearRight = false;

  table.addEventListener('mousemove', e => {
    if (_resizing) return;
    const cell = e.target.closest('td,th');
    if (!cell) return;
    const rect = cell.getBoundingClientRect();
    cell.style.cursor = e.clientX > rect.right - RZONE ? 'col-resize' : '';
  });

  table.addEventListener('mousedown', e => {
    const cell = e.target.closest('td,th');
    if (!cell) return;
    const rect = cell.getBoundingClientRect();
    _nearRight = e.clientX > rect.right - RZONE;
    if (!_nearRight) return;
    e.preventDefault();
    const row    = cell.parentElement;
    const colIdx = Array.from(row.children).indexOf(cell);
    const th     = table.querySelector('thead tr').children[colIdx];
    if (!th) return;
    _resizing = true;
    const sx = e.pageX, sw = th.offsetWidth;
    const mm = ev => { th.style.width = Math.max(40, sw + ev.pageX - sx) + 'px'; };
    const mu = () => {
      _resizing = false; _nearRight = false;
      document.removeEventListener('mousemove', mm);
      document.removeEventListener('mouseup', mu);
      savePrefs();
    };
    document.addEventListener('mousemove', mm);
    document.addEventListener('mouseup', mu);
  });

  // Drag to reorder: solo <th data-col> que NO sean la columna fija CUIJ ─────
  let dragFrom = null;
  const getDataCols = () => Array.from(table.querySelectorAll('th[data-col]'));
  getDataCols().forEach((th, i) => {
    if (th.dataset.col === 'cuij_principal') return; // columna fija, no arrastrable
    th.draggable = true;
    th.addEventListener('dragstart', e => {
      if (_nearRight) { e.preventDefault(); return; } // zona de resize → no drag
      dragFrom = getDataCols().indexOf(th); th.style.opacity = '.5';
    });
    th.addEventListener('dragend',   () => { th.style.opacity = ''; });
    th.addEventListener('dragover',  e => { e.preventDefault(); th.style.boxShadow = 'inset 2px 0 0 #2563eb'; });
    th.addEventListener('dragleave', () => { th.style.boxShadow = ''; });
    th.addEventListener('drop', e => {
      e.preventDefault(); th.style.boxShadow = '';
      const ths = getDataCols(), toI = ths.indexOf(th);
      if (dragFrom === null || dragFrom === toI) { dragFrom = null; return; }
      const allThs  = Array.from(table.querySelector('tr').children);
      const fromAbs = allThs.indexOf(ths[dragFrom]);
      const toAbs   = allThs.indexOf(ths[toI]);
      table.querySelectorAll('tr').forEach(row => {
        const c = Array.from(row.children);
        if (!c[fromAbs] || !c[toAbs]) return;
        row.insertBefore(c[fromAbs], fromAbs < toAbs ? c[toAbs].nextSibling : c[toAbs]);
      });
      dragFrom = null;
      savePrefs();
    });
  });

  // Barra de scroll horizontal
  const tw   = document.querySelector('.tw');
  const chkH = document.getElementById('chk-hscroll');
  if (chkH && tw) {
    tw.style.overflowX = chkH.checked ? 'auto' : '';
    chkH.addEventListener('change', () => { tw.style.overflowX = chkH.checked ? 'auto' : ''; savePrefs(); });
  }

  // Guardar preferencias (anchos de TODAS las columnas + orden de las movibles)
  function savePrefs() {
    if (!document.getElementById('chk-save-prefs')?.checked) return;
    const order = [], widths = {};
    table.querySelectorAll('th[data-col]').forEach(th => {
      if (th.style.width) widths[th.dataset.col] = parseInt(th.style.width);
      if (th.dataset.col !== 'cuij_principal') order.push(th.dataset.col);
    });
    fetch('?save_prefs=' + PREF_KEY, {
      method: 'POST', headers: {'Content-Type':'application/json'},
      body: JSON.stringify({order, widths, hscroll: chkH?.checked || false})
    });
  }

  document.getElementById('chk-save-prefs')?.addEventListener('change', function() {
    if (this.checked) savePrefs();
    else fetch('?delete_prefs=' + PREF_KEY, {method:'POST'});
  });

  document.getElementById('chk-reset-order')?.addEventListener('change', function() {
    if (!this.checked) return;
    Promise.all([
      fetch('?delete_prefs=' + PREF_KEY, {method:'POST'}),
      fetch('?delete_prefs=cols_listarAgenda', {method:'POST'})
    ]).then(() => location.reload());
  });
})();
</script>
