<?php
$authApp = 'autos';
session_start();
require __DIR__ . '/../../config/auth.php';
require __DIR__ . '/../../../../../config/db2.php';
require_once __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 de listado ─────────────────────────────────────────────────
$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;
$orden        = $_GET['orden'] ?? 'prioridad';
$dir          = strtoupper($_GET['dir'] ?? 'DESC') === 'ASC' ? 'ASC' : 'DESC';

$cols_ok = ['prioridad','aa.cuij_principal','aa.imputados','aa.estado_imputado',
            'aa.fecha_auto_apertura','aa.vencimiento_pp_actual','aa.estado',
            'aa.fecha_ingreso_agenda','aa.testigos_aa','aa.jornadas_en_aa'];
if (!in_array($orden, $cols_ok, true)) $orden = 'prioridad';

// ── Filtros ───────────────────────────────────────────────────────────────
$f = [
    'cuij'        => trim($_GET['f_cuij'] ?? ''),
    'imputados'   => trim($_GET['f_imputados'] ?? ''),
    'estado'      => $_GET['f_estado'] ?? '',
    'estado_imp'  => $_GET['f_estado_imp'] ?? '',
    'fiscal'      => trim($_GET['f_fiscal'] ?? ''),
    'defensor'    => trim($_GET['f_defensor'] ?? ''),
    'sin_agendar' => $_GET['f_sin_agendar'] ?? '1',
];

$where  = ["aa.deleted_at IS NULL"];
$params = [];
if ($f['sin_agendar'] === '1') {
    $where[] = "NOT EXISTS (
        SELECT 1 FROM agj_agendamientos ag
        WHERE ag.aa_id=aa.id AND ag.estado NOT IN ('Cancelado') AND ag.deleted_at IS NULL
    )";
}
if ($f['cuij'])       { $where[] = "aa.cuij_principal LIKE ?"; $params[] = '%' . $f['cuij'] . '%'; }
if ($f['imputados'])  { $where[] = "aa.imputados LIKE ?";      $params[] = '%' . $f['imputados'] . '%'; }
if ($f['estado'])     { $where[] = "aa.estado = ?";            $params[] = $f['estado']; }
if ($f['estado_imp']) { $where[] = "aa.estado_imputado = ?";   $params[] = $f['estado_imp']; }
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);

// ── Subconsultas de litigantes ────────────────────────────────────────────
$subFiscal = "(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";
$subDefensor = "(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";
$subQuerellante = "(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";
$subJuecesIPP = "(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";

$selectBase = "aa.id, aa.cuij_principal, aa.imputados, aa.delitos, aa.estado, aa.estado_imputado,
    aa.fecha_auto_apertura, aa.fecha_ingreso_agenda,
    aa.vencimiento_pp_actual,
    DATEDIFF(aa.vencimiento_pp_actual, CURDATE()) AS dias_pp,
    DATEDIFF(CURDATE(), aa.fecha_auto_apertura)   AS dias_aa,
    aa.testigos_aa, aa.jornadas_en_aa, aa.jornadas_agregadas_juez,
    aa.tipo_tribunal, aa.cantidad_detenidos, aa.prioridad,
    jaa.nombre AS juez_aa,
    $subJuecesIPP, $subFiscal, $subDefensor, $subQuerellante";

$fromBase = "FROM agj_autos_apertura aa
    LEFT JOIN mrbs_juez jaa ON aa.juez_aa_id = jaa.juez_id
    $wSql";

// ── CSV ───────────────────────────────────────────────────────────────────
if (($_GET['export'] ?? '') === 'csv') {
    $stmtE = $pdo->prepare("SELECT $selectBase $fromBase ORDER BY $orden $dir");
    $stmtE->execute($params);
    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename="autos_apertura_' . date('Ymd') . '.csv"');
    $out = fopen('php://output', 'w');
    fprintf($out, chr(0xEF) . chr(0xBB) . chr(0xBF));
    fputcsv($out, ['CUIJ','Imputados','Estado','Est.Imp','Fecha AA','Días AA','Ingreso Agenda',
                   'Vto.PP','Días PP','Test.','Jorn.AA','Tribunal','Prioridad',
                   'Juez AA','Jueces IPP','Fiscales','Defensores','Querellantes'], ';');
    while ($r = $stmtE->fetch())
        fputcsv($out, [
            $r['cuij_principal'], $r['imputados'], $r['estado'], $r['estado_imputado'],
            $r['fecha_auto_apertura'], $r['dias_aa'], $r['fecha_ingreso_agenda'],
            $r['vencimiento_pp_actual'], $r['dias_pp'],
            $r['testigos_aa'], $r['jornadas_en_aa'], $r['tipo_tribunal'], $r['prioridad'],
            $r['juez_aa'],
            str_replace("\n", ' / ', $r['jueces_intervinientes'] ?? ''),
            str_replace("\n", ' / ', $r['fiscales'] ?? ''),
            str_replace("\n", ' / ', $r['defensores'] ?? ''),
            str_replace("\n", ' / ', $r['querellantes'] ?? ''),
        ], ';');
    fclose($out); exit;
}

// ── Consulta principal ────────────────────────────────────────────────────
$cnt = $pdo->prepare("SELECT COUNT(*) $fromBase");
$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 $selectBase $fromBase ORDER BY $orden $dir $lim");
$stmt->execute($params);
$autos = $stmt->fetchAll();

$hoy60  = date('Y-m-d', strtotime('+60 days'));
$ppUrg  = count(array_filter($autos, fn($r) =>
    !empty($r['vencimiento_pp_actual']) &&
    $r['vencimiento_pp_actual'] <= $hoy60 &&
    $r['estado_imputado'] === 'Preso'
));

// ── Definición de columnas ────────────────────────────────────────────────
$todasCols = [
    'prioridad'              => 'Prioridad',
    'cuij_principal'         => 'CUIJ',
    'imputados'              => 'Imputados',
    'delitos'                => 'Delito',
    'estado'                 => 'Estado',
    'estado_imputado'        => 'Est.<br>Imputado',
    'fecha_auto_apertura'    => 'Fecha AA',
    'dias_aa'                => 'Días AA',
    'fecha_ingreso_agenda'   => 'Ingreso<br>Agenda',
    'vencimiento_pp_actual'  => 'Vto. PP',
    'dias_pp'                => 'Días PP',
    'testigos_aa'            => 'Test. AA',
    'jornadas_en_aa'         => 'Jorn.<br>AA',
    'jornadas_agregadas_juez'=> 'Jorn.<br>Juez',
    'tipo_tribunal'          => 'Tribunal',
    'juez_aa'                => 'Juez del AA',
    'jueces_intervinientes'  => 'Jueces IPP',
    'fiscales'               => 'Fiscal/es',
    'defensores'             => 'Defensor/es',
    'querellantes'           => 'Querellante/s',
];
$defCols = ['prioridad','cuij_principal','imputados','delitos','estado_imputado',
            'vencimiento_pp_actual','dias_pp','jornadas_en_aa','juez_aa',
            'jueces_intervinientes','fiscales','defensores','querellantes','estado'];

$visCols = !empty($_GET['cols'])
    ? array_intersect(array_keys($todasCols), (array)$_GET['cols'])
    : $defCols;

// Persistencia de columnas visibles
if (isset($_GET['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_listarAutos', implode(',', $visCols)]);
    } catch (Throwable $ignored) {}
} elseif (!array_key_exists('cols', $_GET)) {
    try {
        $sp = $pdo->prepare("SELECT pref_value FROM agj_user_prefs WHERE usuario=? AND pref_key='cols_listarAutos'");
        $sp->execute([$_SESSION['usuario']]);
        $saved = $sp->fetchColumn();
        if ($saved) {
            $loaded = array_intersect(array_keys($todasCols), explode(',', $saved));
            if (!empty($loaded)) $visCols = $loaded;
        }
    } catch (Throwable $ignored) {}
}

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

// Aplicar orden guardado a $todasCols y $visCols
if (!empty($savedColOrder)) {
    $reordered = [];
    foreach ($savedColOrder as $k)               { if (isset($todasCols[$k])) $reordered[$k] = $todasCols[$k]; }
    foreach ($todasCols as $k => $lbl)           { if (!isset($reordered[$k])) $reordered[$k] = $lbl; }
    $todasCols = $reordered;
    $visSet = array_flip($visCols);
    $visReordered = [];
    foreach (array_keys($todasCols) as $k)       { if (isset($visSet[$k])) $visReordered[] = $k; }
    $visCols = $visReordered;
}

// Anchos por defecto — imputados y delitos mínimo 15%
$defaultWidths = [
    'prioridad'              => '6%',
    'cuij_principal'         => '8%',
    'imputados'              => '15%',
    'delitos'                => '15%',
    'estado'                 => '7%',
    'estado_imputado'        => '5%',
    'fecha_auto_apertura'    => '6%',
    'dias_aa'                => '4%',
    'fecha_ingreso_agenda'   => '6%',
    'vencimiento_pp_actual'  => '6%',
    'dias_pp'                => '4%',
    'testigos_aa'            => '4%',
    'jornadas_en_aa'         => '4%',
    'jornadas_agregadas_juez'=> '4%',
    'tipo_tribunal'          => '7%',
    'juez_aa'                => '9%',
    'jueces_intervinientes'  => '10%',
    'fiscales'               => '10%',
    'defensores'             => '10%',
    'querellantes'           => '9%',
];

// ── Resumen global y PP (conteos independientes del filtro activo) ────────
$kpiPP = ['pp_3y'=>0,'pp_2y6m'=>0,'pp_2y'=>0,'debates_curso'=>0,
          'total_activos'=>0,'agendados'=>0,'sin_agendar'=>0];
try {
    $condPP = "WHERE aa.deleted_at IS NULL
          AND aa.estado NOT IN ('Cancelado','Realizado','Abreviado')
          AND aa.estado_imputado = 'Preso'
          AND aa.fecha_detencion IS NOT NULL
          AND NOT EXISTS (
              SELECT 1 FROM agj_agendamientos agx
              WHERE agx.aa_id = aa.id AND agx.estado = 'Realizado' AND agx.deleted_at IS NULL
          )
          AND NOT EXISTS (
              SELECT 1 FROM agj_agendamientos agy
              WHERE agy.aa_id = aa.id AND agy.estado NOT IN ('Cancelado')
                AND agy.deleted_at IS NULL
                AND CURDATE() BETWEEN agy.debate_desde AND agy.fecha_fin_bloqueo
          )";

    $kpiPP['pp_3y'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_autos_apertura aa $condPP
        AND DATEDIFF(CURDATE(), aa.fecha_detencion) > 1095
    ")->fetchColumn();

    $kpiPP['pp_2y6m'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_autos_apertura aa $condPP
        AND DATEDIFF(CURDATE(), aa.fecha_detencion) BETWEEN 913 AND 1095
    ")->fetchColumn();

    $kpiPP['pp_2y'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_autos_apertura aa $condPP
        AND DATEDIFF(CURDATE(), aa.fecha_detencion) BETWEEN 730 AND 912
    ")->fetchColumn();

    $kpiPP['debates_curso'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_agendamientos ag
        WHERE ag.deleted_at IS NULL
          AND ag.estado NOT IN ('Cancelado')
          AND CURDATE() BETWEEN ag.debate_desde AND ag.fecha_fin_bloqueo
    ")->fetchColumn();

    $kpiPP['total_activos'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_autos_apertura aa
        WHERE aa.deleted_at IS NULL
          AND aa.estado NOT IN ('Cancelado','Realizado','Abreviado')
    ")->fetchColumn();

    $kpiPP['agendados'] = (int)$pdo->query("
        SELECT COUNT(*) FROM agj_autos_apertura aa
        WHERE aa.deleted_at IS NULL
          AND aa.estado NOT IN ('Cancelado','Realizado','Abreviado')
          AND EXISTS (
              SELECT 1 FROM agj_agendamientos ag
              WHERE ag.aa_id=aa.id AND ag.estado NOT IN ('Cancelado') AND ag.deleted_at IS NULL
          )
    ")->fetchColumn();

    $kpiPP['sin_agendar'] = $kpiPP['total_activos'] - $kpiPP['agendados'];
} catch (Throwable $e) {}

function prioBadge(int $p): string {
    [$lbl, $bg, $color] = $p >= 700
        ? ['Alta',  '#fee2e2', '#dc2626']
        : ($p >= 350 ? ['Media', '#fef3c7', '#d97706'] : ['Baja', '#d1fae5', '#16a34a']);
    return "<span style='display:inline-flex;flex-direction:column;align-items:center;"
         . "background:{$bg};color:{$color};padding:3px 10px;border-radius:10px;"
         . "font-weight:700;line-height:1.3'>"
         . "<span style='font-size:10px'>{$lbl}</span>"
         . "<span style='font-size:13px'>{$p}</span>"
         . "</span>";
}

$paginaActual = 'juicios';
require __DIR__ . '/../../config/menu.php';
?>
<div class="ph">
  <div>
    <h1>📋 Autos de Apertura</h1>
    <div class="bc"><?= $total ?> registros · ordenados por prioridad</div>
  </div>
  <div style="display:flex;gap:6px;flex-wrap:wrap">
    <?php if (perm('autos', 'agregar')): ?>
      <a href="crearAuto.php" class="btn btn-s">➕ Nuevo AA</a>
    <?php endif; ?>
    <a href="?<?= http_build_query(array_merge($_GET, ['export' => 'csv', 'page' => 1])) ?>" class="btn btn-g">↓ CSV</a>
  </div>
</div>


<!-- ── Panel colapsable: Resumen + PP ──────────────────────────────────── -->
<details id="panel-pp" class="card" open>
  <summary style="list-style:none;cursor:pointer;display:flex;align-items:center;
                  justify-content:space-between;user-select:none;padding:2px 0">
    <span style="font-weight:600;font-size:13px;color:#1e293b">
      Resumen &amp; Prisiones Preventivas Prolongadas
    </span>
    <span class="pp-chev" style="font-size:12px;color:#94a3b8">▲ Contraer</span>
  </summary>

  <div style="display:flex;gap:12px;flex-wrap:wrap;margin-top:14px;margin-bottom:14px">
    <div class="sc" style="flex:1;min-width:150px;border-left:4px solid #1e40af">
      <div class="v" style="color:#1e40af"><?= $kpiPP['total_activos'] ?></div>
      <div class="l">Total sin juicio realizado</div>
    </div>
    <a href="listarAutos.php?f_sin_agendar=0" style="text-decoration:none;flex:1;min-width:150px">
      <div class="sc" style="border-left:4px solid #7c3aed;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(124,58,237,.2)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#7c3aed"><?= $kpiPP['agendados'] ?></div>
        <div class="l">Agendados</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver todos →</div>
      </div>
    </a>
    <a href="listarAutos.php?f_sin_agendar=1" style="text-decoration:none;flex:1;min-width:150px">
      <div class="sc" style="border-left:4px solid #0891b2;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(8,145,178,.2)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#0891b2"><?= $kpiPP['sin_agendar'] ?></div>
        <div class="l">Sin agendar</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver todos →</div>
      </div>
    </a>
  </div>

  <hr style="border:0;border-top:1px solid #e2e8f0;margin:0 0 12px">

  <p style="font-size:12px;color:#64748b;margin:0 0 12px">
    Imputados presos sin juicio realizado ni debate en curso, por duración de la detención.
  </p>
  <div style="display:flex;gap:12px;flex-wrap:wrap">
    <a href="<?= BASE_URL ?>/public/informes/informe.php?tipo=pp_3y" target="_blank"
       style="text-decoration:none;flex:1;min-width:140px">
      <div class="sc" style="border-left:4px solid #dc2626;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(220,38,38,.25)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#dc2626"><?= $kpiPP['pp_3y'] ?></div>
        <div class="l">PP &gt; 3 años</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver informe →</div>
      </div>
    </a>
    <a href="<?= BASE_URL ?>/public/informes/informe.php?tipo=pp_2y6m" target="_blank"
       style="text-decoration:none;flex:1;min-width:140px">
      <div class="sc" style="border-left:4px solid #d97706;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(217,119,6,.25)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#d97706"><?= $kpiPP['pp_2y6m'] ?></div>
        <div class="l">PP 2½–3 años</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver informe →</div>
      </div>
    </a>
    <a href="<?= BASE_URL ?>/public/informes/informe.php?tipo=pp_2y" target="_blank"
       style="text-decoration:none;flex:1;min-width:140px">
      <div class="sc" style="border-left:4px solid #ca8a04;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(202,138,4,.25)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#ca8a04"><?= $kpiPP['pp_2y'] ?></div>
        <div class="l">PP 2–2½ años</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver informe →</div>
      </div>
    </a>
    <a href="<?= BASE_URL ?>/public/informes/informe.php?tipo=debates_curso" target="_blank"
       style="text-decoration:none;flex:1;min-width:140px">
      <div class="sc" style="border-left:4px solid #2563eb;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 4px 12px rgba(37,99,235,.25)'"
           onmouseout="this.style.boxShadow=''">
        <div class="v" style="color:#2563eb"><?= $kpiPP['debates_curso'] ?></div>
        <div class="l">Debates en curso</div>
        <div style="font-size:10px;color:#94a3b8;margin-top:4px">Ver informe →</div>
      </div>
    </a>
  </div>
</details>

<form method="GET" id="fForm" class="fb">
  <div class="fi">
    <label>Solo sin agendar</label>
    <select name="f_sin_agendar">
      <option value="1" <?= $f['sin_agendar'] === '1' ? 'selected' : '' ?>>Sí</option>
      <option value="0" <?= $f['sin_agendar'] === '0' ? 'selected' : '' ?>>Todos</option>
    </select>
  </div>
  <div class="fi">
    <label>CUIJ</label>
    <input type="text" name="f_cuij" value="<?= htmlspecialchars($f['cuij']) ?>" placeholder="Buscar…">
  </div>
  <div class="fi">
    <label>Imputado</label>
    <input type="text" name="f_imputados" value="<?= htmlspecialchars($f['imputados']) ?>">
  </div>
  <div class="fi">
    <label>Estado</label>
    <select name="f_estado">
      <option value="">Todos</option>
      <?php foreach (['En espera','Para Agendar','Programado','Agendado','Realizado','Abreviado','Cancelado'] as $e): ?>
        <option value="<?= $e ?>" <?= $f['estado'] === $e ? 'selected' : '' ?>><?= $e ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="fi">
    <label>Est. Imputado</label>
    <select name="f_estado_imp">
      <option value="">Todos</option>
      <?php foreach (['Preso','En libertad','Rebelde','Internado'] as $e): ?>
        <option value="<?= $e ?>" <?= $f['estado_imp'] === $e ? 'selected' : '' ?>><?= $e ?></option>
      <?php endforeach; ?>
    </select>
  </div>
  <div class="fi">
    <label>Fiscal</label>
    <input type="text" name="f_fiscal" value="<?= htmlspecialchars($f['fiscal']) ?>" placeholder="Apellido…">
  </div>
  <div class="fi">
    <label>Defensor</label>
    <input type="text" name="f_defensor" value="<?= htmlspecialchars($f['defensor']) ?>" placeholder="Apellido…">
  </div>
  <div class="fi">
    <label>Por página</label>
    <select name="per_page">
      <?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" id="colPickerWrap" style="position:relative;flex-basis:auto">
    <label>Columnas</label>
    <button type="button" class="btn btn-g" id="colPickerBtn"
            onclick="document.getElementById('colPickerPanel').style.display=
                     document.getElementById('colPickerPanel').style.display==='none'?'block':'none'">
      Columnas (<?= count($visCols) ?>) ▾
    </button>
    <div id="colPickerPanel" style="display:none;position:absolute;top:100%;left:0;z-index:300;
         background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:10px 14px;
         min-width:200px;max-height:340px;overflow-y:auto;
         box-shadow:0 4px 16px rgba(0,0,0,.12);margin-top:2px">
      <?php foreach ($todasCols 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="cols[]" value="<?= $c ?>"
                 <?= in_array($c, $visCols, 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('colPickerPanel').style.display='none'">Cerrar</button>
      </div>
    </div>
  </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="listarAutos.php" class="btn btn-g">Limpiar</a>
    <label style="display:flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;
                  color:#374151;white-space:nowrap;margin-left:4px"
           title="Guarda el orden y tamaño de columnas">
      <input type="checkbox" id="chk-save-prefs" <?= $savedSavePrefs ? 'checked' : '' ?>>
      Guardar preferencias ⓘ
    </label>
    <label style="display:flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;
                  color:#374151;white-space:nowrap">
      <input type="checkbox" id="chk-hscroll" <?= $savedHScroll ? 'checked' : '' ?>>
      Scroll horizontal
    </label>
  </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" <?= $savedHScroll ? 'style="overflow-x:auto"' : '' ?>>
<table id="tAutos">
  <thead><tr>
    <th style="width:24px">#</th>
    <?php foreach ($visCols as $col):
        $wStyle = isset($savedColWidths[$col])
            ? 'width:' . $savedColWidths[$col] . 'px'
            : 'width:' . ($defaultWidths[$col] ?? '8%');
    ?>
    <th data-col="<?= $col ?>" style="<?= $wStyle ?>">
      <?= ordenLink($col, $todasCols[$col], $orden, $dir) ?>
    </th>
    <?php endforeach; ?>
    <th style="width:70px">Acc.</th>
  </tr></thead>
  <tbody>
  <?php
  $n = ($page - 1) * ($todos ? 0 : $per_page) + 1;
  foreach ($autos as $aa):
    $ppUrg1 = !empty($aa['vencimiento_pp_actual'])
           && $aa['vencimiento_pp_actual'] <= $hoy60
           && $aa['estado_imputado'] === 'Preso';
  ?>
  <tr>
    <td style="color:#94a3b8;font-size:11px"><?= $n++ ?></td>
    <?php foreach ($visCols as $col): ?>
    <td data-col="<?= $col ?>"<?= in_array($col, ['imputados','delitos','jueces_intervinientes','fiscales','defensores','querellantes'], true) ? ' style="white-space:normal"' : '' ?>>
    <?php switch ($col) {
      case 'prioridad':
        echo prioBadge((int)$aa['prioridad']); break;
      case 'cuij_principal':
        echo '<strong>' . htmlspecialchars($aa['cuij_principal'] ?? '') . '</strong>'; break;
      case 'estado_imputado':
        echo badgeEstadoImp($aa['estado_imputado'] ?? ''); break;
      case 'fecha_auto_apertura': case 'fecha_ingreso_agenda':
        echo fmtFecha($aa[$col]); break;
      case 'vencimiento_pp_actual':
        if (!empty($aa[$col])) {
            echo '<span style="' . ($ppUrg1 ? 'color:#dc2626;font-weight:700' : '') . '">'
               . fmtFecha($aa[$col]) . ($ppUrg1 ? ' ⚠️' : '') . '</span>';
        } else { echo '—'; } break;
      case 'dias_pp':
        if ($aa[$col] !== null) {
            $v = (int)$aa[$col];
            $c = $v < 0 ? '#dc2626' : ($v < 30 ? '#d97706' : '#16a34a');
            echo "<span style='color:{$c};font-weight:" . ($v < 60 ? '700' : '400') . "'>{$v}d</span>";
        } else { echo '—'; } break;
      case 'dias_aa':
        echo $aa[$col] !== null ? (int)$aa[$col] . 'd' : '—'; break;
      case 'estado':
        $ec = ['Para Agendar'=>'#2563eb','Programado'=>'#7c3aed','Agendado'=>'#0891b2',
               'Realizado'=>'#16a34a','Cancelado'=>'#dc2626','En espera'=>'#d97706','Abreviado'=>'#64748b'];
        $c = $ec[$aa[$col]] ?? '#64748b';
        echo "<span style='background:{$c}20;color:{$c};padding:1px 7px;border-radius:10px;"
           . "font-size:11px;font-weight:700'>" . htmlspecialchars($aa[$col] ?? '—') . "</span>";
        break;
      case 'juez_aa':
        echo htmlspecialchars($aa['juez_aa'] ?? '—'); break;
      case 'jueces_intervinientes': case 'fiscales': case 'defensores': case 'querellantes':
        echo celdaLitigantes($aa[$col]); break;
      default:
        echo htmlspecialchars($aa[$col] ?? '—');
    } ?>
    </td>
    <?php endforeach; ?>
    <td class="ac">
      <a href="verAuto.php?id=<?= $aa['id'] ?>" class="btn btn-i btn-sm">Ver</a>
      <?php if (perm('autos', 'editar')): ?>
        <a href="editarAuto.php?id=<?= $aa['id'] ?>" class="btn btn-w btn-sm">✏️</a>
      <?php endif; ?>
      <a href="../agendamientos/crearAgendamiento.php?aa_id=<?= $aa['id'] ?>"
         class="btn btn-s btn-sm" title="Agendar">📅</a>
    </td>
  </tr>
  <?php endforeach; ?>
  <?php if (empty($autos)): ?>
    <tr><td colspan="<?= count($visCols) + 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>
(function(){
  const PREF_KEY = 'layout_autos';
  const RZONE    = 10;
  const table    = document.getElementById('tAutos');
  const COL_FIJA = 'cuij_principal';
  if (!table) return;

  // Aplicar anchos guardados, luego congelar todo en px
  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 => {
    th.style.width = th.offsetWidth + 'px';
  });
  table.style.tableLayout = 'fixed';

  // ── Resize por delegación ────────────────────────────────────────────────
  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 colIdx = Array.from(cell.parentElement.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 columnas configurables ───────────────────────
  let dragFrom = null;
  const getDataCols = () => Array.from(table.querySelectorAll('th[data-col]'));

  getDataCols().forEach(th => {
    if (th.dataset.col === COL_FIJA) return;
    th.draggable = true;
    th.addEventListener('dragstart', e => {
      if (_nearRight) { e.preventDefault(); return; }
      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();
    });
  });

  // ── 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 ─────────────────────────────────────────────────
  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 !== COL_FIJA) 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'});
  });
})();

// ── Panel PP: persistir estado abierto/cerrado ───────────────────────────
(function(){
  const panel = document.getElementById('panel-pp');
  const chev  = panel?.querySelector('.pp-chev');
  if (!panel) return;
  if (localStorage.getItem('panel-pp-open') === '0') {
    panel.removeAttribute('open');
    if (chev) chev.textContent = '▼ Expandir';
  }
  panel.addEventListener('toggle', () => {
    localStorage.setItem('panel-pp-open', panel.open ? '1' : '0');
    if (chev) chev.textContent = panel.open ? '▲ Contraer' : '▼ Expandir';
  });
})();

// ── Auto-submit filtros ──────────────────────────────────────────────────
(function(){
  const f = document.getElementById('fForm');
  f.querySelectorAll('select').forEach(el =>
    el.addEventListener('change', () => f.submit())
  );
  f.querySelectorAll('input[type=text], input[type=date], input[type=number]').forEach(el => {
    el.addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); f.submit(); } });
    el.addEventListener('blur', () => f.submit());
  });
})();

// ── Cerrar col picker al clic afuera ────────────────────────────────────
document.addEventListener('click', function(e) {
  const w = document.getElementById('colPickerWrap');
  if (w && !w.contains(e.target)) document.getElementById('colPickerPanel').style.display = 'none';
});
</script>
