<?php
declare(strict_types=1);
$authApp = 'juicios';
session_start();
require __DIR__ . '/../../config/auth.php';
require dirname(__DIR__, 5) . '/config/db2.php';
require __DIR__ . '/../../lib/helpers.php';

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

$MESES = ['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];

$errDash = null;
$kpi = ['pp_3y'=>0, 'pp_2y6m'=>0, 'pp_2y'=>0, 'debates_curso'=>0];
$porMes = [];

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
          )
    ";

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

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

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

    $kpi['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();

    $anioActual  = (int)date('Y');
    $anioProximo = $anioActual + 1;
    $stmt = $pdo->query("
        SELECT DATE_FORMAT(ag.debate_desde, '%Y-%m') AS mes, COUNT(*) AS cant
        FROM agj_agendamientos ag
        WHERE ag.deleted_at IS NULL
          AND ag.estado NOT IN ('Cancelado')
          AND ag.debate_desde >= DATE_FORMAT(CURDATE(), '%Y-%m-01')
          AND ag.debate_desde < '$anioProximo-12-31'
        GROUP BY mes ORDER BY mes
    ");
    $rawMes = [];
    foreach ($stmt->fetchAll() as $r) {
        $rawMes[$r['mes']] = (int)$r['cant'];
    }

    $mesActual = (int)date('m');
    for ($m = $mesActual; $m <= 12; $m++) {
        $key = $anioActual . '-' . str_pad((string)$m, 2, '0', STR_PAD_LEFT);
        $porMes[$anioActual][$key] = $rawMes[$key] ?? 0;
    }
    for ($m = 1; $m <= 12; $m++) {
        $key = $anioProximo . '-' . str_pad((string)$m, 2, '0', STR_PAD_LEFT);
        $porMes[$anioProximo][$key] = $rawMes[$key] ?? 0;
    }

} catch (PDOException $e) {
    $errDash = $e->getMessage();
}

$urlInforme = BASE_URL . '/public/informes/informe.php';
?>

<div class="ph">
  <div>
    <h1>Tablero de Control de Juicios</h1>
    <div class="bc">OGJ Rosario · <?=date('d/m/Y')?></div>
  </div>
</div>

<?php if ($errDash): ?>
<div class="msg msg-err">⚠ Error al cargar el tablero: <?=htmlspecialchars($errDash)?></div>
<?php endif; ?>

<div class="card">
  <div class="sec">Prisiones Preventivas Prolongadas</div>
  <p style="font-size:12px;color:#64748b;margin-bottom:12px">
    Imputados presos sin juicio realizado ni debate en curso, clasificados por duración de la detención.
  </p>
  <div style="display:flex;gap:12px;flex-wrap:wrap">

    <a href="<?=$urlInforme?>?tipo=pp_3y" target="_blank" style="text-decoration:none;flex:1;min-width:160px">
      <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"><?=$kpi['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="<?=$urlInforme?>?tipo=pp_2y6m" target="_blank" style="text-decoration:none;flex:1;min-width:160px">
      <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"><?=$kpi['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="<?=$urlInforme?>?tipo=pp_2y" target="_blank" style="text-decoration:none;flex:1;min-width:160px">
      <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"><?=$kpi['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="<?=$urlInforme?>?tipo=debates_curso" target="_blank" style="text-decoration:none;flex:1;min-width:160px">
      <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"><?=$kpi['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>
</div>

<?php foreach ($porMes as $anio => $meses): ?>
<div class="card">
  <div class="sec">Agenda <?=$anio?></div>
  <div style="display:flex;gap:8px;flex-wrap:wrap">
    <?php foreach ($meses as $mesKey => $cant): ?>
    <?php
    $mn  = (int)substr($mesKey, 5, 2);
    $lbl = $MESES[$mn - 1] ?? '?';
    $esHoy = $mesKey === date('Y-m');
    $color = $cant > 0 ? '#2563eb' : '#94a3b8';
    $bg    = $esHoy ? '#dbeafe' : ($cant > 0 ? '#f0f4ff' : '#f8fafc');
    $border= $esHoy ? '2px solid #2563eb' : '1px solid #e2e8f0';
    ?>
    <a href="<?=$urlInforme?>?tipo=debates_mes&mes=<?=$mesKey?>" target="_blank"
       style="text-decoration:none;min-width:80px;flex:1 1 80px">
      <div style="background:<?=$bg?>;border:<?=$border?>;border-radius:8px;padding:10px 12px;
                  text-align:center;cursor:pointer;transition:box-shadow .15s"
           onmouseover="this.style.boxShadow='0 3px 10px rgba(37,99,235,.2)'"
           onmouseout="this.style.boxShadow=''">
        <div style="font-size:11px;font-weight:700;color:#475569;margin-bottom:4px;text-transform:uppercase">
          <?=$lbl?>
        </div>
        <div style="font-size:22px;font-weight:700;color:<?=$color?>">
          <?=$cant?>
        </div>
        <?php if ($cant > 0): ?>
        <div style="font-size:10px;color:#94a3b8;margin-top:2px">debate<?=$cant===1?'':'s'?></div>
        <?php endif; ?>
      </div>
    </a>
    <?php endforeach; ?>
  </div>
</div>
<?php endforeach; ?>

<div class="card">
  <div class="sec">Accesos rápidos</div>
  <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center">
    <a href="<?=BASE_URL?>/public/autos/crearAuto.php"                  class="btn btn-s">Nuevo AA</a>
    <a href="<?=BASE_URL?>/public/autos/listarAutos.php"                 class="btn btn-g">Autos de Apertura</a>
    <a href="<?=BASE_URL?>/public/agendamientos/crearAgendamiento.php"   class="btn btn-p">Agendar juicio</a>
    <a href="<?=BASE_URL?>/public/agendamientos/listarAgenda.php"        class="btn btn-i">Agenda</a>
    <a href="<?=BASE_URL?>/public/gantt/gantt.php"                       class="btn btn-w">Gantt</a>
    <a href="<?=BASE_URL?>/public/juicios/importarAgenda.php"            class="btn btn-g">Importar agenda</a>
    <button id="btn-recalc" class="btn btn-w"
            onclick="recalcularPrioridades()"
            title="Recalcula la prioridad de todos los AAs pendientes de realización">
      ↻ Recalcular prioridades
    </button>
    <span id="recalc-msg" style="font-size:12px;color:#475569"></span>
  </div>
</div>

<script>
function recalcularPrioridades() {
  var btn = document.getElementById('btn-recalc');
  var msg = document.getElementById('recalc-msg');
  btn.disabled = true;
  btn.textContent = 'Calculando…';
  msg.textContent = '';
  fetch('<?=BASE_URL?>/public/autos/ajax_recalc_all.php', {method:'POST'})
    .then(function(r){ return r.json(); })
    .then(function(d){
      btn.textContent = '↻ Recalcular prioridades';
      btn.disabled = false;
      msg.textContent = '✓ ' + d.actualizados + ' AAs actualizados';
      setTimeout(function(){ msg.textContent = ''; }, 4000);
    })
    .catch(function(){
      btn.textContent = '↻ Recalcular prioridades';
      btn.disabled = false;
      msg.textContent = '✗ Error al recalcular';
    });
}
</script>

</div></body></html>
