<?php
define('ROVO_APP', true);
require_once '../config.php';
require_once '../Auth.php';

$page_title = 'Browse Properties';

if (!$auth->isLoggedIn() || $auth->isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$current_user = $auth->getCurrentUser();

// Get filters
$transaction_type = $_GET['type'] ?? 'all';
$property_type = $_GET['property'] ?? 'all';
$min_price = isset($_GET['min_price']) ? (float)$_GET['min_price'] : null;
$max_price = isset($_GET['max_price']) ? (float)$_GET['max_price'] : null;
$bedrooms = isset($_GET['bedrooms']) ? (int)$_GET['bedrooms'] : null;
$city = $_GET['city'] ?? '';
$state = $_GET['state'] ?? '';
$search = $_GET['search'] ?? '';

// Build query
$sql = "SELECT * FROM properties WHERE status = 'available'";
$params = [];

if ($transaction_type !== 'all') {
    $sql .= " AND transaction_type = ?";
    $params[] = $transaction_type;
}

if ($property_type !== 'all') {
    $sql .= " AND property_type = ?";
    $params[] = $property_type;
}

if ($min_price) {
    $sql .= " AND price >= ?";
    $params[] = $min_price;
}

if ($max_price) {
    $sql .= " AND price <= ?";
    $params[] = $max_price;
}

if ($bedrooms) {
    $sql .= " AND bedrooms >= ?";
    $params[] = $bedrooms;
}

if (!empty($city)) {
    $sql .= " AND city LIKE ?";
    $params[] = "%$city%";
}

if (!empty($state)) {
    $sql .= " AND state LIKE ?";
    $params[] = "%$state%";
}

if (!empty($search)) {
    $sql .= " AND (title LIKE ? OR description LIKE ? OR address LIKE ?)";
    $params[] = "%$search%";
    $params[] = "%$search%";
    $params[] = "%$search%";
}

$sql .= " ORDER BY featured DESC, created_at DESC";

$properties = $db->fetchAll($sql, $params);

// Get unique cities and states
$cities = $db->fetchAll("SELECT DISTINCT city FROM properties WHERE status = 'available' ORDER BY city");
$states = $db->fetchAll("SELECT DISTINCT state FROM properties WHERE status = 'available' ORDER BY state");

include 'includes/header.php';
?>

<style>
    .property-card {
        transition: all 0.3s;
        height: 100%;
        border: none;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }
    
    .property-card:hover {
        transform: translateY(-8px);
        box-shadow: 0 8px 20px rgba(0,0,0,0.15);
    }
    
    .property-image {
        height: 220px;
        object-fit: cover;
        border-radius: 10px 10px 0 0;
    }
    
    .property-badge {
        position: absolute;
        top: 15px;
        right: 15px;
        background: var(--primary);
        color: white;
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 0.85rem;
        font-weight: 600;
    }
    
    .featured-badge {
        position: absolute;
        top: 15px;
        left: 15px;
        background: #dc3545;
        color: white;
        padding: 5px 15px;
        border-radius: 20px;
        font-size: 0.75rem;
        font-weight: 600;
    }
    
    .property-price {
        font-size: 1.8rem;
        font-weight: 700;
        color: var(--primary);
    }
    
    .property-features {
        display: flex;
        gap: 15px;
        padding: 10px 0;
        border-top: 1px solid #e0e0e0;
        border-bottom: 1px solid #e0e0e0;
        margin: 15px 0;
    }
    
    .feature-item {
        display: flex;
        align-items: center;
        gap: 5px;
        color: #666;
    }
    
    .filter-section {
        background: white;
        padding: 20px;
        border-radius: 15px;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        margin-bottom: 30px;
    }
    
    .quick-filter {
        padding: 8px 16px;
        border: 2px solid #e0e0e0;
        border-radius: 20px;
        background: white;
        cursor: pointer;
        transition: all 0.3s;
        text-decoration: none;
        color: #666;
        display: inline-block;
        margin: 5px;
    }
    
    .quick-filter:hover,
    .quick-filter.active {
        border-color: var(--primary);
        background: var(--primary);
        color: white;
    }
</style>

<div class="page-header">
    <h1>Browse Properties</h1>
    <p class="text-muted mb-0">Find your perfect home</p>
</div>

<!-- Search & Filters -->
<div class="filter-section">
    <form method="GET" class="row g-3">
        <div class="col-md-4">
            <input type="text" name="search" class="form-control" 
                   placeholder="Search properties..." 
                   value="<?php echo htmlspecialchars($search); ?>">
        </div>
        
        <div class="col-md-2">
            <select name="type" class="form-select">
                <option value="all">All Types</option>
                <option value="sale" <?php echo $transaction_type === 'sale' ? 'selected' : ''; ?>>For Sale</option>
                <option value="rent" <?php echo $transaction_type === 'rent' ? 'selected' : ''; ?>>For Rent</option>
                <option value="lease" <?php echo $transaction_type === 'lease' ? 'selected' : ''; ?>>For Lease</option>
            </select>
        </div>
        
        <div class="col-md-2">
            <select name="property" class="form-select">
                <option value="all">All Properties</option>
                <option value="house" <?php echo $property_type === 'house' ? 'selected' : ''; ?>>House</option>
                <option value="apartment" <?php echo $property_type === 'apartment' ? 'selected' : ''; ?>>Apartment</option>
                <option value="villa" <?php echo $property_type === 'villa' ? 'selected' : ''; ?>>Villa</option>
                <option value="duplex" <?php echo $property_type === 'duplex' ? 'selected' : ''; ?>>Duplex</option>
            </select>
        </div>
        
        <div class="col-md-2">
            <select name="bedrooms" class="form-select">
                <option value="">Any Bedrooms</option>
                <option value="1" <?php echo $bedrooms === 1 ? 'selected' : ''; ?>>1+ Bedroom</option>
                <option value="2" <?php echo $bedrooms === 2 ? 'selected' : ''; ?>>2+ Bedrooms</option>
                <option value="3" <?php echo $bedrooms === 3 ? 'selected' : ''; ?>>3+ Bedrooms</option>
                <option value="4" <?php echo $bedrooms === 4 ? 'selected' : ''; ?>>4+ Bedrooms</option>
            </select>
        </div>
        
        <div class="col-md-2">
            <button type="submit" class="btn btn-primary w-100">
                <i class="fas fa-search"></i> Search
            </button>
        </div>
        
        <!-- Advanced Filters Toggle -->
        <div class="col-12">
            <button type="button" class="btn btn-sm btn-outline-secondary" 
                    data-bs-toggle="collapse" data-bs-target="#advancedFilters">
                <i class="fas fa-sliders-h"></i> Advanced Filters
            </button>
        </div>
        
        <!-- Advanced Filters -->
        <div class="collapse" id="advancedFilters">
            <div class="row g-3 mt-2">
                <div class="col-md-3">
                    <label class="form-label">Min Price (₦)</label>
                    <input type="number" name="min_price" class="form-control" 
                           placeholder="Min" value="<?php echo $min_price; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">Max Price (₦)</label>
                    <input type="number" name="max_price" class="form-control" 
                           placeholder="Max" value="<?php echo $max_price; ?>">
                </div>
                <div class="col-md-3">
                    <label class="form-label">City</label>
                    <select name="city" class="form-select">
                        <option value="">All Cities</option>
                        <?php foreach ($cities as $c): ?>
                        <option value="<?php echo htmlspecialchars($c['city']); ?>" 
                                <?php echo $city === $c['city'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($c['city']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="col-md-3">
                    <label class="form-label">State</label>
                    <select name="state" class="form-select">
                        <option value="">All States</option>
                        <?php foreach ($states as $s): ?>
                        <option value="<?php echo htmlspecialchars($s['state']); ?>" 
                                <?php echo $state === $s['state'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($s['state']); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
            </div>
        </div>
    </form>
    
    <!-- Quick Filters -->
    <div class="mt-3">
        <strong class="me-2">Quick Filters:</strong>
        <a href="?" class="quick-filter <?php echo empty($_GET) ? 'active' : ''; ?>">All Properties</a>
        <a href="?type=rent" class="quick-filter <?php echo $transaction_type === 'rent' ? 'active' : ''; ?>">For Rent</a>
        <a href="?type=sale" class="quick-filter <?php echo $transaction_type === 'sale' ? 'active' : ''; ?>">For Sale</a>
        <a href="?bedrooms=2" class="quick-filter <?php echo $bedrooms === 2 ? 'active' : ''; ?>">2+ Bedrooms</a>
        <a href="?max_price=2000000" class="quick-filter">Under ₦2M</a>
    </div>
</div>

<!-- Results Count -->
<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">
        <i class="fas fa-building"></i> 
        <?php echo count($properties); ?> Properties Found
    </h5>
    <div>
        <select class="form-select form-select-sm" id="sortBy">
            <option value="featured">Featured First</option>
            <option value="price_low">Price: Low to High</option>
            <option value="price_high">Price: High to Low</option>
            <option value="newest">Newest First</option>
        </select>
    </div>
</div>

<!-- Properties Grid -->
<?php if (empty($properties)): ?>
<div class="card">
    <div class="card-body text-center py-5">
        <i class="fas fa-search fa-5x text-muted mb-4"></i>
        <h4 class="text-muted">No Properties Found</h4>
        <p class="text-muted mb-4">Try adjusting your search filters</p>
        <a href="properties.php" class="btn btn-primary">
            <i class="fas fa-redo"></i> Clear Filters
        </a>
    </div>
</div>
<?php else: ?>
<div class="row" id="propertiesGrid">
    <?php foreach ($properties as $property): ?>
    <div class="col-md-6 col-lg-4 mb-4 property-item" 
         data-price="<?php echo $property['price']; ?>"
         data-featured="<?php echo $property['featured']; ?>"
         data-date="<?php echo strtotime($property['created_at']); ?>">
        <div class="card property-card">
            <div class="position-relative">
                <?php
                $images = json_decode($property['images'], true);
                $image_url = !empty($images) ? '../' . $images[0] : '../assets/images/property-placeholder.jpg';
                ?>
                <img src="<?php echo htmlspecialchars($image_url); ?>" 
                     class="card-img-top property-image" 
                     alt="<?php echo htmlspecialchars($property['title']); ?>">
                
                <?php if ($property['featured']): ?>
                <span class="featured-badge">
                    <i class="fas fa-star"></i> Featured
                </span>
                <?php endif; ?>
                
                <span class="property-badge">
                    <?php echo ucfirst($property['transaction_type']); ?>
                </span>
            </div>
            
            <div class="card-body">
                <h5 class="card-title mb-2">
                    <a href="property-details.php?id=<?php echo $property['id']; ?>" 
                       class="text-decoration-none text-dark">
                        <?php echo htmlspecialchars($property['title']); ?>
                    </a>
                </h5>
                
                <p class="text-muted mb-2">
                    <i class="fas fa-map-marker-alt"></i>
                    <?php echo htmlspecialchars($property['city'] . ', ' . $property['state']); ?>
                </p>
                
                <div class="property-price mb-2">
                    ₦<?php echo number_format($property['price']); ?>
                    <?php if ($property['transaction_type'] === 'rent' && $property['monthly_rent']): ?>
                    <small class="text-muted" style="font-size: 0.9rem;">
                        /year (₦<?php echo number_format($property['monthly_rent']); ?>/month)
                    </small>
                    <?php endif; ?>
                </div>
                
                <div class="property-features">
                    <?php if ($property['bedrooms']): ?>
                    <div class="feature-item">
                        <i class="fas fa-bed"></i>
                        <span><?php echo $property['bedrooms']; ?> Beds</span>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($property['bathrooms']): ?>
                    <div class="feature-item">
                        <i class="fas fa-bath"></i>
                        <span><?php echo $property['bathrooms']; ?> Baths</span>
                    </div>
                    <?php endif; ?>
                    
                    <?php if ($property['size_sqft']): ?>
                    <div class="feature-item">
                        <i class="fas fa-ruler-combined"></i>
                        <span><?php echo number_format($property['size_sqft']); ?> sqft</span>
                    </div>
                    <?php endif; ?>
                </div>
                
                <p class="card-text text-muted small" style="height: 60px; overflow: hidden;">
                    <?php echo htmlspecialchars(substr($property['description'], 0, 120)) . '...'; ?>
                </p>
                
                <div class="d-grid gap-2">
                    <a href="property-details.php?id=<?php echo $property['id']; ?>" 
                       class="btn btn-outline-primary">
                        <i class="fas fa-eye"></i> View Details
                    </a>
                    <?php if ($current_user['status'] === 'active'): ?>
                    <a href="apply.php?property=<?php echo $property['id']; ?>" 
                       class="btn btn-primary">
                        <i class="fas fa-paper-plane"></i> Apply Now
                    </a>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
    <?php endforeach; ?>
</div>
<?php endif; ?>

<script>
$(document).ready(function() {
    // Sort functionality
    $('#sortBy').change(function() {
        const sortBy = $(this).val();
        const $grid = $('#propertiesGrid');
        const $items = $grid.children('.property-item');
        
        $items.sort(function(a, b) {
            switch(sortBy) {
                case 'price_low':
                    return $(a).data('price') - $(b).data('price');
                case 'price_high':
                    return $(b).data('price') - $(a).data('price');
                case 'newest':
                    return $(b).data('date') - $(a).data('date');
                case 'featured':
                default:
                    if ($(b).data('featured') !== $(a).data('featured')) {
                        return $(b).data('featured') - $(a).data('featured');
                    }
                    return $(b).data('date') - $(a).data('date');
            }
        });
        
        $items.detach().appendTo($grid);
    });
});
</script>

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