<?php
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/seo.php';

$status = in_array($_GET['status'] ?? '', ['sale', 'rent'], true) ? $_GET['status'] : '';
$districtSlug = trim($_GET['district'] ?? '');
$typeSlug = trim($_GET['type'] ?? '');
$bedrooms = isset($_GET['bedrooms']) && $_GET['bedrooms'] !== '' ? (int)$_GET['bedrooms'] : null;
$minPrice = isset($_GET['min_price']) && $_GET['min_price'] !== '' ? (float)$_GET['min_price'] : null;
$maxPrice = isset($_GET['max_price']) && $_GET['max_price'] !== '' ? (float)$_GET['max_price'] : null;
$keyword = trim($_GET['q'] ?? '');
$featuredOnly = !empty($_GET['featured']);
$sort = $_GET['sort'] ?? 'newest';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = ITEMS_PER_PAGE;

$district = $districtSlug ? get_district_by_slug($districtSlug) : null;
$category = $typeSlug ? get_category_by_slug($typeSlug) : null;

$where = [];
$params = [];
if ($status) { $where[] = 'p.status = ?'; $params[] = $status; }
if ($district) { $where[] = 'p.district_id = ?'; $params[] = $district['id']; }
if ($category) { $where[] = 'p.category_id = ?'; $params[] = $category['id']; }
if ($bedrooms !== null) { $where[] = 'p.bedrooms >= ?'; $params[] = $bedrooms; }
if ($minPrice !== null) { $where[] = 'p.price >= ?'; $params[] = $minPrice; }
if ($maxPrice !== null) { $where[] = 'p.price <= ?'; $params[] = $maxPrice; }
if ($featuredOnly) { $where[] = 'p.is_featured = 1'; }
if ($keyword !== '') {
    $where[] = '(p.title LIKE ? OR p.sector LIKE ? OR p.neighborhood LIKE ? OR p.short_description LIKE ?)';
    $kw = '%' . $keyword . '%';
    array_push($params, $kw, $kw, $kw, $kw);
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$orderMap = [
    'newest' => 'p.created_at DESC',
    'price_asc' => 'p.price ASC',
    'price_desc' => 'p.price DESC',
    'featured' => 'p.is_featured DESC, p.created_at DESC',
];
$orderSql = $orderMap[$sort] ?? $orderMap['newest'];

$countStmt = db()->prepare("SELECT COUNT(*) FROM properties p $whereSql");
$countStmt->execute($params);
$total = (int)$countStmt->fetchColumn();
$totalPages = max(1, (int)ceil($total / $perPage));
$page = min($page, $totalPages);
$offset = ($page - 1) * $perPage;

$sql = "SELECT p.* FROM properties p $whereSql ORDER BY $orderSql LIMIT $perPage OFFSET $offset";
$stmt = db()->prepare($sql);
$stmt->execute($params);
$properties = $stmt->fetchAll();

$titleParts = [];
if ($category) $titleParts[] = $category['name'];
if ($district) $titleParts[] = 'in ' . $district['name'];
if ($status) $titleParts[] = $status === 'rent' ? 'for Rent' : 'for Sale';
$pageTitle = $titleParts ? implode(' ', $titleParts) : 'All Properties';

$seo = [
    'title' => $pageTitle . ' | ' . SITE_NAME,
    'description' => 'Browse ' . $total . ' verified properties ' . ($district ? 'in ' . $district['name'] . ', ' : '') . 'Kigali, Rwanda. Filter by type, price, bedrooms and more.',
    'path' => '/properties',
];
include __DIR__ . '/../includes/header.php';
?>
<section class="section-pad-sm">
  <div class="container">
    <?= breadcrumb_html([['name' => 'Properties', 'url' => '/properties']]) ?>
    <div class="section-head" style="max-width:none;">
      <div class="eyebrow">Property Search</div>
      <h1 style="font-size:var(--fs-2xl);"><?= e($pageTitle) ?></h1>
      <p><?= (int)$total ?> verified listing<?= $total === 1 ? '' : 's' ?> matching your search.</p>
    </div>

    <div style="display:grid;grid-template-columns:300px 1fr;gap:var(--space-8);align-items:start;">
      <aside class="filter-panel">
        <form method="get" action="/properties" id="filterForm">
          <?php if ($keyword): ?><input type="hidden" name="q" value="<?= e($keyword) ?>"><?php endif; ?>
          <div class="filter-group">
            <h4>Status</h4>
            <div class="filter-chip-row" data-multi="false">
              <label class="filter-chip <?= $status === '' ? 'active' : '' ?>"><input type="radio" name="status" value="" class="visually-hidden" <?= $status === '' ? 'checked' : '' ?> onchange="this.form.submit()">All</label>
              <label class="filter-chip <?= $status === 'sale' ? 'active' : '' ?>"><input type="radio" name="status" value="sale" class="visually-hidden" <?= $status === 'sale' ? 'checked' : '' ?> onchange="this.form.submit()">For Sale</label>
              <label class="filter-chip <?= $status === 'rent' ? 'active' : '' ?>"><input type="radio" name="status" value="rent" class="visually-hidden" <?= $status === 'rent' ? 'checked' : '' ?> onchange="this.form.submit()">For Rent</label>
            </div>
          </div>
          <div class="filter-group">
            <h4>Property Type</h4>
            <select name="type" onchange="this.form.submit()">
              <option value="">All Types</option>
              <?php foreach (get_categories() as $c): ?>
                <option value="<?= e($c['slug']) ?>" <?= $typeSlug === $c['slug'] ? 'selected' : '' ?>><?= e($c['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="filter-group">
            <h4>District</h4>
            <select name="district" onchange="this.form.submit()">
              <option value="">All Districts</option>
              <?php foreach (get_districts() as $d): ?>
                <option value="<?= e($d['slug']) ?>" <?= $districtSlug === $d['slug'] ? 'selected' : '' ?>><?= e($d['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="filter-group">
            <h4>Bedrooms</h4>
            <div class="filter-chip-row" data-multi="false">
              <?php foreach ([null => 'Any', 1 => '1+', 2 => '2+', 3 => '3+', 4 => '4+', 5 => '5+'] as $val => $label): ?>
                <label class="filter-chip <?= $bedrooms === $val ? 'active' : '' ?>"><input type="radio" name="bedrooms" value="<?= e((string)$val) ?>" class="visually-hidden" <?= $bedrooms === $val ? 'checked' : '' ?> onchange="this.form.submit()"><?= $label ?></label>
              <?php endforeach; ?>
            </div>
          </div>
          <div class="filter-group">
            <h4>Price Range (RWF)</h4>
            <div class="field-row">
              <div class="field"><input type="number" name="min_price" placeholder="Min" value="<?= e($_GET['min_price'] ?? '') ?>"></div>
              <div class="field"><input type="number" name="max_price" placeholder="Max" value="<?= e($_GET['max_price'] ?? '') ?>"></div>
            </div>
            <button type="submit" class="btn btn-outline btn-sm btn-block mt-3">Apply Price</button>
          </div>
          <div class="filter-group">
            <label class="checkbox-row"><input type="checkbox" name="featured" value="1" <?= $featuredOnly ? 'checked' : '' ?> onchange="this.form.submit()"> Featured listings only</label>
          </div>
          <a href="/properties" class="btn-ghost text-sm">Clear all filters</a>
        </form>
      </aside>

      <div>
        <div class="results-toolbar">
          <div class="results-count"><?= (int)$total ?> results</div>
          <form method="get" class="flex items-center gap-3">
            <?php foreach (['status','district','type','bedrooms','min_price','max_price','q','featured'] as $k) if (isset($_GET[$k])): ?>
              <input type="hidden" name="<?= e($k) ?>" value="<?= e($_GET[$k]) ?>">
            <?php endif; ?>
            <label for="sort" class="text-sm text-muted">Sort by</label>
            <select id="sort" name="sort" onchange="this.form.submit()">
              <option value="newest" <?= $sort === 'newest' ? 'selected' : '' ?>>Newest</option>
              <option value="price_asc" <?= $sort === 'price_asc' ? 'selected' : '' ?>>Price: Low to High</option>
              <option value="price_desc" <?= $sort === 'price_desc' ? 'selected' : '' ?>>Price: High to Low</option>
              <option value="featured" <?= $sort === 'featured' ? 'selected' : '' ?>>Featured First</option>
            </select>
          </form>
        </div>

        <?php if (empty($properties)): ?>
          <div class="form-card text-center">
            <h3>No properties match your filters</h3>
            <p class="text-muted">Try widening your search, or let us know what you're looking for and we'll notify you when a match becomes available.</p>
            <a href="/vip-alerts" class="btn btn-accent mt-4">Join VIP Property Alerts</a>
          </div>
        <?php else: ?>
          <div class="grid grid-3">
            <?php foreach ($properties as $p): ?>
              <?php include __DIR__ . '/../includes/partials/property-card.php'; ?>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>

        <?= paginate_query('/properties', $_GET, $page, $totalPages) ?>
      </div>
    </div>
  </div>
</section>
<?php include __DIR__ . '/../includes/footer.php'; ?>
