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

header('Content-Type: application/json');

if (!isset($_POST['orderID'])) {
    echo json_encode(['error' => 'Invalid request.']);
    exit();
}

$orderID = $_POST['orderID'];
$user_id = $_SESSION['user_id'] ?? null;
$is_guest = !$user_id;
$session_id = session_id();

// Helper function to get PayPal access token
function get_paypal_access_token($clientId, $secret, $apiBase) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "$apiBase/v1/oauth2/token");
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERPWD, "$clientId:$secret");
    curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=client_credentials");
    $result = curl_exec($ch);
    curl_close($ch);
    
    if (empty($result)) return null;
    
    $json = json_decode($result);
    return $json->access_token ?? null;
}

$accessToken = get_paypal_access_token($paypalClientId, $paypalSecret, $paypalApiBase);

if (!$accessToken) {
    echo json_encode(['error' => 'Could not authenticate with PayPal.']);
    exit();
}

// Capture payment
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$paypalApiBase/v2/checkout/orders/$orderID/capture");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Content-Type: application/json",
    "Authorization: Bearer $accessToken"
]);

$result = curl_exec($ch);
curl_close($ch);
$details = json_decode($result);

if (isset($details->status) && $details->status == 'COMPLETED') {
    $pdo = db();
    
    $delivery_address = $_POST['address'] ?? 'N/A';
    $phone_number = $_POST['phone'] ?? 'N/A';
    $guest_name = null;
    $guest_email = null;
    $guest_token = null;

    if ($is_guest) {
        $guest_name = $_POST['name'] ?? '';
        $guest_email = $_POST['email'] ?? '';
        $cart_identifier = $session_id;
        $cart_column = 'session_id';
        $guest_token = bin2hex(random_bytes(16)); // Generate a unique token for guest orders
    } else {
        $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)) {
        echo json_encode(['error' => 'Your cart is empty.']);
        exit();
    }

    $total_price = $_SESSION['total_price'] ?? 0;
    $discount_amount = $_SESSION['discount_amount'] ?? 0;
    $coupon_id = $_SESSION['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', $orderID, $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;
    }

    echo json_encode(['success' => true, 'order_id' => $order_id]);

} else {
    error_log('PayPal Capture Failed: ' . print_r($details, true));
    echo json_encode(['error' => 'Payment failed. Please try again.']);
}