<?php
session_start();

/* ===============================
   SEGURIDAD
================================ */
if (!isset($_SESSION['rol'], $_SESSION['id_usuario']) || $_SESSION['rol'] !== 'propietario') {
    header("Location: login.php?mensaje=no_autorizado");
    exit;
}

define('TIEMPO_INACTIVIDAD', 900);
if (isset($_SESSION['ultimo_acceso']) && (time() - $_SESSION['ultimo_acceso']) > TIEMPO_INACTIVIDAD) {
    session_unset();
    session_destroy();
    header("Location: login.php?mensaje=inactividad");
    exit;
}
$_SESSION['ultimo_acceso'] = time();

/* ===============================
   BD
================================ */
require_once 'conexion.php';
$id_usuario = $_SESSION['id_usuario'];

/* ===============================
   PROPIETARIO
================================ */
$stmt = $conn->prepare("
    SELECT id_propietario, numero_departamento, estacionamiento
    FROM propietarios
    WHERE id_usuario = ?
");
$stmt->bind_param("i", $id_usuario);
$stmt->execute();
$prop = $stmt->get_result()->fetch_assoc();
if (!$prop) die("Propietario no encontrado");

$id_propietario = $prop['id_propietario'];

/* ===============================
   ARRENDATARIOS
================================ */
$stmt = $conn->prepare("
SELECT 
    a.*,
    DATEDIFF(a.fecha_salida, a.fecha_inicio) AS dias_totales,
    CASE
        WHEN CURDATE() BETWEEN a.fecha_inicio AND a.fecha_salida THEN 'En Arriendo'
        WHEN CURDATE() < a.fecha_inicio THEN 'Pendiente'
        ELSE 'Finalizado'
    END AS estado,
    CASE
        WHEN CURDATE() BETWEEN a.fecha_inicio AND a.fecha_salida THEN 1
        WHEN CURDATE() < a.fecha_inicio THEN 2
        ELSE 3
    END AS prioridad
FROM arrendatarios a
WHERE a.id_propietario = ?
ORDER BY prioridad, a.fecha_inicio
");
$stmt->bind_param("i", $id_propietario);
$stmt->execute();
$result = $stmt->get_result();

/* ===============================
   CONTADORES
================================ */
$rows = [];
$total = $vigentes = $pendientes = $finalizados = 0;

while ($r = $result->fetch_assoc()) {
    $rows[] = $r;
    $total++;
    if ($r['estado'] === 'En Arriendo') $vigentes++;
    if ($r['estado'] === 'Pendiente') $pendientes++;
    if ($r['estado'] === 'Finalizado') $finalizados++;
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Dashboard Propietario</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600&display=fallback">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/css/adminlte.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/datatables.net-bs4/css/dataTables.bootstrap4.min.css">
</head>

<body class="hold-transition sidebar-mini sidebar-collapse">
<div class="wrapper">

<!-- NAVBAR -->
<nav class="main-header navbar navbar-expand navbar-white navbar-light">
  <ul class="navbar-nav">
    <li class="nav-item">
      <a class="nav-link" data-widget="pushmenu"><i class="fas fa-bars"></i></a>
    </li>
  </ul>
  <ul class="navbar-nav ml-auto">
    <li class="nav-item">
      <a href="login.php" class="nav-link">
        <i class="fas fa-sign-out-alt"></i> Salir
      </a>
    </li>
  </ul>
</nav>

<!-- SIDEBAR -->
<aside class="main-sidebar sidebar-dark-primary elevation-4">
  <a class="brand-link text-center">
    <span class="brand-text font-weight-light">Sistema Arriendos</span>
  </a>
  <div class="sidebar">
    <nav class="mt-2">
      <ul class="nav nav-pills nav-sidebar flex-column">
        <li class="nav-item">
          <a href="propietario_dashboard.php" class="nav-link active">
            <i class="fas fa-home nav-icon"></i><p>Dashboard</p>
          </a>
        </li>
        <li class="nav-item">
          <a href="registrar_arrendatario.php" class="nav-link">
            <i class="fas fa-user-plus nav-icon"></i><p>Nuevo Arrendatario</p>
          </a>
        </li>
        <li class="nav-item">
          <a href="calendario_dashboard.php" class="nav-link">
            <i class="fas fa-calendar nav-icon"></i><p>Calendario</p>
          </a>
        </li>
        <li class="nav-item">
          <a href="cambiar_contrasena.php" class="nav-link">
            <i class="fas fa-key nav-icon"></i><p>Contraseña</p>
          </a>
        </li>
      </ul>
    </nav>
  </div>
</aside>

<!-- CONTENT -->
<div class="content-wrapper">
<section class="content-header">
  <div class="container-fluid">
    <h1>Bienvenido <?= htmlspecialchars($_SESSION['nombre']) ?></h1>
    <p>Departamento <?= $prop['numero_departamento'] ?> | Estac. <?= $prop['estacionamiento'] ?></p>
  </div>
</section>

<section class="content">
<div class="container-fluid">

<!-- FILTROS -->
<div class="row">
<?php
$cards = [
  ['Todos', $total, 'info', ''],
  ['Vigentes', $vigentes, 'success', 'En Arriendo'],
  ['Pendientes', $pendientes, 'warning', 'Pendiente'],
  ['Finalizados', $finalizados, 'secondary', 'Finalizado']
];
foreach ($cards as $c):
?>
<div class="col-md-3">
  <div class="small-box bg-<?= $c[2] ?> filtro" data-estado="<?= $c[3] ?>" style="cursor:pointer">
    <div class="inner"><h3><?= $c[1] ?></h3><p><?= $c[0] ?></p></div>
    <div class="icon"><i class="fas fa-list"></i></div>
  </div>
</div>
<?php endforeach; ?>
</div>

<!-- TABLA -->
<div class="card card-outline card-primary">
<div class="card-body">

<table id="tablaArrendatarios" class="table table-bordered table-hover">
<thead>
<tr>
  <th>Estado</th>
  <th>Imagen</th>
  <th>Nombre</th>
  <th>RUT</th>
  <th>Fechas</th>
  <th>URL</th>
  <th>Días</th>
  <th>Acciones</th>
</tr>
</thead>
<tbody>

<?php foreach ($rows as $a): ?>
<tr>

<td>
<span class="badge badge-<?= 
  $a['estado']=='En Arriendo'?'success':
  ($a['estado']=='Pendiente'?'warning':'secondary') ?>">
<?= $a['estado'] ?>
</span>
</td>

<td class="text-center">
<?php
$img = 'uploads_arrendatarios/' . $a['imagen'];
if (!empty($a['imagen']) && file_exists($img)): ?>
  <a href="<?= $img ?>" target="_blank">
    <img src="<?= $img ?>" style="width:50px;height:50px;object-fit:cover;border-radius:6px">
  </a>
<?php else: ?> — <?php endif; ?>
</td>

<td><?= htmlspecialchars($a['nombre']) ?></td>
<td><?= htmlspecialchars($a['rut']) ?></td>

<td>
<?= date('d-m-Y',strtotime($a['fecha_inicio'])) ?> →
<?= date('d-m-Y',strtotime($a['fecha_salida'])) ?>
</td>

<td class="text-center">
<?php if (!empty($a['url_externa'])): ?>
  <a href="<?= htmlspecialchars($a['url_externa']) ?>" target="_blank"
     class="btn btn-sm btn-secondary">
     <i class="fas fa-link"></i>
  </a>
<?php else: ?> — <?php endif; ?>
</td>

<td><?= $a['dias_totales'] ?></td>

<td>
<div class="btn-group btn-group-sm">
  <a href="ver_ficha.php?token=<?= $a['token_pdf'] ?>" class="btn btn-outline-primary">
    <i class="fas fa-file-pdf"></i>
  </a>
  <a href="editar_arrendatario.php?id=<?= $a['id_arrendatario'] ?>" class="btn btn-outline-warning">
    <i class="fas fa-edit"></i>
  </a>
  <a href="eliminar_arrendatario.php?id=<?= $a['id_arrendatario'] ?>"
     onclick="return confirm('¿Eliminar este arrendatario?')"
     class="btn btn-outline-danger">
    <i class="fas fa-trash"></i>
    
  </a>
  
  <button class="btn btn-info btn-sm"
        onclick="enviarCorreoManual(<?= $a['id_arrendatario'] ?>)">
    <i class="fas fa-envelope"></i>
</button>

</div>
</td>

</tr>
<?php endforeach; ?>

</tbody>
</table>

</div>
</div>

</div>
</section>
</div>
</div>

<!-- JS -->
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/admin-lte@3.2/dist/js/adminlte.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/datatables.net-bs4/js/dataTables.bootstrap4.min.js"></script>

<script>
$(function () {
  let tabla = $('#tablaArrendatarios').DataTable({
    responsive: true,
    ordering: false,
    language: { url: '//cdn.datatables.net/plug-ins/1.13.6/i18n/es-CL.json' }
  });

  $('.filtro').click(function () {
    tabla.column(0).search($(this).data('estado')).draw();
  });
});
</script>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
function enviarCorreoManual(idArrendatario) {
    Swal.fire({
        title: 'Enviar correo',
        input: 'email',
        inputLabel: 'Email destinatario',
        inputPlaceholder: 'correo@ejemplo.cl',
        showCancelButton: true,
        confirmButtonText: 'Enviar',
        cancelButtonText: 'Cancelar',
        inputValidator: (value) => {
            if (!value) {
                return 'Debes ingresar un email';
            }
        }
    }).then((result) => {
        if (result.isConfirmed) {
            fetch('enviar_correo_manual.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    id_arrendatario: idArrendatario,
                    email: result.value
                })
            })
            .then(res => res.json())
            .then(data => {
                if (data.ok) {
                    Swal.fire('Enviado', 'Correo enviado correctamente', 'success');
                } else {
                    Swal.fire('Error', data.error, 'error');
                }
            });
        }
    });
}
</script>




</body>
</html>
