<?php
session_start();
require_once 'db/config.php';
require_once 'vendor/autoload.php';
require_once 'includes/api_keys.php';

if (!isset($_GET['session_id'])) {
    header("Location: index.php");
    exit();
}

$stripe_session_id = $_GET['session_id'];
$pdo = db();

\Stripe\Stripe::setApiKey($stripeSecretKey);

try {
    $checkout_session = \Stripe\Checkout\Session::retrieve($stripe_session_id);
    $metadata = $checkout_session->metadata;
    $user_id = $metadata->user_id;
    $coupon_id = $metadata->coupon_id;

    if ($checkout_session->payment_status == 'paid') {
        // Fetch user's address
        $stmt = $pdo->prepare("SELECT address FROM users WHERE id = ?");
        $stmt->execute([$user_id]);
        $user = $stmt->fetch();
        $delivery_address = $user ? $user['address'] : 'N/A';

        // Fetch cart items
        $stmt = $pdo->prepare("SELECT c.*, mi.price, mi.restaurant_id FROM cart c JOIN menu_items mi ON c.menu_item_id = mi.id WHERE c.user_id = ?");
        $stmt->execute([$user_id]);
        $cart_items = $stmt->fetchAll();

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

        $total_price = $_SESSION['total_price'] ?? 0;
        $discount_amount = $_SESSION['discount_amount'] ?? 0;
        $restaurant_id = $cart_items[0]['restaurant_id']; // Assuming order from one restaurant

        // Create order
        $stmt = $pdo->prepare("INSERT INTO orders (user_id, restaurant_id, total_price, status, stripe_session_id, delivery_address, coupon_id, discount_amount) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $restaurant_id, $total_price, 'paid', $stripe_session_id, $delivery_address, $coupon_id, $discount_amount]);
        $order_id = $pdo->lastInsertId();

        // Insert order items
        $stmt = $pdo->prepare("INSERT INTO order_items (order_id, menu_item_id, quantity, price) VALUES (?, ?, ?, ?)");
        foreach ($cart_items as $item) {
            $stmt->execute([$order_id, $item['menu_item_id'], $item['quantity'], $item['price']]);
        }

        // Clear cart
        $stmt = $pdo->prepare("DELETE FROM cart WHERE user_id = ?");
        $stmt->execute([$user_id]);

        // Clear coupon session variables
        unset($_SESSION['coupon_id']);
        unset($_SESSION['coupon_code']);
        unset($_SESSION['discount_percentage']);
        unset($_SESSION['total_price']);
        unset($_SESSION['discount_amount']);
        unset($_SESSION['subtotal']);


        $_SESSION['order_id'] = $order_id;
        header("Location: order_confirmation.php");
        exit();

    } else {
        header("Location: payment-cancel.php");
        exit();
    }
} catch (\Stripe\Exception\ApiErrorException $e) {
    // Handle Stripe API errors
    error_log($e->getMessage());
    header("Location: payment-cancel.php");
    exit();
}
