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

<div class="offcanvas-overlay"></div>

<!-- ...:::Start Cart Section:::... -->
<div class="cart-section section-gap-top-30">
    <div class="container">
        <div class="cart-items-wrapper">
            <?php
           require 'db_connection.php';

            // Retrieve cart from cookies
            $cart = isset($_COOKIE['cart']) ? json_decode($_COOKIE['cart'], true) : [];

            // Initialize totals
            $subtotal = 0;
            $tax_rate = 0.07;
            ?>

            <ul class="cart-item-list">
                <?php if (!empty($cart)): ?>
                    <?php foreach ($cart as $productId => $item): ?>
                        <?php
                        // Fetch the image path for the product
                        $productIdEscaped = mysqli_real_escape_string($conn, $productId);
                        $images_query = "SELECT image_path FROM product_images WHERE product_id = '$productIdEscaped' LIMIT 1";
                        $images_result = mysqli_query($conn, $images_query);

                        if ($images_result && mysqli_num_rows($images_result) > 0) {
                            $image_row = mysqli_fetch_assoc($images_result);
                            $image_path = htmlspecialchars($image_row['image_path']);
                        } else {
                            $image_path = 'default_image.jpg'; // Fallback image
                        }

                        $product_name = htmlspecialchars($item['product_name']);
                        $price = floatval($item['price']);
                        $quantity = intval($item['quantity']);
                        $total_price = $price * $quantity;
                        $subtotal += $total_price;
                        ?>
                        <!-- Start Single Cart Item -->
                        <li class="single-cart-item">
                            <div class="image">
                                <img width="90" height="90" src="adm/<?= $image_path; ?>" alt="<?= $product_name; ?>">
                            </div>
                            <div class="content">
                                <button class="delete-item" data-product-id="<?= $productId; ?>">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
                                        <path d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm0 464c-118.7 0-216-96.1-216-216 0-118.7 96.1-216 216-216 118.7 0 216 96.1 216 216 0 118.7-96.1 216-216 216zm94.8-285.3L281.5 256l69.3 69.3c4.7 4.7 4.7 12.3 0 17l-8.5 8.5c-4.7 4.7-12.3 4.7-17 0L256 281.5l-69.3 69.3c-4.7 4.7-12.3 4.7-17 0l-8.5-8.5c-4.7-4.7-4.7-12.3 0-17l69.3-69.3-69.3-69.3c-4.7-4.7-4.7-12.3 0-17l8.5-8.5c4.7-4.7 12.3-4.7 17 0l69.3 69.3 69.3-69.3c4.7-4.7 12.3-4.7 17 0l8.5 8.5c4.6 4.7 4.6 12.3 0 17z"></path>
                                    </svg>
                                </button>
                                <a href="#" class="title"><?= $product_name; ?></a>
                                <div class="details">
                                    <div class="left">
                                        <span class="price">N<?= number_format($price, 2); ?></span>
                                    </div>
                                    <div class="right">
                                        <div class="product-quantity">
                                            <div class="num-block skin-2">
                                                <span>Quantity: <?= $quantity; ?></span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </li>
                        <!-- End Single Cart Item -->
                    <?php endforeach; ?>
                <?php else: ?>
                    <p>Your cart is empty.</p>
                <?php endif; ?>
            </ul>

            <?php
            // Calculate tax and grand total
            $tax = $subtotal * $tax_rate;
            $grand_total = $subtotal + $tax;
            ?>

            <ul class="cart-info-list">
                <li class="cart-info-single-list">
                    <ul class="cart-info-child">
                        <li class="item"><span class="text-left">Subtotal</span> <span class="text-right">N<?= number_format($subtotal, 2); ?></span></li>
                    </ul>
                </li>
                <li class="cart-info-single-list">
                    <ul class="cart-info-child">
                        <li class="item"><span class="text-left">Tax (7%)</span> <span class="text-right">N<?= number_format($tax, 2); ?></span></li>
                    </ul>
                </li>
                <li class="cart-info-single-list">
                    <ul class="cart-info-child">
                        <li class="item">
                            <span class="text-left">Grand Total</span>
                            <span class="total-price">N<?= number_format($grand_total, 2); ?></span>
                            <a href="checkout.html" class="btn">
                                <span class="icon"><i class="icon icon-carce-check-circle"></i></span>Check out
                            </a>
                        </li>
                    </ul>
                </li>
                <a href="home.php" class="btn">
                    <span class="icon"><i class="icon icon-carce-check-circle"></i></span>Continue
                </a>
            </ul>
        </div>
    </div>
</div>
<!-- ...:::End Cart Section:::... -->

<!-- JavaScript to Delete Item from Cart -->
<script>
document.querySelectorAll('.delete-item').forEach(button => {
    button.addEventListener('click', function () {
        const productId = this.getAttribute('data-product-id');
        let cart = JSON.parse(getCookie('cart') || '{}');
        
        delete cart[productId]; // Remove item from cart

        setCookie('cart', JSON.stringify(cart), 7); // Update cookie
        location.reload(); // Refresh page to reflect changes
    });
});

function getCookie(name) {
    const cookies = document.cookie.split(';').map(cookie => cookie.trim());
    for (const cookie of cookies) {
        if (cookie.startsWith(name + '=')) {
            return decodeURIComponent(cookie.split('=')[1]);
        }
    }
    return '';
}

function setCookie(name, value, days) {
    const date = new Date();
    date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
    document.cookie = `${name}=${encodeURIComponent(value)}; expires=${date.toUTCString()}; path=/`;
}
</script>
