<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include "db.php";

/* USER MUST BE LOGGED IN */
if (!isset($_SESSION['user_id'])) {
    header("Location: auth.php");
    exit;
}

/* CART MUST NOT BE EMPTY */
if (empty($_SESSION['cart'])) {
    die("Cart is empty.");
}

/* ---------------------------
   GET CHECKOUT FORM DATA
--------------------------- */
$country   = $_POST['country'] ?? "";
$first     = $_POST['first_name'] ?? "";
$last      = $_POST['last_name'] ?? "";
$address   = $_POST['address'] ?? "";
$apartment = $_POST['apartment'] ?? "";
$city      = $_POST['city'] ?? "";
$pincode   = $_POST['pincode'] ?? "";
$phone     = $_POST['phone'] ?? "";

$state = ($country === "India")
    ? ($_POST['state'] ?? "")
    : ($_POST['state_text'] ?? "");

/* REQUIRED VALIDATION */
if (
    $country === "" || $first === "" || $last === "" ||
    $address === "" || $city === "" ||
    $pincode === "" || $phone === ""
) {
    die("Missing required checkout fields.");
}

/* ---------------------------
   CALCULATE TOTAL
--------------------------- */
$user_id = $_SESSION['user_id'];
$total_amount = 0;

foreach ($_SESSION['cart'] as $item) {
    $total_amount += $item['qty'] * $item['price'];
}

/* ---------------------------
   INSERT ORDER
--------------------------- */
$order_stmt = $pdo->prepare("
    INSERT INTO orders 
    (user_id, first_name, last_name, phone, country, state, city, address, apartment, pincode, total_amount, payment_status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$order_stmt->execute([
    $user_id,
    $first,
    $last,
    $phone,
    $country,
    $state,
    $city,
    $address,
    $apartment,
    $pincode,
    $total_amount,
    "pending"
]);

$order_id = $pdo->lastInsertId();

/* ---------------------------
   INSERT ORDER ITEMS (WITH VARIANTS)
--------------------------- */
$item_stmt = $pdo->prepare("
    INSERT INTO order_items 
    (order_id, product_id, qty, price, variant_details)
    VALUES (?, ?, ?, ?, ?)
");

foreach ($_SESSION['cart'] as $c) {

    // 🔥 BUILD VARIANT STRING
    $variant_details = "Size: {$c['size']} | Garlic: {$c['garlic']} | Spice: {$c['spice']}";

    $item_stmt->execute([
        $order_id,
        $c['product_id'],
        $c['qty'],
        $c['price'],
        $variant_details
    ]);
}

/* ---------------------------
   SAVE ORDER SESSION
--------------------------- */
$_SESSION['current_order_id'] = $order_id;
$_SESSION['order_amount']    = $total_amount;

/* ---------------------------
   REDIRECT TO PAYMENT GATEWAY
--------------------------- */
header("Location: razorpay.php");
exit;
