<?php
session_start();
require 'db.php';

// Redirect if not logged in
if(!isset($_SESSION['user_id'])){
    header("Location: login.php");
    exit;
}

// Fetch all properties
$query = $conn->query("
    SELECT properties.*, users.fullname, users.email, users.phoneno
    FROM properties
    LEFT JOIN users ON properties.agent_id = users.id
    ORDER BY properties.created_at DESC
");
?>

<!DOCTYPE html>
<html>
<head>
<title>Admin Dashboard - Properties</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">

<style>
body { background: #f4f4f4; }
.navbar { background: #000; }
.navbar a { color: #fff !important; }
.table thead { background: #000; color: #fff; }
</style>
</head>

<body>

<!-- NAVBAR -->
<nav class="navbar navbar-expand-lg navbar-dark mb-4">
  <div class="container">
    <a class="navbar-brand" href="dashboard.php">Admin Dashboard</a>
    <div class="ms-auto">
      <a href="post_property.php" class="btn btn-light btn-sm">Post Property</a>
      <a href="logout.php" class="btn btn-danger btn-sm">Logout</a>
    </div>
  </div>
</nav>

<div class="container">
  <h3 class="mb-4">All Posted Properties</h3>

  <div class="table-responsive">
    <table class="table table-bordered table-striped">
      <thead>
        <tr>
          <th>#</th>
          <th>Main Image</th>
          <th>Title</th>
          <th>Price</th>
          <th>Category</th>
          <th>Type</th>
          <th>Agent</th>
          <th>Date</th>
          <th>View</th>
        </tr>
      </thead>
      <tbody>

      <?php 
      $count = 1; 
      while($row = $query->fetch_assoc()): 
      ?>

        <tr>
          <td><?= $count++; ?></td>
          <td>
            <img src="<?= $row['img']; ?>" width="80" height="60" style="object-fit:cover; border-radius:5px;">
          </td>
          <td><?= htmlspecialchars($row['title']); ?></td>
          <td>₦<?= number_format($row['price']); ?></td>
          <td><?= ucfirst($row['category']); ?></td>
          <td><?= ucfirst($row['type']); ?></td>
          <td>
            <?= htmlspecialchars($row['fullname']); ?><br>
            <small><?= htmlspecialchars($row['email']); ?></small>
          </td>
          <td><?= date("d M, Y", strtotime($row['created_at'])); ?></td>

          <td>
            <a href="admin_view_property.php?id=<?= $row['id']; ?>" 
               class="btn btn-dark btn-sm">View</a>
          </td>
        </tr>

      <?php endwhile; ?>

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

</div>

</body>
</html>
