<?php
session_start();
include 'db.php';

// ADD TO CART
if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['product_id'])){
    $id = (int)$_POST['product_id'];
    $qty = (int)$_POST['qty'];

    if(!isset($_SESSION['cart'])){
        $_SESSION['cart'] = [];
    }

    if(isset($_SESSION['cart'][$id])){
        $_SESSION['cart'][$id] += $qty;
    } else {
        $_SESSION['cart'][$id] = $qty;
    }

    header("Location: cart.php");
    exit;
}

// REMOVE ITEM
if(isset($_GET['remove'])){
    $id = (int)$_GET['remove'];
    unset($_SESSION['cart'][$id]);
}

// UPDATE QTY
if(isset($_POST['update_qty'])){
    foreach($_POST['qty'] as $id => $q){
        $_SESSION['cart'][$id] = max(1, (int)$q);
    }
}

include 'include/header.php'; // ✅ include after session start
?>

<style>
/* Styling for the Cart Page */
.cart-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 30px;
}

.cart-card {
    background-color: #fff;
    padding: 20px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    margin-top: 20px;
}

.cart-table {
    width: 100%;
    border-collapse: collapse;
}

.cart-table th,
.cart-table td {
    padding: 15px;
    text-align: center;
}

.cart-table th {
    background-color: #f7f7f7;
    font-size: 16px;
    color: #555;
}

.cart-item {
    display: flex;
    align-items: center;
}

.cart-img {
    width: 80px;
    height: 100px;
    object-fit: cover;
    border-radius: 10px;
    margin-right: 15px;
}

.cart-item-details {
    font-size: 14px;
    color: #333;
}

.qty-column {
    display: flex;
    justify-content: center;
    align-items: center;
}

/* New Qty Box Styling */
.qty-box {
    display: inline-flex;
    align-items: center;
    border: 1px solid #ccc;
    border-radius: 12px;
    overflow: hidden;
    width: 140px;
    justify-content: space-between;
    padding: 5px 10px;
    background: #fff;
}

.qty-box button {
    border: none;
    background: transparent;
    font-size: 20px;
    width: 30px;
    height: 30px;
    padding: 0;
    cursor: pointer;
    color: #333;
    margin: 0;
}

.qty-box input {
    width: 40px;
    text-align: center;
    border: none;
    outline: none;
    font-size: 16px;
    font-weight: 500;
    background: transparent;
}

/* Remove button styles */
.remove-btn-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.remove-btn.small-btn {
    color: red;
    font-size: 16px;
    text-decoration: none;
    padding: 5px;
}

.remove-btn.small-btn svg {
    width: 16px;
    height: 16px;
}

.remove-btn:hover {
    color: darkred;
}

.total-container {
    text-align: right;
    margin-top: 20px;
}

.total-container h4 {
    font-size: 1.2rem;
    font-weight: bold;
}

.total-container p {
    font-size: 0.9rem;
    color: #555;
}

.checkout-btn {
    background: black;
    color: white;
    padding: 15px;
    border-radius: 30px;
    width: 100%;
    border: none;
    cursor: pointer;
    text-align: center;
}

tbody,
td,
tfoot,
th,
thead,
tr {
    border-color: inherit;
    border-style: none !important;
    border-width: 0;
}
</style>
<div class="container py-5 cart-container">
    <h2>Your Cart</h2>

    <?php if(!empty($_SESSION['cart'])): ?>
    <form method="POST">
        <div class="card cart-card">
            <table class="table cart-table">
                <thead>
                    <tr>
                        <th style="border: none; text-align:left;">Product</th>
                        <th style="border: none; text-align: center;">Quantity</th>
                        <th style="border: none; text-align: center;">Total</th>
                    </tr>
                </thead>
                <tbody>
                    <?php
                    $total = 0;
                    foreach($_SESSION['cart'] as $id => $qty):
                        $product = $conn->query("SELECT * FROM products WHERE id=$id")->fetch_assoc();
                        $price = $product['sale_price'] ?: $product['price'];
                        $sub = $price * $qty;
                        $total += $sub;
                    ?>
                    <tr>
                        <td>
                            <div class="cart-item">
                                <img src="assets/images/products/<?= $product['pro_image'] ?>" class="cart-img">
                                <div class="cart-item-details">
                                    <strong><?= $product['pro_title'] ?></strong><br>
                                    Rs. <?= number_format($price, 2) ?>
                                </div>
                            </div>
                        </td>
                        <td class="qty-column">
                            <div class="qty-box">
                                <button class="btn-qty" data-id="<?= $id ?>" data-change="-1">-</button>
                                <input type="number" id="qty-<?= $id ?>" value="<?= $qty ?>" min="1" readonly>
                                <button class="btn-qty" data-id="<?= $id ?>" data-change="1">+</button>
                            </div>
                            <a href="cart.php?remove=<?= $id ?>" class="remove-btn small-btn">
                                <svg xmlns="http://www.w3.org/2000/svg" class="icon icon-remove" viewBox="0 0 16 16">
                                    <path fill="currentColor"
                                        d="M14 3h-3.53a3.07 3.07 0 0 0-.6-1.65C9.44.82 8.8.5 8 .5s-1.44.32-1.87.85A3.06 3.06 0 0 0 5.53 3H2a.5.5 0 0 0 0 1h1.25v10c0 .28.22.5.5.5h8.5a.5.5 0 0 0 .5-.5V4H14a.5.5 0 0 0 0-1M6.91 1.98c.23-.29.58-.48 1.09-.48s.85.19 1.09.48c.2.24.3.6.36 1.02h-2.9c.05-.42.17-.78.36-1.02m4.84 11.52h-7.5V4h7.5z">
                                    </path>
                                    <path fill="currentColor"
                                        d="M6.55 5.25a.5.5 0 0 0-.5.5v6a.5.5 0 0 0 1 0v-6a.5.5 0 0 0-.5-.5m2.9 0a.5.5 0 0 0-.5.5v6a.5.5 0 0 0 1 0v-6a.5.5 0 0 0-.5-.5">
                                    </path>
                                </svg>
                            </a>
                        </td>
                        <td>
                            Rs. <?= number_format($sub, 2) ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Total Calculation -->
        <div class="row mt-5">
            <div class="col-md-4"></div>
            <div class="col-md-4"></div>

            <div class="col-md-4">
                <div class="total-container">
                    <h4>Estimated Total: Rs. <?= number_format($total, 2) ?></h4>
                    <p>Taxes, discounts, and shipping calculated at checkout.</p>
                    <a href="checkout.php" class="checkout-btn w-100">Check out</a>
                </div>
            </div>
        </div>


    </form>
    <?php else: ?>
    <div class="text-center py-5">
        <h3>Your cart is empty</h3>
        <a href="shop.php" class="checkout-btn" style="width:auto; padding:10px 30px; margin-top:20px;">Continue
            Shopping</a>
    </div>
    <?php endif; ?>
</div>

<script>
function changeQty(val, id) {
    let qtyInput = document.getElementById("qty-" + id);
    let current = parseInt(qtyInput.value) || 1;
    current += val;
    if (current < 1) current = 1;
    qtyInput.value = current;
}
</script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {

    $(".btn-qty").click(function() {
        let id = $(this).data("id");
        let change = parseInt($(this).data("change"));
        let qtyInput = $("#qty-" + id);
        let currentQty = parseInt(qtyInput.val()) || 1;
        currentQty += change;
        if (currentQty < 1) currentQty = 1;
        qtyInput.val(currentQty);

        // AJAX to update session and calculate totals
        $.ajax({
            url: "update_cart.php",
            type: "POST",
            data: {
                id: id,
                qty: currentQty
            },
            dataType: "json",
            success: function(data) {
                $("#subtotal-" + id).text("Rs. " + data.subtotal);
                $("#total").text("Estimated Total: Rs. " + data.total);
            }
        });
    });

});
</script>
<?php include 'include/footer.php'; ?>