<?php
require_once 'includes/auth.php';
exigir_rol('propietario');
require_once 'conexion.php';
require_once 'includes/departamentos.php';
require_once 'includes/layout.php';

$id_usuario = $_SESSION['id_usuario'];

$prop = departamento_de_usuario($conn, $id_usuario);
if (!$prop) die('Propietario no encontrado');

$inPropietarios = sql_in_propietarios(
    ids_propietarios_departamento($conn, $prop['numero_departamento'])
);

$stats = $conn->query("
    SELECT
        COUNT(*) total,
        SUM(CASE WHEN CURDATE() BETWEEN fecha_inicio AND fecha_salida THEN 1 ELSE 0 END) activos,
        SUM(CASE WHEN CURDATE() < fecha_inicio THEN 1 ELSE 0 END) pendientes,
        SUM(CASE WHEN CURDATE() > fecha_salida THEN 1 ELSE 0 END) finalizados
    FROM arrendatarios WHERE id_propietario IN ($inPropietarios)")->fetch_assoc();

page_header('Calendario de Arriendos', 'calendario');
?>

<div class="row g-3 mb-4">
  <?php
  $cards = [
      ['Total',       (int)$stats['total'],       'bg-info-grad',      'bi-collection'],
      ['En Arriendo', (int)$stats['activos'],     'bg-success-grad',   'bi-house-check'],
      ['Pendientes',  (int)$stats['pendientes'],  'bg-warning-grad',   'bi-hourglass-split'],
      ['Finalizados', (int)$stats['finalizados'], 'bg-secondary-grad', 'bi-check2-circle'],
  ];
  foreach ($cards as $c): ?>
  <div class="col-6 col-lg-3">
    <div class="stat-card" style="cursor:default">
      <div class="stat-icon <?= $c[2] ?>"><i class="bi <?= $c[3] ?>"></i></div>
      <div class="stat-info"><h3><?= $c[1] ?></h3><span><?= $c[0] ?></span></div>
    </div>
  </div>
  <?php endforeach; ?>
</div>

<div class="card">
  <div class="card-header">
    <i class="bi bi-calendar3 me-2 text-primary"></i> Calendario
    <span class="ms-3" style="font-size:12px">
      <span class="badge" style="background:#198754">En arriendo</span>
      <span class="badge text-dark" style="background:#ffc107">Pendiente</span>
      <span class="badge" style="background:#6c757d">Finalizado</span>
    </span>
  </div>
  <div class="card-body" style="overflow:visible">
    <div id="calendario" style="min-height:680px"></div>
  </div>
</div>

<?php
$js = <<<'JS'
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@6.1.11/index.global.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
  const calendar = new FullCalendar.Calendar(document.getElementById('calendario'), {
    locale: 'es',
    initialView: 'dayGridMonth',
    height: 660,
    headerToolbar: { left: 'prev,next today', center: 'title', right: 'dayGridMonth,listMonth' },
    buttonText: { today: 'Hoy', month: 'Mes', list: 'Lista' },
    events: 'eventos_calendario.php',
    eventDisplay: 'block'
  });
  calendar.render();
});
</script>
JS;
page_footer($js);
