<?php
session_start();
if (!isset($_SESSION['admin'])) { header('Location: login.php'); exit; }

require '../conexion.php';

$busq = $_GET['q'] ?? '';
$sql = "SELECT c.*, p.titulo FROM consultas c LEFT JOIN propiedades p ON p.id = c.propiedad_id";
$params=[];$types='';
if ($busq !== '') {
  $sql .= " WHERE p.titulo LIKE ? OR c.nombre LIKE ?";
  $params[]='%'.$busq.'%';$params[]='%'.$busq.'%';$types='ss';
}
$sql .= " ORDER BY c.fecha DESC";

$stmt = $conn->prepare($sql);
if ($params) { $stmt->bind_param($types, ...$params); }
$stmt->execute();
$res = $stmt->get_result();
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Consultas recibidas</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light">
<nav class="navbar navbar-expand-lg navbar-dark bg-dark mb-4">
  <div class="container">
    <a class="navbar-brand" href="dashboard.php">← Dashboard</a>
    <span class="navbar-text text-white">Consultas</span>
  </div>
</nav>

<div class="container">
  <form class="d-flex mb-3" method="get">
    <input type="search" class="form-control me-2" name="q" placeholder="Buscar por propiedad o nombre" value="<?php echo htmlspecialchars($busq); ?>">
    <button class="btn btn-outline-secondary" type="submit">Buscar</button>
  </form>

  <?php if ($res->num_rows===0): ?>
    <p>No hay consultas.</p>
  <?php else: ?>
  <div class="table-responsive">
    <table class="table table-hover align-middle">
      <thead class="table-dark">
        <tr>
          <th>Fecha</th><th>Propiedad</th><th>Nombre</th><th>Teléfono</th><th>Mensaje</th><th>Acciones</th>
        </tr>
      </thead>
      <tbody>
      <?php while($c=$res->fetch_assoc()): ?>
        <tr>
          <td><?php echo date('d/m/Y H:i', strtotime($c['fecha'])); ?></td>
          <td><a href="../propiedad.php?id=<?php echo $c['propiedad_id']; ?>" target="_blank"><?php echo htmlspecialchars($c['titulo']); ?></a></td>
          <td><?php echo htmlspecialchars($c['nombre']); ?></td>
          <td><?php echo htmlspecialchars($c['telefono']); ?></td>
          <td><?php echo nl2br(htmlspecialchars(substr($c['mensaje'],0,80))); ?></td>
          <td>
            <a href="eliminar_consulta.php?id=<?php echo $c['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('¿Eliminar consulta?');">Borrar</a>
          </td>
        </tr>
      <?php endwhile; ?>
      </tbody>
    </table>
  </div>
  <?php endif; ?>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
