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

if (!isset($_SESSION['user_id']) || !isset($_GET['session_id'])) {
    header("Location: ../user/billing.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$session_id = filter_input(INPUT_GET, 'session_id', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'stripe_secret_key'");
$secret_key = $stmt->fetchColumn();

// Use basic cURL to verify the Stripe Checkout Session
$ch = curl_init("https://api.stripe.com/v1/checkout/sessions/" . $session_id);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
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['payment_status']) && $session['payment_status'] === 'paid') {
    $invoice = $_SESSION['invoice_data'] ?? null;
    
    if ($invoice && $invoice['user_id'] == $user_id) {
        $plan_id = $invoice['plan_id'];
        $amount = $invoice['amount'];
        $expiry_date = date('Y-m-d H:i:s', strtotime("+" . $invoice['duration'] . " days"));

        // Update database subscription ledger
        $stmt = $pdo->prepare("INSERT INTO user_subscriptions (user_id, plan_id, expires_at, is_active) 
                               VALUES (?, ?, ?, 1) 
                               ON DUPLICATE KEY UPDATE plan_id = ?, expires_at = ?, is_active = 1");
        $stmt->execute([$user_id, $plan_id, $expiry_date, $plan_id, $expiry_date]);

        // Log transaction ledger
        $trans_stmt = $pdo->prepare("INSERT INTO transactions (user_id, plan_id, amount_paid, payment_method, status) 
                                     VALUES (?, ?, ?, 'Stripe (Automated)', 'success')");
        $trans_stmt->execute([$user_id, $plan_id, $amount]);

        unset($_SESSION['invoice_data']);
        $_SESSION['success_msg'] = "Membership package successfully activated via Stripe!";
    } else {
        $_SESSION['error_msg'] = "Session validation dropped. Please contact support.";
    }
} else {
    $_SESSION['error_msg'] = "Stripe verification failed or invoice is unpaid.";
}

header("Location: ../user/billing.php");
exit();
?>