<?php
session_start();
include "config/db.php";

if (!isset($_SESSION['user_id']) || empty($_SESSION['cart'])) {
    die("Invalid access");
}

$user_id = $_SESSION['user_id'];

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

mysqli_query($conn,
  "INSERT INTO orders (user_id, total_price)
   VALUES ('$user_id', '$total')"
);

$order_id = mysqli_insert_id($conn);

foreach ($_SESSION['cart'] as $item) {
    mysqli_query($conn,
      "INSERT INTO order_items (order_id, product_name, price, quantity)
       VALUES ('$order_id',
       '{$item['name']}',
       '{$item['price']}',
       '{$item['qty']}')"
    );
}

unset($_SESSION['cart']);

echo "<h2>Payment Successful 🎉</h2>";
echo "<a href='user/my-orders.php'>View Orders</a>";
