<?php
session_start();
require_once 'db/config.php';
require_once 'stripe-php/init.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$plan = $_GET['plan'] ?? null;

if ($plan !== 'pro') {
    die("Invalid plan selected.");
}

// Replace with your Stripe secret key
$stripeSecretKey = 'sk_test_51SnbE1DXiGqo6jDypbXwuZkNZVV4g4KB9rkixQzchrtzzjd8kGYON1QIweBLYHG1mNqrGxjCuvQBeVRsCyhAI58400CllOBiwh';
\Stripe\Stripe::setApiKey($stripeSecretKey);

// Replace with your actual Price ID from your Stripe Dashboard
$priceId = 'price_1PeioMDXiGqo6jDyv4oMh940'; // PLACEHOLDER

$user_id = $_SESSION['user_id'];

// Get user's email
$stmt = db()->prepare("SELECT email FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    die("User not found.");
}

$checkout_session = \Stripe\Checkout\Session::create([
    'customer_email' => $user['email'],
    'payment_method_types' => ['card'],
    'line_items' => [[
        'price' => $priceId,
        'quantity' => 1,
    ]],
    'mode' => 'subscription',
    'success_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/success.php?session_id={CHECKOUT_SESSION_ID}',
    'cancel_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/cancel.php',
    'client_reference_id' => $user_id
]);

header("HTTP/1.1 303 See Other");
header("Location: " . $checkout_session->url);
