<?php
include('db_connection.php');
include('header2.php');

// Fetch products from the database
try {
    $stmt = $conn->prepare("SELECT * FROM product_img"); // Replace with your actual table name
    $stmt->execute();
    $products = $stmt->fetchAll(); // Fetch all products as an array
} catch (PDOException $e) {
    $products = []; // Default to an empty array if there's an error
    error_log("Error fetching products: " . $e->getMessage());
}

$message = "";

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['submit_data'])) {
    $area = $_POST['area'];
    $min_price = $_POST['min_price'];
    $max_price = $_POST['max_price'];
    $start_date = $_POST['start_date'];
    $end_date = $_POST['end_date'];
    $user_id = 1; // Replace with a valid user_id from sign_up

    if (!empty($area) && !empty($min_price) && !empty($max_price) && !empty($start_date) && !empty($end_date)) {
        try {
            $sql = "INSERT INTO submit_connection (user_id, area, min_price, max_price, start_date, end_date) 
                    VALUES (:user_id, :area, :min_price, :max_price, :start_date, :end_date)";
            $stmt = $conn->prepare($sql);

            $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $stmt->bindParam(':area', $area, PDO::PARAM_INT);
            $stmt->bindParam(':min_price', $min_price, PDO::PARAM_INT);
            $stmt->bindParam(':max_price', $max_price, PDO::PARAM_INT);
            $stmt->bindParam(':start_date', $start_date, PDO::PARAM_STR);
            $stmt->bindParam(':end_date', $end_date, PDO::PARAM_STR);

            if ($stmt->execute()) {
                $message = "Data inserted successfully!";
            } else {
                $message = "Failed to insert data.";
            }
        } catch (PDOException $e) {
            $message = "Error: " . $e->getMessage();
        }
    } else {
        $message = "All fields are required.";
    }
}

?>

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Product Page</title>
    <link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.19/dist/tailwind.min.css" rel="stylesheet">
    <style>
        /* Style for the pop-up overlay */
        .popup-overlay {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
        }

        /* Style for the pop-up content */
        .popup-content {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            width: 300px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }

        /* Close button style */
        .popup-close {
            background: #ff5e57;
            color: white;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            margin-top: 10px;
        }
    </style>
</head>

<body class="bg-gray-100">

    <div class="flex min-h-screen">
        <!-- Sidebar Filter Section -->
        <aside id="sidebar" class="w-64 bg-white p-4 border-r hidden md:block">
            <div class="mb-4">
                <h2 class="font-semibold text-lg">Filter</h2>

                <!-- Building Filter -->
                <div class="mb-6">
                    <h3 class="font-semibold text-sm">Choose building</h3>
                    <div class="mb-4">
                        <label><input type="radio" name="building" onchange="filterBybuilding('dining')"> Dining Room</label><br>
                        <label><input type="radio" name="building" onchange="filterBybuilding('bedroom')"> Bedroom</label><br>
                        <label><input type="radio" name="building" onchange="filterBybuilding('kitchen')"> Kitchen</label><br>
                    </div>
                </div>

                <!-- Brand Filter -->
                <div class="mb-6">
                    <h3 class="font-semibold text-sm">Brand</h3>
                    <div>
                        <label><input type="checkbox" onchange="filterByBrand('Reynomed')"> Reynomed</label>
                        <label><input type="checkbox" onchange="filterByBrand('Blue World')"> Blue World</label>
                        <label><input type="checkbox" onchange="filterByBrand('Wearhouse')"> Wearhouse</label>
                        <label><input type="checkbox" onchange="filterByBrand('Umbroos')"> Umbroos</label>
                    </div>
                </div>

                <!-- Price Filter -->
                <div class="mb-4">
                    <h3 class="font-semibold text-sm">Price</h3>
                    <label><input type="radio" name="price" onchange="filterByPrice('0-100')"> 0 - 100</label><br>
                    <label><input type="radio" name="price" onchange="filterByPrice('100-150')"> 100 - 150</label><br>
                    <label><input type="radio" name="price" onchange="filterByPrice('150-200')"> 150 - 200</label><br>
                </div>
            </div>
        </aside>

        <!-- Main Product Section -->
        <main class="flex-1 p-6">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-2xl font-semibold">Product List</h2>
                <div class="flex items-center space-x-4">
                    <label for="sort" class="text-sm">Sort by:</label>
                    <select id="sort" class="border rounded" onchange="sortProducts()">
                        <option value="lowToHigh">Low to High</option>
                        <option value="highToLow">High to Low</option>
                    </select>
                    <button class="md:hidden bg-blue-500 text-white p-2 rounded" onclick="toggleSidebar()">Filter</button>
                </div>
            </div>

            <!-- Product Grid -->
            <!-- Product Grid -->
            <div id="product-grid" class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
                <?php if (!empty($products)): ?>
                    <?php foreach ($products as $product): ?>
                        <div class="bg-white p-4 border rounded-lg shadow-sm">
                            <div class="relative">
                                <img src="<?= htmlspecialchars($product["image_path"]) ?>" alt="Product Image" class="w-full h-32 object-cover mb-4">
                            </div>
                            <h3 class="text-sm font-medium"><?= htmlspecialchars($product["title"]) ?></h3>
                            <p class="text-gray-500 text-xs"><?= htmlspecialchars($product["description"]) ?></p>
                            <p class="text-lg font-semibold text-gray-800">₹<?= htmlspecialchars($product["price_min"]) ?> - ₹<?= htmlspecialchars($product["price_max"]) ?></p>
                            <!-- <button class="w-full py-2 bg-blue-500 text-white rounded-lg mt-4 addToCartButton">Order</button> -->
                            <button class="openModal bg-green-500 text-white py-2 px-4 rounded addToCartButton">Order</button>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <p class="text-center text-gray-500">No products available.</p>
                <?php endif; ?>
            </div>

            <!-- Popup Modal -->
            <div id="popupModal" class="fixed inset-0 bg-black bg-opacity-50 flex justify-center items-center hidden">
                <div class="bg-white p-6 rounded-lg shadow-lg w-96">
                    <h2 class="text-lg font-bold mb-4">Product Details</h2>
                    <!-- Form for Submitting Data -->
                    <form method="POST" action="">
                        <label for="area">Area (sq. ft):</label>
                        <input type="number" id="area" name="area" class="w-full p-2 border rounded mb-4" required>

                        <label for="min_price">Min Price:</label>
                        <input type="number" id="min_price" name="min_price" class="w-full p-2 border rounded mb-4" required>

                        <label for="max_price">Max Price:</label>
                        <input type="number" id="max_price" name="max_price" class="w-full p-2 border rounded mb-4" required>

                        <label for="start_date">Start Date:</label>
                        <input type="date" id="start_date" name="start_date" class="w-full p-2 border rounded mb-4" required>

                        <label for="end_date">End Date:</label>
                        <input type="date" id="end_date" name="end_date" class="w-full p-2 border rounded mb-4" required>

                        <div class="flex justify-between">
                            <button type="submit" name="submit_data" class="bg-blue-500 text-white py-2 px-4 rounded">Submit</button>
                            <button type="button" id="closeModal" class="bg-red-500 text-white py-2 px-4 rounded">Close</button>
                        </div>
                    </form>
                </div>
            </div>

            <?php if ($message): ?>
                <p class="text-center text-green-500"><?= htmlspecialchars($message) ?></p>
            <?php endif; ?>



            <!-- JavaScript -->
            <script>
                // JavaScript to manage modal visibility
                document.addEventListener("DOMContentLoaded", function() {
                    const modal = document.getElementById("popupModal");
                    const closeModal = document.getElementById("closeModal");

                    document.querySelectorAll(".openModal").forEach(button => {
                        button.addEventListener("click", function() {
                            modal.classList.remove("hidden");
                        });
                    });

                    closeModal.addEventListener("click", function() {
                        modal.classList.add("hidden");
                    });
                });
            </script>



            <script>
                // Toggle sidebar visibility on mobile
                function toggleSidebar() {
                    document.getElementById('sidebar').classList.toggle('hidden');
                }

                // Filter products by color
                function filterBybuilding(building) {
                    fetchProducts({
                        building
                    });
                }

                // Filter products by brand
                function filterByBrand(brand) {
                    fetchProducts({
                        brand
                    });
                }

                // Filter products by price range
                function filterByPrice(price) {
                    fetchProducts({
                        price
                    });
                }

                // Sort products
                function sortProducts() {
                    const sortOrder = document.getElementById('sort').value;
                    fetchProducts({
                        sort: sortOrder
                    });
                }

                // AJAX function to fetch products based on filters
                function fetchProducts(params) {
                    // Convert the parameters object to a query string
                    const query = new URLSearchParams(params).toString();

                    // Construct the URL and make the fetch request
                    fetch(`product.php?${query}`)
                        .then(response => response.text())
                        .then(html => {
                            // Update the product grid with the fetched HTML
                            document.getElementById('product-grid').innerHTML = html;
                        })
                        .catch(console.error); // Log any errors to the console
                }
            </script>

</body>

</html>