<?php
require_once './stripe-php_/init.php';
require_once 'db/config.php'; // mysqli $con is used here

// Set your Stripe secret key
\Stripe\Stripe::setApiKey('sk_test_51Qn7DORo551DelC0H2WwHVXAPchbxx4v3cC6nuXO2139cmM0Up1y8nFxF2krYs5KBez9hZp10NdDtLJpDWPxQQih00ufuwCq6A'); // Replace with live key in production

// Get session ID
if (!isset($_GET['id'])) {
    echo "❌ Invalid session. No session ID provided.";
    exit;
}

$session_id = trim($_GET['id']);

try {
    // Fetch Checkout Session
    $session = \Stripe\Checkout\Session::retrieve($session_id);

    if ($session['payment_status'] === 'paid') {
        // Get Payment Intent
        $paymentIntent = \Stripe\PaymentIntent::retrieve($session->payment_intent);

        $amount   = $paymentIntent->amount_received / 100;
        $currency = strtoupper($paymentIntent->currency);
        $email    = $session->customer_details->email ?? 'Not available';

        // 1️⃣ Find subscription in pending_package_subscriptions
        $stmt = $con->prepare("SELECT user_id, package FROM pending_package_subscriptions 
                               WHERE stripe_session_id = ? AND status = 'pending' LIMIT 1");
        $stmt->bind_param("s", $session_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $subscription = $result->fetch_assoc();

        if ($subscription) {
            $user_id = $subscription['user_id'];
            $package = $subscription['package'];

            // 2️⃣ Update subscription to completed
            $update_sub = $con->prepare("UPDATE pending_package_subscriptions 
                                         SET status = 'completed' 
                                         WHERE stripe_session_id = ?");
            $update_sub->bind_param("s", $session_id);
            $update_sub->execute();

            // 3️⃣ Update user package & expiry
            $update_user = $con->prepare("UPDATE users 
                                          SET package = ?, 
                                              package_expiry = DATE_ADD(NOW(), INTERVAL 30 DAY) 
                                          WHERE user_id = ?");
            $update_user->bind_param("si", $package, $user_id);
            $update_user->execute();

            echo "<h2 style='font-size:40px;'>✅ Payment Successful</h2>";
            echo "<p style='font-size:32px;'>Thank you! Your payment of <strong>{$currency} {$amount}</strong> was successful.</p>";
            echo "<p style='font-size:32px;'>Your <strong>{$package}</strong> package has been activated for 30 days.</p>";
            echo "<p style='font-size:32px;'>Receipt sent to: {$email}</p>";

        } else {
            echo "<h2 style='font-size:40px;'>⚠ No Pending Subscription Found</h2>";
            echo "<p style='font-size:32px;'>We could not find a matching pending subscription for this payment.</p>";
        }

        $stmt->close();
    } else {
        echo "<h2 style='font-size:40px;'>⏳ Payment Not Completed</h2>";
        echo "<p style='font-size:32px;'>The payment session exists, but the payment has not been completed.</p>";
    }

} catch (Exception $e) {
    echo "<h2>❌ Error</h2>";
    echo "<p>" . $e->getMessage() . "</p>";
}

// Close DB
$con->close();
?>
