<?php
require_once 'db.php';
require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('your_secret_key');

$data = json_decode(file_get_contents('php://input'), true);
$cart = $data ?? [];

$line_items = [];
$total = 0;

foreach($cart as $product_id => $quantity) {
    $stmt = $db->prepare("SELECT * FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    
    if($product) {
        $line_items[] = [
            'price_data' => [
                'currency' => 'usd',
                'product_data' => [
                    'name' => $product['title'],
                ],
                'unit_amount' => $product['price'] * 100,
            ],
            'quantity' => $quantity,
        ];
        $total += $product['price'] * $quantity;
    }
}

$checkout_session = \Stripe\Checkout\Session::create([
    'payment_method_types' => ['card'],
    'line_items' => $line_items,
    'mode' => 'payment',
    'success_url' => 'https://your-domain.com/success.php',
    'cancel_url' => 'https://your-domain.com/cancel.php',
]);

$stmt = $db->prepare("INSERT INTO orders (total_amount, status, stripe_session_id) VALUES (?, ?, ?)");
$stmt->execute([$total, 'pending', $checkout_session->id]);
$order_id = $db->lastInsertId();

foreach($cart as $product_id => $quantity) {
    $stmt = $db->prepare("SELECT price FROM products WHERE id = ?");
    $stmt->execute([$product_id]);
    $product = $stmt->fetch();
    
    if($product) {
        $stmt = $db->prepare("INSERT INTO order_items (order_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
        $stmt->execute([$order_id, $product_id, $quantity, $product['price']]);
    }
}

echo json_encode(['id' => $checkout_session->id]);