<?php
$paginaActual = $paginaActual ?? '';
if (!defined('BASE_URL')) {
    $proto = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $script = str_replace('\\', '/', $_SERVER['SCRIPT_NAME']);
    $pos    = strpos($script, '/agendaJuicios');
    $base   = $pos !== false ? substr($script, 0, $pos) . '/agendaJuicios' : '/agendaJuicios';
    define('BASE_URL', $proto . '://' . $_SERVER['HTTP_HOST'] . $base);
}
$nav = [
    ['id'=>'inicio',            'url'=> BASE_URL.'/index.php',                          'ico'=>'🏠', 'lbl'=>'Inicio'],
    ['id'=>'agenda_audiencias', 'url'=> '/mrbs/web',                                    'ico'=>'📅', 'lbl'=>'Agenda Audiencias', 'submenu'=>[
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web',                                'lbl'=>'Vista por Salas',           'title'=>'Vista horizontal diaria por Grupo de Salas'],
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web/grilla.php',                     'lbl'=>'Grilla',                    'title'=>'Grilla diaria de Audiencias'],
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web/grilla.php',                     'lbl'=>'Jueces de Turno y Carga',   'title'=>'Jueces de Turno, licencias y carga diaria de Audiencias'],
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web/consultaAudiencias.php',         'lbl'=>'Consultas',                 'title'=>'Consulta de audiencias por diferentes Filtros'],
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web/DiaJuez.php',                    'lbl'=>'Juez x Día',                'title'=>'Ocupación Juez-Hora-Dia'],
        ['id'=>'agenda_audiencias', 'url'=>'/mrbs/web/consultaDetenidos.php',          'lbl'=>'Detenidos',                 'title'=>'Consulta Alojamiento Detenidos'],
    ]],
    ['id'=>'juicios',           'url'=> BASE_URL.'/public/juicios/tablero.php',         'ico'=>'⚖️', 'lbl'=>'Juicios', 'submenu'=>[
        ['id'=>'juicios', 'url'=> BASE_URL.'/public/juicios/tablero.php',               'lbl'=>'Tablero de Juicios'],
        ['id'=>'juicios', 'url'=> BASE_URL.'/public/autos/listarAutos.php',             'lbl'=>'Autos de Apertura'],
        ['id'=>'juicios', 'url'=> BASE_URL.'/public/agendamientos/listarAgenda.php',    'lbl'=>'Agenda de Juicios'],
        ['id'=>'juicios', 'url'=> BASE_URL.'/public/gantt/gantt.php',                   'lbl'=>'Gantt'],
    ]],
    ['id'=>'litigantes',        'url'=> BASE_URL.'/public/litigantes/listarJueces.php', 'ico'=>'👥', 'lbl'=>'Litigantes', 'submenu'=>[
        ['id'=>'litigantes', 'url'=> BASE_URL.'/public/litigantes/listarJueces.php',             'lbl'=>'Jueces'],
        ['id'=>'litigantes', 'url'=> BASE_URL.'/public/litigantes/listarFiscales.php',           'lbl'=>'Fiscales'],
        ['id'=>'litigantes', 'url'=> BASE_URL.'/public/litigantes/listarDefensoresPublicos.php', 'lbl'=>'Defensores'],
        ['id'=>'litigantes', 'url'=> BASE_URL.'/public/litigantes/listarJuezRol.php',            'lbl'=>'Autoridades'],
    ]],
    ['id'=>'configuracion',     'url'=> BASE_URL.'/public/configuracion/listarSalas.php','ico'=>'⚙️', 'lbl'=>'Configuración', 'submenu'=>[
        ['id'=>'configuracion', 'url'=> BASE_URL.'/public/configuracion/listarSalas.php',          'lbl'=>'Salas'],
        ['id'=>'configuracion', 'url'=> BASE_URL.'/public/configuracion/listarTiposAudiencia.php', 'lbl'=>'Tipos de Audiencia'],
        ['id'=>'configuracion', 'url'=> BASE_URL.'/public/configuracion/listarUsuarios.php',       'lbl'=>'Usuarios'],
        ['id'=>'configuracion', 'url'=> BASE_URL.'/public/configuracion/listarUserApp.php',        'lbl'=>'Permisos de Aplicación'],
        ['id'=>'configuracion', 'url'=> BASE_URL.'/public/configuracion/listarRolesJuez.php',      'lbl'=>'Roles Juez'],
    ]],
];
?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Agenda Juicios · OGJ Rosario</title>
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
body{font-family:Arial,sans-serif;background:#f0f2f5;display:flex;min-height:100vh;font-size:14px;color:#1e293b}
/* Sidebar */
.sb{width:5px;min-height:100vh;background:#1e293b;display:flex;flex-direction:column;flex-shrink:0;position:fixed;top:0;left:0;bottom:0;z-index:100;overflow:hidden;transition:width .22s ease;cursor:e-resize;border-right:2px solid #2563eb}
.sb:hover{width:210px;cursor:default;border-right-color:transparent}
.sb-brand{background:#0f172a;padding:16px 14px;border-bottom:1px solid #334155;white-space:nowrap;min-width:210px}
.sb-brand .t1{font-size:15px;font-weight:700;color:#f1f5f9}
.sb-brand .t2{font-size:11px;color:#64748b;margin-top:2px}
.sb nav{flex:1;padding:10px 0;min-width:210px}
.sb nav a{display:flex;align-items:center;gap:10px;padding:10px 14px;color:#94a3b8;text-decoration:none;font-size:13px;border-left:3px solid transparent;transition:background .12s,color .12s;white-space:nowrap}
.sb nav a:hover{background:#334155;color:#f1f5f9}
.sb nav a.on{background:#1e40af;color:#fff;border-left-color:#60a5fa}
.sb-foot{padding:12px 14px;border-top:1px solid #334155;font-size:12px;color:#64748b;white-space:nowrap;min-width:210px}
.sb-foot .usr{color:#94a3b8;font-weight:600;margin-bottom:5px}
.sb-foot a{color:#ef4444;text-decoration:none;font-weight:700}
/* Main */
.main{margin-left:8px;flex:1;padding:20px;min-width:0}
/* Layout helpers */
.ph{display:flex;align-items:flex-start;justify-content:space-between;margin-bottom:16px;gap:10px;flex-wrap:wrap}
.ph h1{font-size:20px;font-weight:700}
.bc{font-size:12px;color:#64748b;margin-top:3px}
.bc a{color:#2563eb;text-decoration:none}
.card{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:16px;margin-bottom:12px}
.sec{font-size:14px;font-weight:700;color:#334155;margin-bottom:12px;padding-bottom:6px;border-bottom:2px solid #e2e8f0}
.sr{display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap}
.sc{background:#fff;border:1px solid #e2e8f0;border-radius:8px;padding:12px 16px;flex:1;min-width:120px}
.sc .v{font-size:24px;font-weight:700;color:#2563eb}
.sc .l{font-size:11px;color:#64748b;margin-top:2px}
/* Filtros */
.fb{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:14px;margin-bottom:12px;display:flex;flex-wrap:wrap;gap:10px}
.fi{flex:1 1 150px}
.fi label{display:block;font-weight:bold;font-size:12px;margin-bottom:3px;color:#475569}
.fi input,.fi select,.fi textarea{width:100%;padding:6px 8px;border:1px solid #d1d5db;border-radius:5px;font-size:13px;background:#fff}
.fi input:focus,.fi select:focus{outline:2px solid #2563eb}
/* Botones */
.btn{display:inline-block;padding:6px 14px;border:none;border-radius:5px;cursor:pointer;font-size:13px;font-weight:600;text-decoration:none;transition:opacity .12s;white-space:nowrap}
.btn:hover{opacity:.85}
.btn-p{background:#2563eb;color:#fff}
.btn-s{background:#16a34a;color:#fff}
.btn-g{background:#64748b;color:#fff}
.btn-i{background:#0891b2;color:#fff}
.btn-w{background:#d97706;color:#fff}
.btn-r{background:#dc2626;color:#fff}
.btn-sm{padding:3px 8px;font-size:12px}
/* Tabla */
.tw{background:#fff;border:1px solid #e2e8f0;border-radius:8px;overflow:auto;margin-bottom:8px}
table{width:100%;border-collapse:collapse;table-layout:fixed}
th,td{border:1px solid #e2e8f0;padding:7px 9px;text-align:left;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
th{background:#1e293b;color:#fff;font-size:11px;text-transform:uppercase;letter-spacing:.04em}
th a{color:#fff;text-decoration:none}
tr:nth-child(even){background:#f8fafc}
tr:hover{background:#dbeafe}
td.w{white-space:normal;word-break:break-word}
.ac{display:flex;gap:3px;flex-wrap:wrap;white-space:normal;overflow:visible}
/* Badges */
.bp{display:inline-block;padding:1px 7px;border-radius:10px;font-size:11px;font-weight:600}
.bp-p{background:#fee2e2;color:#991b1b} /* preso */
.bp-l{background:#d1fae5;color:#166534} /* libre */
.bp-r{background:#fef3c7;color:#92400e} /* rebelde */
.bp-i{background:#e0e7ff;color:#3730a3} /* internado */
.bj{display:inline-block;padding:1px 7px;border-radius:10px;font-size:11px;font-weight:600}
.bj-t{background:#dbeafe;color:#1e40af} /* titular */
.bj-s{background:#fef3c7;color:#92400e} /* sobre-agendado */
/* Mensajes */
.msg{padding:9px 14px;margin-bottom:12px;border-radius:5px;font-size:13px}
.msg-ok{background:#d1fae5;color:#065f46;border:1px solid #6ee7b7}
.msg-err{background:#fee2e2;color:#991b1b;border:1px solid #fca5a5}
/* Top bar */
.topbar{display:flex;align-items:center;justify-content:flex-end;gap:10px;background:#fff;border-bottom:1px solid #e2e8f0;padding:6px 16px;margin:-20px -20px 16px -20px;font-size:13px;color:#475569}
.topbar .tb-user{font-weight:600;color:#1e293b}
.topbar a.tb-out{color:#ef4444;text-decoration:none;font-weight:600}
.topbar a.tb-out:hover{text-decoration:underline}
.topbar a.tb-in{color:#2563eb;text-decoration:none;font-weight:600}
.topbar a.tb-in:hover{text-decoration:underline}
/* Paginación */
.pg{display:flex;align-items:center;gap:4px;padding:8px 0;flex-wrap:wrap}
.pg button{padding:4px 10px;border:1px solid #d1d5db;border-radius:5px;cursor:pointer;background:#fff;font-size:13px}
.pg button:hover{background:#e2e8f0}
.pg button.on{background:#2563eb;color:#fff;border-color:#2563eb}
.pg button:disabled{opacity:.4;cursor:not-allowed}
.pgi{font-size:13px;color:#64748b;margin-left:auto}
/* Form grid */
.fg{display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:12px;margin-bottom:16px}
.ff label{display:block;font-weight:bold;font-size:12px;margin-bottom:3px;color:#475569}
.ff input,.ff select,.ff textarea{width:100%;padding:7px 9px;border:1px solid #d1d5db;border-radius:5px;font-size:13px}
.ff input:focus,.ff select:focus{outline:2px solid #2563eb}
/* Span 2/3 */
.sp2{grid-column:span 2}
.sp3{grid-column:span 3}
</style>
<script>
(function(){
  function toDisplay(v){
    if(!v||!/^\d{4}-\d{2}-\d{2}$/.test(v))return '';
    var p=v.split('-');return p[2]+'/'+p[1]+'/'+p[0];
  }
  function toISO(v){
    var m=v&&v.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
    return m?m[3]+'-'+m[2].padStart(2,'0')+'-'+m[1].padStart(2,'0'):'';
  }
  function initDP(inp){
    if(inp.dataset.dpDone)return;
    inp.dataset.dpDone='1';

    var wrap=document.createElement('div');
    wrap.style.cssText='display:flex;align-items:stretch;width:100%';

    var txt=document.createElement('input');
    txt.type='text';
    txt.placeholder='dd/mm/yyyy';
    txt.value=toDisplay(inp.value);
    txt.style.cssText='flex:1;min-width:0;padding:7px 9px;border:1px solid #d1d5db;'+
      'border-radius:5px 0 0 5px;font-size:13px;background:#fff';

    var btn=document.createElement('button');
    btn.type='button';btn.textContent='📅';btn.title='Elegir fecha';
    btn.style.cssText='border:1px solid #d1d5db;border-left:none;border-radius:0 5px 5px 0;'+
      'background:#f8fafc;padding:0 8px;cursor:pointer;font-size:12px;flex-shrink:0';
    btn.addEventListener('click',function(){try{inp.showPicker();}catch(e){}});

    // texto → input hidden
    txt.addEventListener('change',function(){
      inp.value=toISO(txt.value)||'';
      inp.dispatchEvent(new Event('change',{bubbles:true}));
    });
    // normalizar al salir del campo
    txt.addEventListener('blur',function(){
      var iso=toISO(txt.value);
      if(iso)txt.value=toDisplay(iso);
    });
    // picker nativo → texto
    inp.addEventListener('change',function(){
      txt.value=toDisplay(inp.value);
    });

    // ocultar input original (se mantiene en el DOM para envío y JS existente)
    inp.style.cssText='position:absolute;width:1px;height:1px;opacity:0;'+
      'pointer-events:none;padding:0;border:0;overflow:hidden';
    inp.removeAttribute('required');

    inp.parentNode.insertBefore(wrap,inp);
    wrap.appendChild(txt);
    wrap.appendChild(btn);
    wrap.appendChild(inp);
  }

  document.addEventListener('DOMContentLoaded',function(){
    document.querySelectorAll('input[type="date"]').forEach(initDP);
  });
})();
</script>
</head>
<body>
<div class="sb">
  <div class="sb-brand"><div class="t1">⚖️ Agenda Juicios</div><div class="t2">OGJ · Rosario</div></div>
  <nav>
    <?php foreach($nav as $m): ?>
      <?php if (!empty($m['submenu'])): ?>
        <a href="<?=$m['url']?>" class="<?=$paginaActual===$m['id']?'on':''?>" style="justify-content:space-between">
          <span style="display:flex;align-items:center;gap:10px"><span><?=$m['ico']?></span><?=$m['lbl']?></span>
        </a>
        <?php foreach($m['submenu'] as $sub): ?>
          <a href="<?=$sub['url']?>" class="<?=$paginaActual===$m['id']?'on':''?>" style="padding-left:32px;font-size:12px"
             <?= isset($sub['title']) ? 'title="'.htmlspecialchars($sub['title']).'"' : '' ?>>
            › <?=$sub['lbl']?>
          </a>
        <?php endforeach; ?>
      <?php else: ?>
        <a href="<?=$m['url']?>" class="<?=$paginaActual===$m['id']?'on':''?>">
          <span><?=$m['ico']?></span> <?=$m['lbl']?>
        </a>
      <?php endif; ?>
    <?php endforeach; ?>
  </nav>
  <div class="sb-foot">
    <div class="usr">👤 <?=htmlspecialchars($_SESSION['userDisplay'] ?? $_SESSION['usuario'])?></div>
    <a href="../../logout.php">🚪 Cerrar sesión</a>
  </div>
</div>
<div class="main">
<div class="topbar">
  <?php if (isset($_SESSION['usuario'])): ?>
    <span class="tb-user">👤 <?=htmlspecialchars($_SESSION['userDisplay'] ?? $_SESSION['usuario'])?></span>
    <a href="<?=BASE_URL?>/logout.php" class="tb-out">Salir</a>
  <?php else: ?>
    <span style="color:#94a3b8">Usuario anónimo</span>
    <a href="<?=BASE_URL?>/login.php" class="tb-in">Iniciar sesión</a>
  <?php endif; ?>
</div>
