<?php
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../../config/config.php';

// Ensure JSON header return format
header('Content-Type: application/json');

if (!isset($_SESSION['user_id']) || !isset($_SESSION['invoice_data'])) {
    echo json_encode(['error' => 'Invoice session expired or unauthorized.']);
    exit();
}

$invoice = $_SESSION['invoice_data'];

// Fetch live Stripe Secret Key from Database
$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'stripe_secret_key'");
$secret_key = $stmt->fetchColumn();

// Simple cURL request initializing a Stripe Checkout Session
$url = 'https://api.stripe.com/v1/checkout/sessions';

$data = [
    'payment_method_types' => ['card'],
    'line_items' => [[
        'price_data' => [
            'currency' => 'usd',
            'product_data' => [
                'name' => $invoice['plan_name'],
            ],
            'unit_amount' => intval($invoice['amount'] * 100), // Stripe processes in cents
        ],
        'quantity' => 1,
    ]],
    'mode' => 'payment',
    'success_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/football-pred-pro/public/user/gateways/verify-stripe.php?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'https://' . $_SERVER['HTTP_HOST'] . '/football-pred-pro/public/user/billing.php',
];

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Basic ' . base64_encode($secret_key . ':')
]);

$response = curl_exec($ch);
curl_close($ch);

$session = json_decode($response, true);

if (isset($session['id'])) {
    echo json_encode(['id' => $session['id']]);
} else {
    echo json_encode(['error' => $session['error']['message'] ?? 'Unable to initialize payment gateway session.']);
}
exit();
?>