<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
if (!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true) {
    header("location: login.php");
    exit;
}

require_once 'includes/config.php';

/* ---------- DELETE ---------- */
if (isset($_GET['delete']) && is_numeric($_GET['delete'])) {
    $stmt = $conn->prepare("DELETE FROM inquiries WHERE id=?");
    $stmt->bind_param("i", $_GET['delete']);
    $stmt->execute();

    $_SESSION['success'] = 'Inquiry deleted successfully!';
    header("Location: visit_requests.php");
    exit;
}

/* ---------- FILTERS ---------- */
$property_filter = $_GET['property'] ?? '';
$date_from       = $_GET['date_from'] ?? '';
$date_to         = $_GET['date_to'] ?? '';

$query  = "SELECT id, inquiry_type, name, phone, email, location, property_type, created_at FROM inquiries WHERE 1=1";
$where  = [];
$params = [];
$types  = "";

if ($property_filter) {
    $where[] = "property_type=?";
    $params[] = $property_filter;
    $types .= "s";
}

if ($date_from) {
    $where[] = "created_at >= ?";
    $params[] = $date_from . " 00:00:00";
    $types .= "s";
}

if ($date_to) {
    $where[] = "created_at <= ?";
    $params[] = $date_to . " 23:59:59";
    $types .= "s";
}

if ($where) {
    $query .= " AND " . implode(" AND ", $where);
}

$query .= " ORDER BY created_at DESC";

/* ---------- COUNT ---------- */
$count_sql = "SELECT COUNT(*) FROM inquiries WHERE 1=1";
if ($where) {
    $count_sql .= " AND " . implode(" AND ", $where);
}

$count_stmt = $conn->prepare($count_sql);
if ($params) {
    $count_stmt->bind_param($types, ...$params);
}
$count_stmt->execute();
$count_stmt->bind_result($total);
$count_stmt->fetch();
$count_stmt->close();

/* ---------- PAGINATION ---------- */
$per_page = 10;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $per_page;

$query .= " LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;
$types   .= "ii";

/* ---------- MAIN QUERY ---------- */
$stmt = $conn->prepare($query);
$stmt->bind_param($types, ...$params);
$stmt->execute();

$stmt->bind_result(
    $id,
    $inquiry_type,
    $name,
    $phone,
    $email,
    $location,
    $property_type,
    $created_at
);

$requests = [];
while ($stmt->fetch()) {
    $requests[] = compact(
        'id',
        'inquiry_type',
        'name',
        'phone',
        'email',
        'location',
        'property_type',
        'created_at'
    );
}
$stmt->close();

/* ---------- PROPERTIES ---------- */
$properties = [];
$res = $conn->query("SELECT DISTINCT property_type FROM inquiries WHERE property_type!='' AND property_type IS NOT NULL");
while ($row = $res->fetch_assoc()) {
    $properties[] = $row['property_type'];
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Visit Requests</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
<style>
.visit-details { display:none }
.visit-details.show { display:table-row }
</style>
</head>
<body>

<?php include 'includes/header.php'; ?>

<div class="container-fluid mt-4">

<?php if (!empty($_SESSION['success'])): ?>
<div class="alert alert-success"><?= $_SESSION['success']; unset($_SESSION['success']); ?></div>
<?php endif; ?>

<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Inquiry Type</th>
<th>Property</th>
<th>Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>

<?php foreach ($requests as $r): ?>
<tr>
<td><?= $r['id'] ?></td>
<td><?= htmlspecialchars($r['name']) ?></td>
<td><?= htmlspecialchars($r['inquiry_type']) ?></td>
<td><?= htmlspecialchars($r['property_type']) ?></td>
<td><?= date('M j, Y h:i A', strtotime($r['created_at'])) ?></td>
<td>
<button class="btn btn-sm btn-primary view-details" data-id="<?= $r['id'] ?>">
<i class="bi bi-eye"></i>
</button>
<a class="btn btn-sm btn-danger" href="?delete=<?= $r['id'] ?>" 
onclick="return confirm('Delete this inquiry?')">
<i class="bi bi-trash"></i>
</a>
</td>
</tr>

<tr id="details-<?= $r['id'] ?>" class="visit-details">
<td colspan="6" class="bg-light">
<b>Phone:</b> <?= htmlspecialchars($r['phone']) ?><br>
<b>Email:</b> <?= htmlspecialchars($r['email']) ?><br>
<b>Location:</b> <?= htmlspecialchars($r['location']) ?>
</td>
</tr>
<?php endforeach; ?>

</tbody>
</table>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.querySelectorAll('.view-details').forEach(b=>{
b.onclick=()=>document.getElementById('details-'+b.dataset.id).classList.toggle('show');
});
</script>

</body>
</html>
