<?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();
$session_id = session_id();

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

try {
    $checkout_session = \Stripe\Checkout\Session::retrieve($stripe_session_id);
    $metadata = $checkout_session->metadata;
    $user_id = $metadata->user_id ?? null;
    $is_guest = !$user_id;

    if ($checkout_session->payment_status == 'paid') {
        $delivery_address = null;
        $phone_number = null;
        $guest_name = null;
        $guest_email = null;
        $guest_token = null;

        if ($is_guest) {
            $guest_name = $metadata->guest_name ?? '';
            $guest_email = $metadata->guest_email ?? '';
            $delivery_address = $metadata->guest_address ?? 'N/A';
            $phone_number = $metadata->guest_phone ?? 'N/A';
            $cart_identifier = $session_id;
            $cart_column = 'session_id';
            $guest_token = $metadata->token ?? null; // Use token from metadata
        } else {
            $stmt = $pdo->prepare("SELECT address, phone FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            $delivery_address = $user ? $user['address'] : 'N/A';
            $phone_number = $user ? $user['phone'] : 'N/A';
            $cart_identifier = $user_id;
            $cart_column = 'user_id';
        }

        // 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.$cart_column = ?");
        $stmt->execute([$cart_identifier]);
        $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;
        $coupon_id = $metadata->coupon_id ?? null;
        $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, phone_number, coupon_id, discount_amount, guest_name, guest_email, token) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([$user_id, $restaurant_id, $total_price, 'paid', $stripe_session_id, $delivery_address, $phone_number, $coupon_id, $discount_amount, $guest_name, $guest_email, $guest_token]);
        $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 $cart_column = ?");
        $stmt->execute([$cart_identifier]);

        // 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;
        if ($is_guest) {
            $_SESSION['token'] = $guest_token;
        }

        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();
}
