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

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

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

if (!$session_id) {
    die("Session ID is missing.");
}

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

try {
    $checkout_session = \Stripe\Checkout\Session::retrieve($session_id);
} catch (\Stripe\Exception\ApiErrorException $e) {
    die("Error retrieving checkout session: " . $e->getMessage());
}

$user_id = $checkout_session->client_reference_id;
$stripe_subscription_id = $checkout_session->subscription;

// Get subscription details
try {
    $subscription = \Stripe\Subscription::retrieve($stripe_subscription_id);
} catch (\Stripe\Exception\ApiErrorException $e) {
    die("Error retrieving subscription details: " . $e->getMessage());
}

$plan = $subscription->items->data[0]->price->lookup_key;
$status = $subscription->status;
$start_date = date('Y-m-d H:i:s', $subscription->current_period_start);
$end_date = date('Y-m-d H:i:s', $subscription->current_period_end);

// Save subscription to database
try {
    $stmt = db()->prepare("INSERT INTO subscriptions (user_id, stripe_subscription_id, plan, status, start_date, end_date) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$user_id, $stripe_subscription_id, $plan, $status, $start_date, $end_date]);
} catch (PDOException $e) {
    // Ideally, you should log this error and handle it gracefully
    die("Database error: " . $e->getMessage());
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Subscription Successful - Veritune</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600&family=Inter:wght@400;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="assets/css/custom.css">
</head>
<body class="bg-light-gray">
    <?php include 'includes/header.php'; ?>

    <main class="container py-5">
        <div class="card text-center">
            <h1>Subscription Successful!</h1>
            <p>Thank you for subscribing to our Pro plan. You now have unlimited certificate generation.</p>
            <a href="dashboard.php" class="btn btn-primary">Go to Dashboard</a>
        </div>
    </main>

    <footer class="footer bg-white">
        <div class="container">
            <p>&copy; <?php echo date("Y"); ?> Veritune. All rights reserved.</p>
        </div>
    </footer>
</body>
</html>
