<?php
require_once 'config.php';

// Initialize variables
$is_logged_in = isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);

// Get filter parameters - only set if actually provided and not empty
$keyword = isset($_GET['keyword']) && !empty(trim($_GET['keyword'])) ? trim($_GET['keyword']) : '';
$type = isset($_GET['type']) && !empty(trim($_GET['type'])) ? trim($_GET['type']) : '';
$location = isset($_GET['location']) && !empty(trim($_GET['location'])) ? trim($_GET['location']) : '';
$min_price = isset($_GET['min_price']) && !empty(trim($_GET['min_price'])) ? intval($_GET['min_price']) : 0;
$max_price = isset($_GET['max_price']) && !empty(trim($_GET['max_price'])) ? intval($_GET['max_price']) : 0;
$bedrooms = isset($_GET['bedrooms']) && intval($_GET['bedrooms']) > 0 ? intval($_GET['bedrooms']) : 0;
$bathrooms = isset($_GET['bathrooms']) && intval($_GET['bathrooms']) > 0 ? intval($_GET['bathrooms']) : 0;
$sort = isset($_GET['sort']) && !empty(trim($_GET['sort'])) ? trim($_GET['sort']) : 'newest';
$page = isset($_GET['page']) ? intval($_GET['page']) : 1;
$per_page = 9;
$offset = ($page - 1) * $per_page;

// Build query with proper parameter binding
$query = "SELECT * FROM properties WHERE status = 'active'";
$count_query = "SELECT COUNT(*) as total FROM properties WHERE status = 'active'";
$conditions = array();
$params = array();
$types = '';

// Keyword search
if (!empty($keyword)) {
    $conditions[] = "(title LIKE ? OR description LIKE ? OR address LIKE ? OR city LIKE ?)";
    $keyword_param = '%' . $keyword . '%';
    $params[] = $keyword_param;
    $params[] = $keyword_param;
    $params[] = $keyword_param;
    $params[] = $keyword_param;
    $types .= 'ssss';
}

// Type filter
if (!empty($type)) {
    $conditions[] = "type = ?";
    $params[] = $type;
    $types .= 's';
}

// Location filter
if (!empty($location)) {
    $conditions[] = "(city LIKE ? OR address LIKE ?)";
    $location_param = '%' . $location . '%';
    $params[] = $location_param;
    $params[] = $location_param;
    $types .= 'ss';
}

// Price range
if ($min_price > 0) {
    $conditions[] = "price >= ?";
    $params[] = $min_price;
    $types .= 'i';
}

if ($max_price > 0) {
    $conditions[] = "price <= ?";
    $params[] = $max_price;
    $types .= 'i';
}

// Bedrooms filter
if ($bedrooms > 0) {
    $conditions[] = "bedrooms >= ?";
    $params[] = $bedrooms;
    $types .= 'i';
}

// Bathrooms filter
if ($bathrooms > 0) {
    $conditions[] = "bathrooms >= ?";
    $params[] = $bathrooms;
    $types .= 'i';
}

// Add conditions to query
if (!empty($conditions)) {
    $query .= " AND " . implode(" AND ", $conditions);
    $count_query .= " AND " . implode(" AND ", $conditions);
}

// Sorting
switch ($sort) {
    case 'price_low':
        $query .= " ORDER BY price ASC";
        break;
    case 'price_high':
        $query .= " ORDER BY price DESC";
        break;
    case 'newest':
    default:
        $query .= " ORDER BY created_at DESC";
}

// Get total count
$stmt_count = $conn->prepare($count_query);
if (!empty($params)) {
    $stmt_count->bind_param($types, ...$params);
}
$stmt_count->execute();
$result_count = $stmt_count->get_result();
$row_count = $result_count->fetch_assoc();
$total_properties = $row_count['total'];
$total_pages = ceil($total_properties / $per_page);

// Get paginated results
$query .= " LIMIT $per_page OFFSET $offset";
$stmt = $conn->prepare($query);
if (!empty($params)) {
    $stmt->bind_param($types, ...$params);
}
$stmt->execute();
$properties_result = $stmt->get_result();
$properties = array();
while ($row = $properties_result->fetch_assoc()) {
    $properties[] = $row;
}
?>
<!doctype html>
<html class="no-js" lang="zxx">

<head>
  <meta charset="utf-8">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <title>Properties - Zemaraim</title>
  <meta name="author" content="vecuro">
  <meta name="description" content="Find your dream property on Zemaraim">
  <meta name="keywords" content="real estate, properties, apartments, villas">
  <meta name="robots" content="INDEX,FOLLOW">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <link rel="icon" type="image/png" href="assets/img/favicons/favicon.png">
  <meta name="msapplication-TileColor" content="#ffffff">
  <meta name="theme-color" content="#ffffff">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin="">
  <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;500;600;700&family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
  <link rel="stylesheet" href="assets/css/bootstrap.min.css">
  <link rel="stylesheet" href="assets/css/fontawesome.min.css">
  <link rel="stylesheet" href="assets/css/magnific-popup.min.css">
  <link rel="stylesheet" href="assets/css/slick.min.css">
  <link rel="stylesheet" href="assets/css/style.css">
  <style>
    .properties-container { min-height: calc(100vh - 300px); }
    .sidebar-widget { background: white; padding: 25px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.08); margin-bottom: 25px; }
    .sidebar-widget h3 { font-size: 16px; font-weight: 700; margin-bottom: 20px; color: #1a1a1a; }
    .form-group label { display: block; margin-bottom: 8px; color: #1a1a1a; font-weight: 600; font-size: 13px; }
    .form-control { padding: 10px 12px; border: 1px solid #e0e0e0; border-radius: 5px; font-size: 13px; width: 100%; transition: all 0.3s ease; }
    .form-control:focus { border-color: #667eea; box-shadow: 0 0 0 3px rgba(102,126,234,0.1); outline: none; }
    .search-btn { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; padding: 12px; border-radius: 5px; width: 100%; font-weight: 600; cursor: pointer; transition: all 0.3s ease; margin-top: 15px; }
    .search-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(102,126,234,0.3); }
    .property-card-modern { background: white; border-radius: 10px; overflow: hidden; box-shadow: 0 2px 15px rgba(0,0,0,0.08); transition: all 0.3s ease; display: flex; flex-direction: column; height: 100%; }
    .property-card-modern:hover { transform: translateY(-5px); box-shadow: 0 10px 30px rgba(0,0,0,0.15); }
    .property-image { position: relative; overflow: hidden; height: auto; background: #f0f0f0; }
    .property-image img { width: 100%; height: auto; object-fit: cover; transition: transform 0.3s ease; }
    .property-card-modern:hover .property-image img { transform: scale(1.1); }
    .property-badge { position: absolute; top: 15px; right: 15px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 6px 12px; border-radius: 20px; font-size: 11px; font-weight: 700; text-transform: uppercase; }
    .property-badge.sold { background: #ff4757; }
    .property-badge.pending { background: #ffa502; }
    .property-content { padding: 20px; flex-grow: 1; display: flex; flex-direction: column; }
    .property-meta { display: flex; gap: 15px; margin: 0px 0; font-size: 13px; color: #999; flex-wrap: wrap; }
    .property-meta i { color: #667eea; min-width: 14px; }
    .property-price { font-size: 22px; font-weight: 700; color: #667eea; margin: 0px 0; }
    .property-address { color: #1a1a1a; font-size: 14px; margin: 0px 0; }
    .property-desc { color: #666; font-size: 13px; margin: 0px 0; flex-grow: 1; }
    .property-footer { display: flex; gap: 10px; margin-top: auto; }
    .view-btn { flex: 1; padding: 10px; background: #f0f0f0; color: #667eea; text-decoration: none; text-align: center; border-radius: 5px; transition: all 0.3s ease; font-weight: 600; font-size: 12px; }
    .view-btn:hover { background: #667eea; color: white; }
    .favorite-btn { padding: 10px 15px; border: 1px solid #e0e0e0; background: white; color: #667eea; cursor: pointer; border-radius: 5px; transition: all 0.3s ease; }
    .favorite-btn:hover { border-color: #667eea; background: #f8f9fa; }
    .favorite-btn.active { background: #ff4757; color: white; border-color: #ff4757; }
    .sort-options { display: flex; gap: 10px; margin-bottom: 20px; flex-wrap: wrap; }
    .sort-btn { padding: 8px 15px; border: 1px solid #e0e0e0; background: #164a4d; border-radius: 5px; cursor: pointer; transition: all 0.3s ease; font-size: 13px; font-weight: 600; }
    .sort-btn.active { background: #667eea; color: white; border-color: #667eea; }
    .sort-btn:hover { border-color: #667eea; color: #667eea; }
    .pagination-wrapper { display: flex; justify-content: center; gap: 10px; margin-top: 15px; margin-bottom: 15px; flex-wrap: wrap; }
    .pagination-btn { padding: 8px 12px; border: 1px solid #e0e0e0; background: white; border-radius: 5px; text-decoration: none; color: #1a1a1a; transition: all 0.3s ease; font-weight: 600; }
    .pagination-btn:hover { border-color: #667eea; color: #667eea; }
    .pagination-btn.active { background: #667eea; color: white; border-color: #667eea; }
    .no-results { text-align: center; padding: 60px 20px; }
    .no-results i { font-size: 60px; color: #ddd; margin-bottom: 20px; }
    .no-results h3 { color: #1a1a1a; margin-bottom: 10px; }
    .no-results p { color: #999; }

    @media (max-width: 992px) {
      .property-image { height: 180px; }
      .property-content { padding: 15px; }
      .sidebar-widget { margin-bottom: 20px; }
    }

    @media (max-width: 768px) {
      .sort-options { gap: 8px; }
      .sort-btn { padding: 6px 12px; font-size: 12px; }
      .property-card-modern { border-radius: 8px; }
      .property-image { height: 160px; }
      .property-content { padding: 12px; }
      .property-price { font-size: 18px; }
      .sidebar-widget { padding: 20px; }
    }

    @media (max-width: 480px) {
      .property-image { height: 140px; }
      .property-content { padding: 10px; }
      .property-price { font-size: 16px; }
      .property-meta { font-size: 12px; gap: 10px; }
      .property-footer { gap: 8px; }
      .view-btn, .favorite-btn { padding: 8px 10px; font-size: 11px; }
      .sidebar-widget { padding: 15px; margin-bottom: 15px; }
      .form-control { padding: 8px 10px; font-size: 12px; }
    }
  </style>
</head>

<body>
  <?php include 'header.php'; ?>

  <!-- Breadcrumb -->
  <div class="breadcrumb-wrapper" style="background-image: url('assets/img/bg/breadcrumb-bg.jpg')">
    <div class="breadcrumb-content">
      <h1 class="breadcrumb-title">Properties</h1>
      <div class="breadcrumb-menu">
        <a href="index.php">Home</a>
        <span class="breadcrumb-separator">/</span>
        <span class="breadcrumb-current">Properties (<?php echo $total_properties; ?> Found)</span>
      </div>
    </div>
  </div>

  <!-- Properties Section -->
  <section class="vs-section-padding properties-container">
    <div class="container">
      <div class="row g-4">
        
        <!-- SIDEBAR: Filters -->
        <div class="col-lg-3">
          <div class="sidebar-widget">
            <h3><i class="fas fa-search"></i> Search & Filter</h3>
            <form method="GET" action="">
              <!-- Keyword Search -->
              <div class="form-group">
                <label for="keyword">Keyword</label>
                <input type="text" id="keyword" name="keyword" class="form-control" placeholder="Location, city, zip..." value="<?php echo htmlspecialchars($keyword); ?>">
              </div>

              <!-- Property Type -->
              <div class="form-group">
                <label for="type">Property Type</label>
                <select id="type" name="type" class="form-control">
                  <option value="">All Types</option>
                  <option value="apartment" <?php echo $type === 'apartment' ? 'selected' : ''; ?>>Apartment</option>
                  <option value="villa" <?php echo $type === 'villa' ? 'selected' : ''; ?>>Villa</option>
                  <option value="house" <?php echo $type === 'house' ? 'selected' : ''; ?>>House</option>
                  <option value="commercial" <?php echo $type === 'commercial' ? 'selected' : ''; ?>>Commercial</option>
                  <option value="land" <?php echo $type === 'land' ? 'selected' : ''; ?>>Land</option>
                </select>
              </div>

              <!-- Location -->
              <div class="form-group">
                <label for="location">Location</label>
                <input type="text" id="location" name="location" class="form-control" placeholder="City or address" value="<?php echo htmlspecialchars($location); ?>">
              </div>

              <!-- Price Range -->
              <div class="form-group">
                <label>Price Range</label>
                <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                  <input type="number" name="min_price" class="form-control" placeholder="Min" value="<?php echo $min_price > 0 ? $min_price : ''; ?>">
                  <input type="number" name="max_price" class="form-control" placeholder="Max" value="<?php echo $max_price > 0 ? $max_price : ''; ?>">
                </div>
              </div>

              <!-- Bedrooms -->
              <div class="form-group">
                <label for="bedrooms">Bedrooms</label>
                <select id="bedrooms" name="bedrooms" class="form-control">
                  <option value="0">Any</option>
                  <option value="1" <?php echo $bedrooms === 1 ? 'selected' : ''; ?>>1+</option>
                  <option value="2" <?php echo $bedrooms === 2 ? 'selected' : ''; ?>>2+</option>
                  <option value="3" <?php echo $bedrooms === 3 ? 'selected' : ''; ?>>3+</option>
                  <option value="4" <?php echo $bedrooms === 4 ? 'selected' : ''; ?>>4+</option>
                </select>
              </div>

              <!-- Bathrooms -->
              <div class="form-group">
                <label for="bathrooms">Bathrooms</label>
                <select id="bathrooms" name="bathrooms" class="form-control">
                  <option value="0">Any</option>
                  <option value="1" <?php echo $bathrooms === 1 ? 'selected' : ''; ?>>1+</option>
                  <option value="2" <?php echo $bathrooms === 2 ? 'selected' : ''; ?>>2+</option>
                  <option value="3" <?php echo $bathrooms === 3 ? 'selected' : ''; ?>>3+</option>
                </select>
              </div>

              <button type="submit" class="search-btn">
                <i class="fas fa-search"></i> Search Properties
              </button>
            </form>
          </div>
        </div>

        <!-- MAIN: Properties Grid -->
        <div class="col-lg-9">
          <!-- Sort Options -->
          <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 30px; flex-wrap: wrap; gap: 15px;">
            <h3 style="margin: 0; font-size: 18px;">Results: <span style="color: #667eea;"><?php echo $total_properties; ?></span> Properties Found</h3>
            <div class="sort-options">
              <a href="?<?php echo http_build_query(array_merge($_GET, ['sort' => 'newest'])); ?>" class="sort-btn <?php echo $sort === 'newest' ? 'active' : ''; ?>">Newest</a>
              <a href="?<?php echo http_build_query(array_merge($_GET, ['sort' => 'price_low'])); ?>" class="sort-btn <?php echo $sort === 'price_low' ? 'active' : ''; ?>">Price: Low</a>
              <a href="?<?php echo http_build_query(array_merge($_GET, ['sort' => 'price_high'])); ?>" class="sort-btn <?php echo $sort === 'price_high' ? 'active' : ''; ?>">Price: High</a>
            </div>
          </div>

          <!-- Properties Grid -->
          <?php if (!empty($properties)): ?>
            <div class="row g-4">
              <?php foreach ($properties as $prop): ?>
                <div class="col-md-6 col-lg-4">
                  <div class="property-card-modern">
                    <div class="property-image">
                      <img src="<?php echo !empty($prop['image_url']) ? htmlspecialchars($prop['image_url']) : 'assets/img/properties/properties-list-1.png'; ?>" alt="<?php echo htmlspecialchars($prop['title']); ?>">
                      <span class="property-badge <?php echo $prop['status'] !== 'active' ? strtolower($prop['status']) : ''; ?>">
                        <?php echo strtoupper($prop['status']); ?>
                      </span>
                    </div>
                    <div class="property-content">
                      <h4 style="margin: 0 0 8px 0; color: #1a1a1a;"><?php echo htmlspecialchars($prop['title']); ?></h4>
                      <div class="property-address">
                        <i class="fas fa-map-marker-alt" style="color: #667eea; margin-right: 5px;"></i>
                        <?php echo htmlspecialchars($prop['address']); ?>, <?php echo htmlspecialchars($prop['city']); ?>
                      </div>
                      <div class="property-meta">
                        <span><i class="fas fa-bed"></i> <?php echo $prop['bedrooms']; ?> Beds</span>
                        <span><i class="fas fa-bath"></i> <?php echo $prop['bathrooms']; ?> Baths</span>
                        <span><i class="fas fa-ruler-combined"></i> <?php echo $prop['area']; ?> sqft</span>
                      </div>
                      <div class="property-desc">
                        <?php echo substr(htmlspecialchars($prop['description']), 0, 100) . '...'; ?>
                      </div>
                      <div class="property-price">₹<?php echo number_format($prop['price']); ?></div>
                      <div class="property-footer">
                        <a href="properties-details.php?id=<?php echo $prop['id']; ?>" class="view-btn">
                          <i class="fas fa-eye"></i> View Details
                        </a>
                        <button class="favorite-btn" onclick="toggleFavorite(<?php echo $prop['id']; ?>, event)">
                          <i class="fas fa-heart"></i>
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>

            <!-- Pagination -->
            <?php if ($total_pages > 1): ?>
              <div class="pagination-wrapper">
                <?php if ($page > 1): ?>
                  <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>" class="pagination-btn">First</a>
                  <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page - 1])); ?>" class="pagination-btn">Previous</a>
                <?php endif; ?>

                <?php 
                  $start = max(1, $page - 2);
                  $end = min($total_pages, $page + 2);
                  for ($i = $start; $i <= $end; $i++): 
                ?>
                  <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>" class="pagination-btn <?php echo $i === $page ? 'active' : ''; ?>"><?php echo $i; ?></a>
                <?php endfor; ?>

                <?php if ($page < $total_pages): ?>
                  <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $page + 1])); ?>" class="pagination-btn">Next</a>
                  <a href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>" class="pagination-btn">Last</a>
                <?php endif; ?>
              </div>
            <?php endif; ?>
          <?php else: ?>
            <div class="no-results">
              <i class="fas fa-search"></i>
              <h3>No Properties Found</h3>
              <p>Try adjusting your search filters or browse all properties.</p>
            </div>
          <?php endif; ?>
        </div>
      </div>
    </div>
  </section>

  <?php include 'footer.php'; ?>

  <script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
  <script src="assets/js/bootstrap.min.js"></script>
  <script src="assets/js/slick.min.js"></script>
  <script src="assets/js/jquery.magnific-popup.min.js"></script>
  <script src="assets/js/imagesloaded.pkgd.min.js"></script>
  <script src="assets/js/isotope.pkgd.min.js"></script>
  <script src="assets/js/main.js"></script>

  <script>
    // Real-time favorite toggle
    async function toggleFavorite(propertyId, e) {
      e.preventDefault();
      const btn = e.target.closest('.favorite-btn');
      
      // Check if user is logged in
      if (!<?php echo isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'customer' ? 'true' : 'false'; ?>) {
        alert('Please login as a customer to add favorites');
        window.location.href = 'login.php';
        return;
      }
      
      const isActive = btn.classList.contains('active');
      const action = isActive ? 'remove' : 'add';
      
      try {
        const response = await fetch('api/favorites-toggle.php', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({
            property_id: propertyId,
            action: action
          })
        });
        
        const data = await response.json();
        if (data.success) {
          btn.classList.toggle('active');
          // Notify dashboard if open in another tab
          localStorage.setItem('favorites-updated', JSON.stringify({
            property_id: propertyId,
            action: action,
            timestamp: new Date().getTime()
          }));
        } else {
          alert('Error: ' + (data.message || 'Failed to update favorite'));
        }
      } catch (error) {
        console.error('Error toggling favorite:', error);
        alert('Error updating favorite');
      }
    }

    // Load favorites on page load
    async function loadFavoritesStatus() {
      <?php if (isset($_SESSION['user_id']) && $_SESSION['user_role'] === 'customer'): ?>
        try {
          const response = await fetch('api/get-favorites.php');
          const data = await response.json();
          if (data.success) {
            const favoriteIds = (data.favorites || []).map(f => f.id);
            document.querySelectorAll('.favorite-btn').forEach(btn => {
              const propertyId = btn.getAttribute('onclick').match(/\d+/)[0];
              if (favoriteIds.includes(parseInt(propertyId))) {
                btn.classList.add('active');
              }
            });
          }
        } catch (error) {
          console.error('Error loading favorites:', error);
        }
      <?php endif; ?>
    }

    document.addEventListener('DOMContentLoaded', function() {
      loadFavoritesStatus();
      
      // Listen for updates from other tabs
      window.addEventListener('storage', function(e) {
        if (e.key === 'favorites-updated') {
          loadFavoritesStatus();
        }
      });
    });
  </script>
</body>

</html>
