<?php
session_start();

require_once "config/database.php";

/* ADD PRODUCT TO CART */
if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $product_id = isset($_POST["product_id"])
        ? (int)$_POST["product_id"]
        : 0;

    $variation_id = isset($_POST["variation_id"])
        ? (int)$_POST["variation_id"]
        : 0;

    $quantity = isset($_POST["quantity"])
        ? (int)$_POST["quantity"]
        : 1;

    if ($product_id <= 0 || $variation_id <= 0 || $quantity <= 0) {
        die("Invalid cart information.");
    }

    /* GET PRODUCT */
    $stmt = $conn->prepare(
        "SELECT * FROM products WHERE id = ?"
    );

    $stmt->bind_param("i", $product_id);
    $stmt->execute();

    $product_result = $stmt->get_result();
    $product = $product_result->fetch_assoc();

    $stmt->close();

    if (!$product) {
        die("Product not found.");
    }

    /* GET COLOUR VARIATION */
    $variation_stmt = $conn->prepare(
        "SELECT * FROM product_variations
         WHERE id = ? AND product_id = ?"
    );

    $variation_stmt->bind_param(
        "ii",
        $variation_id,
        $product_id
    );

    $variation_stmt->execute();

    $variation_result = $variation_stmt->get_result();
    $variation = $variation_result->fetch_assoc();

    $variation_stmt->close();

    if (!$variation) {
        die("Colour variation not found.");
    }

    /* CHECK STOCK */
    if ($quantity > (int)$variation["stock"]) {
        die("Not enough stock available.");
    }

    /* CREATE CART SESSION */
    if (!isset($_SESSION["cart"])) {
        $_SESSION["cart"] = [];
    }

    $cart_key = $product_id . "_" . $variation_id;

    /* ADD / UPDATE CART */
    if (isset($_SESSION["cart"][$cart_key])) {

        $new_quantity =
            $_SESSION["cart"][$cart_key]["quantity"]
            + $quantity;

        if ($new_quantity > (int)$variation["stock"]) {
            die("Not enough stock available.");
        }

        $_SESSION["cart"][$cart_key]["quantity"] =
            $new_quantity;

    } else {

        $_SESSION["cart"][$cart_key] = [

            "product_id" => $product_id,

            "variation_id" => $variation_id,

            "name" => $product["name"],

            "price" => (float)$product["price"],

            "colour" => $variation["colour"],

            "image" => $variation["image"],

            "quantity" => $quantity

        ];
    }
}


/* REMOVE ITEM */
if (isset($_GET["remove"])) {

    $remove_key = $_GET["remove"];

    if (isset($_SESSION["cart"][$remove_key])) {

        unset($_SESSION["cart"][$remove_key]);
    }
}


/* CART ITEMS */
$cart = $_SESSION["cart"] ?? [];


/* TOTAL */
$total = 0;

foreach ($cart as $item) {

    $total +=
        $item["price"] * $item["quantity"];
}

?>

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

<head>

    <meta charset="UTF-8">

    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">

    <title>
        Shopping Cart - Muthu Jewellers
    </title>

    <style>

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            font-family: Arial, sans-serif;
            background: #f5f5f5;
            color: #111;
        }

        header {
    background: #111;
    color: white;
    padding: 18px 7%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

header h2 {
    font-size: 28px;
}

.logo img {
    width: 190px;
    height: 55px;
    object-fit: contain;
    display: block;
}

nav a {
    color: white;
    text-decoration: none;
    margin-left: 30px;
    font-size: 18px;
}

nav a:hover {
    color: #d4af37;
}

        .container {
            max-width: 1100px;
            margin: 40px auto;
            padding: 25px;
        }

        h1 {
            font-size: 36px;
            margin-bottom: 25px;
        }

        .cart-box {
            background: white;
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
        }

        .cart-item {
            display: flex;
            gap: 20px;
            align-items: center;
            padding: 20px 0;
            border-bottom: 1px solid #ddd;
        }

        .cart-item img {
            width: 120px;
            height: 120px;
            object-fit: cover;
            border-radius: 10px;
        }

        .item-info {
            flex: 1;
        }

        .item-info h2 {
            font-size: 23px;
            margin-bottom: 8px;
        }

        .item-info p {
            margin-bottom: 6px;
            color: #555;
            font-size: 16px;
        }

        .item-price {
            color: #b8860b;
            font-weight: bold;
            font-size: 20px;
        }

        .remove-btn {
            background: #c00000;
            color: white;
            padding: 9px 15px;
            border-radius: 7px;
            text-decoration: none;
        }

        .remove-btn:hover {
            background: #900000;
        }

        .cart-total {
            text-align: right;
            margin-top: 25px;
            font-size: 25px;
            font-weight: bold;
        }

        .checkout-btn {
            display: block;
            text-align: center;
            margin-top: 20px;
            padding: 15px;
            background: #b8860b;
            color: white;
            text-decoration: none;
            border-radius: 8px;
            font-size: 19px;
            font-weight: bold;
        }

        .checkout-btn:hover {
            background: #946f08;
        }

        .empty {
            text-align: center;
            padding: 50px;
            font-size: 22px;
            color: #555;
        }

        .shop-btn {
            display: inline-block;
            margin-top: 20px;
            background: #111;
            color: white;
            padding: 12px 20px;
            border-radius: 7px;
            text-decoration: none;
        }

        @media (max-width: 700px) {

            header {
                flex-direction: column;
                gap: 15px;
            }

            nav a {
                margin: 0 8px;
            }

            .cart-item {
                flex-direction: column;
                align-items: flex-start;
            }

        }

    </style>

</head>

<body>

<header>

    <a href="index.php" class="logo">
    <img src="images/logo.png" alt="Muthu Jewellers Logo">
</a>

    <nav>

        <a href="index.php">
            Home
        </a>

        <a href="shop.php">
            Shop
        </a>

        <a href="cart.php">
            Cart 🛒
        </a>

    </nav>

</header>


<div class="container">

    <h1>
        🛒 Shopping Cart
    </h1>

    <?php if (empty($cart)): ?>

        <div class="cart-box">

            <div class="empty">

                Your cart is empty.

                <br>

                <a
                    href="shop.php"
                    class="shop-btn"
                >
                    Continue Shopping
                </a>

            </div>

        </div>

    <?php else: ?>

        <div class="cart-box">

            <?php foreach ($cart as $key => $item): ?>

                <div class="cart-item">

                    <?php if (!empty($item["image"])): ?>

                        <img
                            src="assets/images/<?php echo htmlspecialchars($item["image"]); ?>"
                            alt="<?php echo htmlspecialchars($item["name"]); ?>"
                        >

                    <?php endif; ?>


                    <div class="item-info">

                        <h2>
                            <?php
                            echo htmlspecialchars(
                                $item["name"]
                            );
                            ?>
                        </h2>

                        <p>
                            Colour:
                            <strong>
                                <?php
                                echo htmlspecialchars(
                                    $item["colour"]
                                );
                                ?>
                            </strong>
                        </p>

                        <p>
                            Quantity:
                            <?php
                            echo (int)$item["quantity"];
                            ?>
                        </p>

                        <p class="item-price">

                            Rs.
                            <?php
                            echo number_format(
                                $item["price"],
                                2
                            );
                            ?>

                        </p>

                    </div>


                    <a
                        href="cart.php?remove=<?php echo urlencode($key); ?>"
                        class="remove-btn"
                        onclick="return confirm('Remove this item from cart?');"
                    >
                        🗑 Remove
                    </a>

                </div>

            <?php endforeach; ?>


            <div class="cart-total">

                Total:
                Rs.
                <?php
                echo number_format(
                    $total,
                    2
                );
                ?>

            </div>


            <a
                href="checkout.php"
                class="checkout-btn"
            >
                Proceed to Checkout 💳
            </a>

        </div>

    <?php endif; ?>

</div>

</body>

</html>