<?php

session_start();

require_once "config/database.php";

$cart = $_SESSION["cart"] ?? [];

if (empty($cart)) {
    header("Location: cart.php");
    exit;
}

$total = 0;


/* PLACE ORDER */

if (isset($_POST["place_order"])) {

    $customer_name = trim($_POST["customer_name"] ?? "");
    $phone1 = trim($_POST["phone1"] ?? "");
    $phone2 = trim($_POST["phone2"] ?? "");
    $address = trim($_POST["address"] ?? "");
    $city = trim($_POST["city"] ?? "");


    /* CALCULATE ORDER TOTAL */

    $order_total = 0;

    foreach ($cart as $item) {

        $order_total +=
            (float)$item["price"] *
            (int)$item["quantity"];
    }


    /* START TRANSACTION */

    $conn->begin_transaction();

    try {

        /* INSERT ORDER */

        $stmt = $conn->prepare("
            INSERT INTO orders
            (
                customer_name,
                phone1,
                phone2,
                address,
                city,
                total_amount
            )
            VALUES (?, ?, ?, ?, ?, ?)
        ");

        if (!$stmt) {
            throw new Exception($conn->error);
        }

        $stmt->bind_param(
            "sssssd",
            $customer_name,
            $phone1,
            $phone2,
            $address,
            $city,
            $order_total
        );

        if (!$stmt->execute()) {
            throw new Exception($stmt->error);
        }


        /* GET NEW ORDER ID */

        $order_id = $conn->insert_id;

        $stmt->close();


        /* INSERT ORDER ITEMS */

        $item_stmt = $conn->prepare("
            INSERT INTO order_items
            (
                order_id,
                product_id,
                variation_id,
                product_name,
                colour,
                image,
                quantity,
                price
            )
            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
        ");

        if (!$item_stmt) {
            throw new Exception($conn->error);
        }


        foreach ($cart as $item) {

            $product_id = (int)$item["product_id"];
            $variation_id = (int)$item["variation_id"];

            $product_name = $item["name"] ?? "";
            $colour = $item["colour"] ?? "";
            $image = $item["image"] ?? "";

            $quantity = (int)$item["quantity"];
            $price = (float)$item["price"];


            $item_stmt->bind_param(
                "iiisssid",
                $order_id,
                $product_id,
                $variation_id,
                $product_name,
                $colour,
                $image,
                $quantity,
                $price
            );


            if (!$item_stmt->execute()) {
                throw new Exception($item_stmt->error);
            }
        }


        $item_stmt->close();


        /* COMMIT */

        $conn->commit();


        /* CLEAR CART */

        unset($_SESSION["cart"]);


        header("Location: order-success.php?id=" . $order_id);
exit;



    } catch (Exception $e) {

        $conn->rollback();

        echo "<script>
                alert('Something went wrong: " .
                htmlspecialchars($e->getMessage()) .
                "');
              </script>";
    }
}

?>

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

<head>

    <meta charset="UTF-8">

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

    <title>Checkout - 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: 25px 45px;

            display: flex;
            justify-content: space-between;
            align-items: center;
        }


        header h2 {
            font-size: 30px;
        }


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


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


        h1 {
            font-size: 42px;
            margin-bottom: 30px;
        }


        .checkout-box {
            background: white;
            border-radius: 15px;
            padding: 30px;

            box-shadow:
                0 4px 15px rgba(0,0,0,0.08);
        }


        .section-title {
            font-size: 26px;
            margin-bottom: 20px;
        }


        .form-group {
            margin-bottom: 18px;
        }


        label {
            display: block;
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 17px;
        }


        input,
        textarea {
            width: 100%;
            padding: 14px;

            border: 1px solid #ccc;
            border-radius: 8px;

            font-size: 16px;
        }


        textarea {
            min-height: 100px;
            resize: vertical;
        }


        .address-note {
            margin-top: 8px;
            color: #666;
            font-size: 14px;
        }


        .order-summary {
            margin-top: 35px;
            padding-top: 25px;

            border-top: 1px solid #ddd;
        }


        .cart-item {
            display: flex;
            align-items: center;
            gap: 20px;

            padding: 15px 0;

            border-bottom: 1px solid #eee;
        }


        .cart-item img {
            width: 90px;
            height: 90px;

            object-fit: cover;

            border-radius: 10px;
            border: 1px solid #ddd;
        }


        .item-info {
            flex: 1;
        }


        .item-info strong {
            font-size: 18px;
        }


        .item-info p {
            margin-top: 5px;
            color: #555;
        }


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


        .total {
            text-align: right;

            font-size: 28px;
            font-weight: bold;

            color: #b8860b;

            margin-top: 20px;
        }


        .place-order {
            width: 100%;

            background: #b8860b;
            color: white;

            border: none;

            padding: 17px;

            border-radius: 8px;

            font-size: 20px;
            font-weight: bold;

            cursor: pointer;

            margin-top: 25px;
        }


        .place-order:hover {
            background: #996f08;
        }


        @media (max-width: 700px) {

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

            nav a {
                margin: 0 8px;
            }

            h1 {
                font-size: 32px;
            }

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

        }

    </style>

</head>


<body>


<header>

    <h2>MUTHU JEWELLERS 💎</h2>

    <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>
        Checkout 💳
    </h1>


    <div class="checkout-box">


        <h2 class="section-title">
            Customer Details
        </h2>


        <form method="POST" action="">


            <div class="form-group">

                <label>
                    Full Name *
                </label>

                <input
                    type="text"
                    name="customer_name"
                    placeholder="Enter your full name"
                    required
                >

            </div>


            <div class="form-group">

                <label>
                    Phone Number 1 *
                </label>

                <input
                    type="tel"
                    name="phone1"
                    placeholder="Enter your primary phone number"
                    required
                >

            </div>


            <div class="form-group">

                <label>
                    Phone Number 2 *
                </label>

                <input
                    type="tel"
                    name="phone2"
                    placeholder="Enter an alternative phone number"
                    required
                >

            </div>


            <div class="form-group">

                <label>
                    Delivery Address *
                </label>

                <textarea
                    name="address"
                    placeholder="Enter your complete delivery address"
                    required
                ></textarea>


                <p class="address-note">

                    📌 Please enter your complete and correct
                    delivery address, including house number,
                    street, town/city, and a nearby landmark.

                </p>

            </div>


            <div class="form-group">

                <label>
                    Nearest City / Town *
                </label>

                <input
                    type="text"
                    name="city"
                    placeholder="Enter your nearest city or town"
                    required
                >

            </div>


            <div class="order-summary">


                <h2 class="section-title">
                    Order Summary
                </h2>


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

                    <?php

                    $item_total =
                        $item["price"] *
                        $item["quantity"];

                    $total += $item_total;

                    ?>


                    <div class="cart-item">


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

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

                        <?php endif; ?>


                        <div class="item-info">

                            <strong>

                                <?= htmlspecialchars(
                                    $item["name"]
                                ) ?>

                            </strong>


                            <p>

                                Colour:

                                <strong>

                                    <?= htmlspecialchars(
                                        $item["colour"] ?? "N/A"
                                    ) ?>

                                </strong>

                            </p>


                            <p>

                                Quantity:

                                <?= (int)$item["quantity"] ?>

                            </p>


                            <p class="item-price">

                                Rs.

                                <?= number_format(
                                    $item_total,
                                    2
                                ) ?>

                            </p>

                        </div>


                    </div>


                <?php endforeach; ?>


                <div class="total">

                    Total:
                    Rs.
                    <?= number_format($total, 2) ?>

                </div>


                <button
                    type="submit"
                    name="place_order"
                    class="place-order"
                >

                    Place Order 🛍️

                </button>


            </div>


        </form>


    </div>


</div>


</body>

</html>