<?php
// Initialize the session
session_start();
 
// Check if the user is logged in, if not then redirect to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
    header("location: login.php");
    exit;
}

// Include config file
require_once "includes/config.php";

// Initialize variables
$properties = [];
$error_message = "";
$success_message = "";
$current_page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$per_page = 10;
$offset = ($current_page - 1) * $per_page;
$total_items = 0;

// Handle property deletion
if(isset($_GET['action']) && $_GET['action'] == 'delete' && isset($_GET['id'])) {
    $id = (int)$_GET['id'];
    
    try {
        // Get property images to delete files
        $sql = "SELECT image_path FROM property_images WHERE property_id = ?";
        if($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $id);
            if($stmt->execute()) {
                $result = $stmt->get_result();
                while($image = $result->fetch_assoc()) {
                    if(file_exists("../uploads/properties/" . $image['image_path'])) {
                        unlink("../uploads/properties/" . $image['image_path']);
                    }
                }
                $result->free();
            }
            $stmt->close();
        }
        
        // Delete property images from database
        $sql = "DELETE FROM property_images WHERE property_id = ?";
        if($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $id);
            $stmt->execute();
            $stmt->close();
        }
        
        // Delete property
        $sql = "DELETE FROM properties WHERE id = ?";
        if($stmt = $conn->prepare($sql)) {
            $stmt->bind_param("i", $id);
            if($stmt->execute()) {
                $success_message = "Property deleted successfully!";
                // Redirect to refresh the page
                header("location: properties.php?success=deleted");
                exit();
            }
            $stmt->close();
        }
    } catch (Exception $e) {
        $error_message = "Error deleting property: " . $e->getMessage();
    }
}

// Get total number of properties
$sql = "SELECT COUNT(*) as total FROM properties";
if($result = $conn->query($sql)) {
    $row = $result->fetch_assoc();
    $total_items = $row['total'];
    $result->free();
}

// Calculate total pages
$total_pages = ceil($total_items / $per_page);

// Get properties with pagination
$sql = "SELECT p.*, 
               (SELECT image_path FROM property_images WHERE property_id = p.id LIMIT 1) as featured_image
        FROM properties p 
        ORDER BY p.created_at DESC 
        LIMIT ? OFFSET ?";

if($stmt = $conn->prepare($sql)) {
    $stmt->bind_param("ii", $per_page, $offset);
    if($stmt->execute()) {
        $result = $stmt->get_result();
        while($row = $result->fetch_assoc()) {
            $properties[] = $row;
        }
        $result->free();
    }
    $stmt->close();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Properties Management - Real Estate Admin</title>
    
    <!-- Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <!-- Bootstrap 5 -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Custom styles -->
    <style>
        :root {
            --primary-color: #4361ee;
            --secondary-color: #3f37c9;
            --success-color: #4cc9f0;
            --danger-color: #f72585;
            --warning-color: #f8961e;
            --dark-color: #1a1a2e;
            --light-color: #f8f9fa;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: #f5f7fb;
            color: #4a4a4a;
        }

        /* Sidebar Styles */
        .sidebar {
            background: linear-gradient(180deg, var(--dark-color) 0%, #16213e 100%);
            min-height: 100vh;
            box-shadow: 2px 0 10px rgba(0,0,0,0.1);
            position: fixed;
            width: 250px;
            z-index: 1000;
        }

        .sidebar .brand-link {
            padding: 1.5rem 1rem;
            text-align: center;
            border-bottom: 1px solid rgba(255,255,255,0.1);
            margin-bottom: 1rem;
        }

        .sidebar .brand-text {
            font-size: 1.5rem;
            font-weight: 700;
            color: white;
        }

        .sidebar .nav-link {
            color: rgba(255, 255, 255, 0.8);
            padding: 12px 20px;
            margin: 4px 10px;
            border-radius: 8px;
            transition: all 0.3s;
        }

        .sidebar .nav-link:hover,
        .sidebar .nav-link.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            transform: translateX(5px);
        }

        .sidebar .nav-link i {
            width: 24px;
            text-align: center;
            margin-right: 10px;
        }

        /* Main Content */
        .main-content {
            margin-left: 250px;
            padding: 2rem;
            min-height: 100vh;
        }

        /* Header */
        .page-header {
            background: white;
            padding: 1.5rem;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            margin-bottom: 2rem;
            display: flex;
            justify-content: space-between;
            align-items: center;
            flex-wrap: wrap;
            gap: 1rem;
        }

        .page-title {
            font-weight: 700;
            color: var(--dark-color);
            margin: 0;
        }

        /* Property Card */
        .property-card {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
            transition: all 0.3s ease;
            margin-bottom: 1.5rem;
            height: 100%;
        }

        .property-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 20px rgba(0,0,0,0.1);
        }

        .property-img {
            width: 100%;
            height: 200px;
            object-fit: cover;
        }

        .property-badge {
            position: absolute;
            top: 15px;
            right: 15px;
            z-index: 1;
            font-size: 0.8rem;
            font-weight: 600;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
        }

        .property-badge.sale {
            background-color: var(--danger-color);
            color: white;
        }

        .property-badge.rent {
            background-color: var(--success-color);
            color: white;
        }

        .property-details {
            padding: 1.5rem;
        }

        .property-title {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: var(--dark-color);
        }

        .property-location {
            color: #6c757d;
            margin-bottom: 0.75rem;
            display: flex;
            align-items: center;
        }

        .property-location i {
            margin-right: 0.5rem;
            color: var(--primary-color);
        }

        .property-features {
            display: flex;
            flex-wrap: wrap;
            gap: 1rem;
            margin-bottom: 1rem;
            padding-bottom: 1rem;
            border-bottom: 1px solid #f0f0f0;
        }

        .feature {
            display: flex;
            align-items: center;
            color: #6c757d;
            font-size: 0.9rem;
        }

        .feature i {
            margin-right: 0.5rem;
            color: var(--primary-color);
        }

        .property-price {
            font-size: 1.5rem;
            font-weight: 700;
            color: var(--primary-color);
            margin-bottom: 1rem;
        }

        .property-price span {
            font-size: 0.9rem;
            font-weight: 400;
            color: #6c757d;
        }

        .property-actions {
            display: flex;
            gap: 0.5rem;
        }

        /* Empty State */
        .empty-state {
            text-align: center;
            padding: 3rem 1rem;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.05);
        }

        .empty-state i {
            font-size: 4rem;
            color: #d1d5db;
            margin-bottom: 1rem;
        }

        .empty-state h4 {
            color: #4b5563;
            margin-bottom: 0.5rem;
        }

        .empty-state p {
            color: #6b7280;
            margin-bottom: 1.5rem;
        }

        /* Pagination */
        .pagination {
            margin-top: 2rem;
            justify-content: center;
        }

        .page-link {
            color: var(--primary-color);
            border: 1px solid #dee2e6;
            margin: 0 5px;
            border-radius: 8px !important;
            padding: 0.5rem 1rem;
            min-width: 40px;
            text-align: center;
            transition: all 0.2s;
        }

        .page-item.active .page-link {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
            color: white;
        }

        .page-link:hover {
            color: var(--secondary-color);
            background-color: #f0f2f5;
            border-color: #dee2e6;
        }

        /* Responsive */
        @media (max-width: 992px) {
            .sidebar {
                transform: translateX(-100%);
                transition: transform 0.3s ease;
            }
            
            .sidebar.show {
                transform: translateX(0);
            }
            
            .main-content {
                margin-left: 0;
            }
            
            .navbar-toggler {
                display: block;
            }
        }

        @media (min-width: 993px) {
            .navbar-toggler {
                display: none;
            }
        }

        @media (max-width: 768px) {
            .property-features {
                flex-direction: column;
                gap: 0.5rem;
            }
            
            .property-actions {
                flex-direction: column;
            }
            
            .property-actions .btn {
                width: 100%;
                margin-bottom: 0.5rem;
            }
        }
    </style>
</head>
<body>
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="d-flex flex-column h-100">
            <!-- Brand Logo -->
            <a href="index.php" class="brand-link">
                <span class="brand-text">RealEstate Pro</span>
            </a>

            <!-- Sidebar Menu -->
            <nav class="mt-3">
                <ul class="nav flex-column">
                    <li class="nav-item">
                        <a href="index.php" class="nav-link">
                            <i class="fas fa-tachometer-alt"></i> Dashboard
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="properties.php" class="nav-link active">
                            <i class="fas fa-home"></i> Properties
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="gallery.php" class="nav-link">
                            <i class="fas fa-images"></i> Gallery
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="categories.php" class="nav-link">
                            <i class="fas fa-tags"></i> Categories
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="users.php" class="nav-link">
                            <i class="fas fa-users"></i> Users
                        </a>
                    </li>
                    <li class="nav-item">
                        <a href="settings.php" class="nav-link">
                            <i class="fas fa-cog"></i> Settings
                        </a>
                    </li>
                </ul>
            </nav>

            <!-- User Profile -->
            <div class="mt-auto p-3">
                <div class="d-flex align-items-center text-white">
                    <img src="https://ui-avatars.com/api/?name=<?php echo urlencode($_SESSION['username'] ?? 'Admin'); ?>&background=4361ee&color=fff" 
                         alt="User" 
                         class="rounded-circle me-2" 
                         width="40" 
                         height="40">
                    <div>
                        <div class="fw-bold"><?php echo htmlspecialchars($_SESSION['username'] ?? 'Admin'); ?></div>
                        <small>Administrator</small>
                    </div>
                </div>
                <div class="mt-3">
                    <a href="logout.php" class="btn btn-outline-light btn-sm w-100">
                        <i class="fas fa-sign-out-alt me-1"></i> Logout
                    </a>
                </div>
            </div>
        </div>
    </div>

    <!-- Main Content -->
    <div class="main-content">
        <!-- Page Header -->
        <div class="page-header">
            <h1 class="page-title">Properties Management</h1>
            <div class="d-flex align-items-center">
                <a href="property-add.php" class="btn btn-primary">
                    <i class="fas fa-plus me-2"></i>Add New Property
                </a>
                <button class="btn btn-outline-secondary ms-2 d-md-none" id="sidebarToggle">
                    <i class="fas fa-bars"></i>
                </button>
            </div>
        </div>

        <?php if (isset($_GET['success'])): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <div class="d-flex align-items-center">
                    <i class="fas fa-check-circle me-2"></i>
                    <div>
                        <?php 
                        if ($_GET['success'] == 'added') {
                            echo 'Property added successfully!';
                        } elseif ($_GET['success'] == 'updated') {
                            echo 'Property updated successfully!';
                        } elseif ($_GET['success'] == 'deleted') {
                            echo 'Property deleted successfully!';
                        }
                        ?>
                    </div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="fas fa-exclamation-circle me-2"></i>
                <?php echo $error_message; ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
            </div>
        <?php endif; ?>

        <!-- Properties Grid -->
        <div class="row">
            <?php if (empty($properties)): ?>
                <div class="col-12">
                    <div class="empty-state">
                        <i class="fas fa-home"></i>
                        <h4>No Properties Found</h4>
                        <p>Get started by adding your first property.</p>
                        <a href="property-add.php" class="btn btn-primary">
                            <i class="fas fa-plus me-2"></i>Add Property
                        </a>
                    </div>
                </div>
            <?php else: ?>
                <?php foreach ($properties as $property): ?>
                    <div class="col-md-6 col-lg-4 col-xl-3">
                        <div class="property-card">
                            <div class="position-relative">
                                <img src="<?php echo !empty($property['featured_image']) ? '../uploads/properties/' . htmlspecialchars($property['featured_image']) : 'https://via.placeholder.com/400x300?text=No+Image'; ?>" 
                                     alt="<?php echo htmlspecialchars($property['title']); ?>" 
                                     class="property-img">
                                <span class="property-badge <?php echo $property['type'] === 'sale' ? 'sale' : 'rent'; ?>">
                                    <?php echo ucfirst($property['type']); ?>
                                </span>
                            </div>
                            <div class="property-details">
                                <h3 class="property-title"><?php echo htmlspecialchars($property['title']); ?></h3>
                                <div class="property-location">
                                    <i class="fas fa-map-marker-alt"></i>
                                    <?php echo htmlspecialchars($property['address']); ?>
                                </div>
                                <div class="property-features">
                                    <div class="feature">
                                        <i class="fas fa-bed"></i>
                                        <span><?php echo $property['bedrooms']; ?> Beds</span>
                                    </div>
                                    <div class="feature">
                                        <i class="fas fa-bath"></i>
                                        <span><?php echo $property['bathrooms']; ?> Baths</span>
                                    </div>
                                    <div class="feature">
                                        <i class="fas fa-ruler-combined"></i>
                                        <span><?php echo number_format($property['area']); ?> sqft</span>
                                    </div>
                                </div>
                                <div class="property-price">
                                    $<?php echo number_format($property['price']); ?>
                                    <?php if ($property['type'] === 'rent'): ?>
                                        <span>/ month</span>
                                    <?php endif; ?>
                                </div>
                                <div class="property-actions">
                                    <a href="property-view.php?id=<?php echo $property['id']; ?>" 
                                       class="btn btn-sm btn-outline-primary flex-grow-1">
                                        <i class="fas fa-eye me-1"></i> View
                                    </a>
                                    <a href="property-edit.php?id=<?php echo $property['id']; ?>" 
                                       class="btn btn-sm btn-outline-secondary">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <a href="properties.php?action=delete&id=<?php echo $property['id']; ?>" 
                                       class="btn btn-sm btn-outline-danger"
                                       onclick="return confirm('Are you sure you want to delete this property? This action cannot be undone.');">
                                        <i class="fas fa-trash"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>

        <!-- Pagination -->
        <?php if ($total_pages > 1): ?>
            <nav aria-label="Properties pagination" class="mt-4">
                <ul class="pagination justify-content-center">
                    <?php if ($current_page > 1): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo ($current_page - 1); ?>" aria-label="Previous">
                                <span aria-hidden="true">&laquo;</span>
                            </a>
                        </li>
                    <?php endif; ?>

                    <?php 
                    $start_page = max(1, $current_page - 2);
                    $end_page = min($total_pages, $start_page + 4);
                    $start_page = max(1, $end_page - 4);
                    
                    if ($start_page > 1) {
                        echo '<li class="page-item"><span class="page-link">...</span></li>';
                    }
                    
                    for ($i = $start_page; $i <= $end_page; $i++): 
                    ?>
                        <li class="page-item <?php echo ($i == $current_page) ? 'active' : ''; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php 
                    endfor; 
                    
                    if ($end_page < $total_pages) {
                        echo '<li class="page-item"><span class="page-link">...</span></li>';
                    }
                    ?>

                    <?php if ($current_page < $total_pages): ?>
                        <li class="page-item">
                            <a class="page-link" href="?page=<?php echo ($current_page + 1); ?>" aria-label="Next">
                                <span aria-hidden="true">&raquo;</span>
                            </a>
                        </li>
                    <?php endif; ?>
                </ul>
            </nav>
        <?php endif; ?>
    </div>

    <!-- Bootstrap Bundle with Popper -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Toggle sidebar on mobile
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            document.querySelector('.sidebar').classList.toggle('show');
        });

        // Auto-hide sidebar when clicking outside on mobile
        document.addEventListener('click', function(event) {
            const sidebar = document.querySelector('.sidebar');
            const sidebarToggle = document.getElementById('sidebarToggle');
            
            if (window.innerWidth <= 992 && 
                !sidebar.contains(event.target) && 
                event.target !== sidebarToggle && 
                !sidebarToggle.contains(event.target)) {
                sidebar.classList.remove('show');
            }
        });
    </script>
</body>
</html>
