<?php
// Include the database connection
require 'db_connection.php';

// Check if product_id is passed in the URL
if (isset($_GET['product_id'])) {
    $product_id = $_GET['product_id'];

    // Fetch product details
    $query = "
        SELECT 
            p.product_name, 
            p.current_price, 
            p.description
        FROM products p
        WHERE p.id = '$product_id'
    ";
    $product_result = mysqli_query($conn, $query);

    // Fetch images for the product
    $images_query = "SELECT image_path FROM product_images WHERE product_id = '$product_id'";
    $images_result = mysqli_query($conn, $images_query);

    // Check if the product exists
    if ($product_result && mysqli_num_rows($product_result) > 0) {
        $product = mysqli_fetch_assoc($product_result);
    } else {
        echo '<p>Product not found.</p>';
        exit;
    }
} else {
    echo '<p>No product ID provided.</p>';
    exit;
}
?>

<?php include("header.php"); ?>

<body>
<main class="main-wrapper">
    <?php include("top.php"); ?>
    <div class="offcanvas-overlay"></div>

    <!-- ...:::Start Product Single Section:::... -->
    <div class="product-single-section section-gap-top-30">
        <div class="container">
            <div class="product-gallery-image">
                <!-- Slider main container -->
                <div class="swiper">
                    <!-- Additional required wrapper -->
                    <div class="swiper-wrapper">
                        <!-- Dynamically Generated Slides -->
                        <?php
                        if ($images_result && mysqli_num_rows($images_result) > 0) {
                            while ($image = mysqli_fetch_assoc($images_result)) {
                                $image_path = !empty($image['image_path']) ? htmlspecialchars($image['image_path']) : 'placeholder.jpg';
                                echo '
                                <div class="swiper-slide">
                                    <div class="product-gallery-single-item">
                                        <div class="image">
                                            <img class="img-fluid" width="276" height="172" src="adm/' . $image_path . '" alt="' . htmlspecialchars($product['product_name']) . '">
                                            <div class="image-shape image-shape-1"></div>
                                            <div class="image-shape image-shape-2"></div>
                                        </div>
                                    </div>
                                </div>';
                            }
                        } else {
                            echo '<div class="swiper-slide">No images available.</div>';
                        }
                        ?>
                    </div>
                </div>
                <!-- If we need pagination -->
                <div class="swiper-pagination"></div>
                <div class="product-tag">
                    <span class="tag-discount">40% OFF</span>
                    <a href="wishlist.html" aria-label="Wishlist" class="btn btn--size-33-33 btn--center btn--round btn--color-radical-red btn--bg-white btn--box-shadow">
                        <i class="icon icon-carce-heart"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="container px-0">
            <div class="product-gallery-details">
                <h1 class="title"><?= htmlspecialchars($product['product_name']); ?></h1>
                <p class="text">
                    <?= nl2br(htmlspecialchars($product['description'])); ?>
                </p>

                <ul class="product-variable-lists">
                    <li class="list-item">
                        <div class="left">QTY</div>
                        <div class="right">
                            <div class="product-quantity">
                                <div class="num-block skin-2">
                                    <div class="num-in">
                                        <span class="minus" id="reduce-quantity">-</span>
                                        <input id="quantity" type="text" class="in-num" value="1" readonly="">
                                        <span class="plus" id="add-quantity">+</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </li>
                </ul>

                <div class="price-n-cart">
                    <span class="price" id="total-price">
                        N<?= number_format($product['current_price'], 2); ?>
                    </span>
                   <a href="#" class="btn cart" id="add-to-cart-btn" data-product-id="<?= $product_id; ?>" data-product-name="<?= htmlspecialchars($product['product_name']); ?>" data-price="<?= $product['current_price']; ?>">
    <span class="icon"><i class="icon icon-carce-cart"></i></span>Add to Cart
</a>

                </div>
            </div>
        </div>
    </div>
    <!-- ...:::End Product Single Section:::... -->

    <footer class="footer-section"></footer>
</main>

<!-- JS Files -->
<script src="assets/js/vendor/modernizr-3.11.2.min.js"></script>
<script src="assets/js/vendor/jquery-3.6.0.min.js"></script>
<script src="assets/js/vendor/jquery-migrate-3.3.2.min.js"></script>
<script src="assets/js/plugins/swiper-bundle.min.js"></script>
<script src="assets/js/main.js"></script>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        // Get elements
        const reduceBtn = document.getElementById("reduce-quantity");
        const addBtn = document.getElementById("add-quantity");
        const quantityInput = document.getElementById("quantity");
        const totalPriceElement = document.getElementById("total-price");

        // Product current price
        const currentPrice = <?= json_encode($product['current_price']); ?>;

        // Function to update total price
        function updateTotalPrice() {
            const quantity = parseInt(quantityInput.value, 10);
            const totalPrice = quantity * currentPrice;
            totalPriceElement.textContent = `N${totalPrice.toLocaleString()}`;
        }

        // Reduce Quantity
        reduceBtn.addEventListener("click", () => {
            let currentValue = parseInt(quantityInput.value, 10);
            if (currentValue > 1) {
                currentValue -= 1;
                quantityInput.value = currentValue;
                updateTotalPrice();
            }
        });

        // Add Quantity
        addBtn.addEventListener("click", () => {
            let currentValue = parseInt(quantityInput.value, 10);
            currentValue += 1;
            quantityInput.value = currentValue;
            updateTotalPrice();
        });

        // Handle Manual Quantity Input
        quantityInput.addEventListener("input", () => {
            let quantity = parseInt(quantityInput.value, 10);
            if (!isNaN(quantity) && quantity > 0) {
                updateTotalPrice();
            } else {
                quantityInput.value = 1; // Reset invalid value
                updateTotalPrice();
            }
        });
    });
</script>

<script>
// Function to get a cookie value by name
function getCookie(name) {
    let cookies = document.cookie.split(';');
    for (let i = 0; i < cookies.length; i++) {
        let cookie = cookies[i].trim();
        if (cookie.startsWith(name + '=')) {
            return decodeURIComponent(cookie.substring(name.length + 1));
        }
    }
    return '';
}

// Function to set a cookie
function setCookie(name, value, days) {
    let date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = name + '=' + encodeURIComponent(value) + '; expires=' + date.toUTCString() + '; path=/';
}

// Function to add item to cart
document.getElementById('add-to-cart-btn').addEventListener('click', function (e) {
    e.preventDefault();

    const productId = this.getAttribute('data-product-id');
    const productName = this.getAttribute('data-product-name');
    const price = this.getAttribute('data-price');

    // Get existing cart from cookies or initialize an empty object
    let cart = getCookie('cart') ? JSON.parse(getCookie('cart')) : {};

    // If the product is already in the cart, increase the quantity
    if (cart[productId]) {
        cart[productId].quantity += 1;
    } else {
        // Add new product to the cart
        cart[productId] = {
            product_name: productName,
            price: price,
            quantity: 1
        };
    }

    // Save the updated cart back to cookies (expires in 7 days)
    setCookie('cart', JSON.stringify(cart), 7);

    // Update cart count in the header
    updateCartCount();

    alert('Product added to cart!');
});

// Function to update the cart count in the header
function updateCartCount() {
    let cart = getCookie('cart') ? JSON.parse(getCookie('cart')) : {};
    let count = Object.values(cart).reduce((total, item) => total + item.quantity, 0);
    document.getElementById('cart-count').textContent = count;
}

// Update cart count on page load
document.addEventListener('DOMContentLoaded', updateCartCount);
</script>


</body>
</html>
