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

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

$total_price = $_SESSION['total_price'] ?? 0;
$coupon_id = $_SESSION['coupon_id'] ?? null;
$user_id = $_SESSION['user_id'] ?? null;
$is_guest = !$user_id;

if ($total_price <= 0) {
    header("Location: cart.php");
    exit();
}

$metadata = [
    'coupon_id' => $coupon_id
];

$customer_email = null;

if ($is_guest) {
    $token = bin2hex(random_bytes(16));
    $metadata['token'] = $token;
    $metadata['guest_name'] = $_POST['name'] ?? '';
    $metadata['guest_email'] = $_POST['email'] ?? '';
    $metadata['guest_address'] = $_POST['address'] ?? '';
    $metadata['guest_phone'] = $_POST['phone'] ?? '';
    $customer_email = $_POST['email'] ?? null;
} else {
    $metadata['user_id'] = $user_id;
}

$checkout_session_params = [
    'payment_method_types' => ['card'],
    'line_items' => [[
        'price_data' => [
            'currency' => 'usd',
            'product_data' => [
                'name' => 'Total Order Amount',
            ],
            'unit_amount' => $total_price * 100, // Amount in cents
        ],
        'quantity' => 1,
    ]],
    'mode' => 'payment',
    'success_url' => 'http://localhost:8080/payment-success.php?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'http://localhost:8080/payment-cancel.php',
    'metadata' => $metadata
];

if ($customer_email) {
    $checkout_session_params['customer_email'] = $customer_email;
}

$checkout_session = \Stripe\Checkout\Session::create($checkout_session_params);

header("Location: " . $checkout_session->url);
