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

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit;
}

$user_id = $_SESSION['user_id'];

// Fetch cart items from database
$stmt = $conn->prepare("
    SELECT c.id AS cart_id, p.id AS product_id, p.product_name AS name, p.price, c.quantity
    FROM carts c
    JOIN products p ON c.product_id = p.id
    WHERE c.user_id = ?
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();
$items = $result->fetch_all(MYSQLI_ASSOC);

if (count($items) == 0) {
    echo "Your cart is empty!";
    exit;
}

// Get form data
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$address_line1 = $_POST['address_line1'];
$address_line2 = $_POST['address_line2'];
$city = $_POST['city'];
$state = $_POST['state'];
$pincode = $_POST['pincode'];
$country = $_POST['country'];
$instructions = $_POST['instructions'];
$payment_method = $_POST['payment_method'];
$total_amount = $_POST['total_amount'];

// Insert order
$stmt = $conn->prepare("
    INSERT INTO orders (user_id, full_name, email, phone, address_line1, address_line2, city, state, pincode, country, instructions, payment_method, total_amount, status)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

// COD: status = pending, Online: status = pending (will update after payment)
$status = ($payment_method == 'COD') ? 'pending' : 'pending';

$stmt->bind_param("issssssssssssd", $user_id, $name, $email, $phone, $address_line1, $address_line2, $city, $state, $pincode, $country, $instructions, $payment_method, $total_amount, $status);
$stmt->execute();
$order_id = $stmt->insert_id;

// Handle payment method
if ($payment_method == 'COD') {
    // Insert order items
    foreach ($items as $item) {
        $stmt = $conn->prepare("
            INSERT INTO order_items (order_id, product_id, quantity, price)
            VALUES (?, ?, ?, ?)
        ");
        $stmt->bind_param("iiid", $order_id, $item['product_id'], $item['quantity'], $item['price']);
        $stmt->execute();
    }

    // Clear cart
    $conn->query("DELETE FROM carts WHERE user_id = $user_id");

    // Redirect to Thank You page
    header("Location: thank_you.php?order_id=$order_id");
    exit;
} else {
    // Online Payment: redirect to a payment gateway or simulated page
    // Here we simulate a payment page:
    $_SESSION['online_payment_order'] = $order_id;
    header("Location: payment_page.php"); // you can create this page
    exit;
}
?>
