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

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

$invoice = $_SESSION['invoice_data'];
$user_id = $_SESSION['user_id'];

// Fetch Paystack public key
$stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'paystack_public_key'");
$public_key = $stmt->fetchColumn();

// Fetch user email and name
$user_stmt = $pdo->prepare("SELECT email, full_name FROM users WHERE id = ?");
$user_stmt->execute([$user_id]);
$u_row = $user_stmt->fetch(PDO::FETCH_ASSOC);
$email = $u_row['email'] ?? 'user@example.com';
$full_name = $u_row['full_name'] ?? 'User';

// ============================================================
// CURRENCY CONVERSION: USD → NGN
// ============================================================
$rate_stmt = $pdo->query("SELECT key_value FROM payment_settings WHERE key_name = 'usd_ngn_rate'");
$rate = $rate_stmt->fetchColumn();
if (!$rate || $rate <= 0) {
    $rate = 1500.00; // Fallback
}

$amount_usd = $invoice['amount'];
$amount_ngn = $amount_usd * $rate;
$amount_kobo = intval($amount_ngn * 100); // Paystack expects amount in kobo (1/100 of NGN)

// Generate a unique reference
$reference = 'PAY-' . strtoupper(uniqid() . bin2hex(random_bytes(4)));

// ============================================================
// STORE PENDING PAYMENT (WITH BOTH USD AND NGN)
// ============================================================
// Check if `ngn_amount` column exists; add it if not (or we can handle by checking columns)
// For simplicity, we'll assume the column exists – we'll add it via ALTER TABLE if needed.
try {
    $stmt = $pdo->prepare("INSERT INTO pending_payments (user_id, plan_id, reference, amount, ngn_amount, status) VALUES (?, ?, ?, ?, ?, 'pending')");
    $stmt->execute([$user_id, $invoice['plan_id'], $reference, $amount_usd, $amount_ngn]);
} catch (PDOException $e) {
    // If the column doesn't exist, fallback to inserting without ngn_amount
    // We'll log an error but still proceed.
    error_log("Pending payments table may lack 'ngn_amount' column: " . $e->getMessage());
    $stmt = $pdo->prepare("INSERT INTO pending_payments (user_id, plan_id, reference, amount, status) VALUES (?, ?, ?, ?, 'pending')");
    $stmt->execute([$user_id, $invoice['plan_id'], $reference, $amount_usd]);
}

$_SESSION['paystack_reference'] = $reference;
?>
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Paystack Checkout - tipspac</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            background: #020617;
            background-image: radial-gradient(circle at 10% 20%, rgba(16, 185, 129, 0.05) 0%, transparent 40%),
                              radial-gradient(circle at 90% 80%, rgba(59, 130, 246, 0.05) 0%, transparent 40%);
        }
        .glass-card {
            background: rgba(15, 23, 42, 0.7);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(30, 41, 59, 0.6);
        }
        .btn-gradient {
            background: linear-gradient(135deg, #10b981, #059669);
            transition: all 0.3s ease;
        }
        .btn-gradient:hover {
            transform: translateY(-2px);
            box-shadow: 0 0 30px rgba(16, 185, 129, 0.3);
        }
        .loader {
            border: 3px solid rgba(255,255,255,0.1);
            border-top: 3px solid #10b981;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            animation: spin 0.8s linear infinite;
            display: inline-block;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .exchange-note {
            font-size: 8px;
            color: #94a3b8;
            border-top: 1px solid #1e293b;
            padding-top: 12px;
            margin-top: 12px;
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">

    <div class="fixed inset-0 pointer-events-none opacity-20 bg-cover bg-center bg-no-repeat" style="background-image: url('https://images.unsplash.com/photo-1579952363873-27f3bade9f55?q=80&w=2000&auto=format&fit=crop');"></div>
    <div class="fixed inset-0 pointer-events-none bg-gradient-to-t from-[#020617] via-[#020617]/85 to-transparent"></div>

    <div class="glass-card rounded-3xl p-6 sm:p-8 max-w-md w-full relative z-10 shadow-2xl text-center">
        <div class="flex items-center justify-center gap-3 mb-4">
            <div class="w-10 h-10 rounded-xl bg-emerald-500/10 border border-emerald-500/30 flex items-center justify-center shadow-[0_0_15px_rgba(16,185,129,0.1)]">
                <svg class="w-5 h-5 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
            </div>
            <span class="font-black text-xl tracking-wider text-white uppercase">tipspac <span class="text-emerald-400">Pro</span></span>
        </div>

        <h3 class="text-lg font-black tracking-wider uppercase text-emerald-400 mb-2">💳 Paystack Secured</h3>
        <p class="text-xs text-slate-400 mb-6">You will be redirected to Paystack to complete your subscription payment.</p>

        <!-- Invoice Summary -->
        <div class="bg-slate-950/60 border border-slate-800 rounded-2xl p-4 mb-4 flex justify-between items-center text-sm font-bold">
            <span class="text-slate-400">Plan</span>
            <span class="text-white"><?= htmlspecialchars($invoice['plan_name'] ?? 'Subscription') ?></span>
        </div>
        <div class="bg-slate-950/60 border border-slate-800 rounded-2xl p-4 mb-4 flex justify-between items-center text-sm font-bold">
            <span class="text-slate-400">Amount (USD)</span>
            <span class="text-emerald-400">$<?= number_format($amount_usd, 2) ?></span>
        </div>
        <div class="bg-slate-950/60 border border-slate-800 rounded-2xl p-4 mb-4 flex justify-between items-center text-sm font-bold">
            <span class="text-slate-400">Amount (NGN)</span>
            <span class="text-amber-400 text-lg">₦<?= number_format($amount_ngn, 0) ?></span>
        </div>
        <div class="bg-slate-950/60 border border-slate-800 rounded-2xl p-4 mb-6 flex justify-between items-center text-xs font-bold">
            <span class="text-slate-400">Email</span>
            <span class="text-slate-300"><?= htmlspecialchars($email) ?></span>
        </div>

        <!-- Exchange Rate Note -->
        <div class="exchange-note text-[8px] text-slate-400 text-center">
            💱 1 USD = ₦<?= number_format($rate, 2) ?> • Paystack charges in NGN
        </div>

        <form id="paymentForm" class="mt-4">
            <input type="hidden" id="email-address" value="<?= $email ?>">
            <input type="hidden" id="amount" value="<?= $amount_kobo ?>">
            <input type="hidden" id="reference" value="<?= $reference ?>">
            <button type="button" onclick="payWithPaystack()" id="payBtn" class="btn-gradient w-full text-white font-black py-4 rounded-xl text-xs uppercase tracking-[0.15em] shadow-lg flex items-center justify-center gap-2">
                <span>Pay ₦<?= number_format($amount_ngn, 0) ?></span>
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path></svg>
            </button>
            <div id="payLoader" class="hidden mt-2 flex items-center justify-center gap-2 text-xs text-slate-400">
                <span class="loader"></span> Processing...
            </div>
        </form>

        <a href="../billing.php" class="block mt-6 text-[9px] font-black tracking-widest uppercase text-slate-500 hover:text-white transition">Cancel &amp; Return to Billing</a>

        <div class="mt-4 flex items-center justify-center gap-2 text-[9px] text-slate-500">
            <svg class="w-3 h-3 text-emerald-400" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/></svg>
            <span>Secured by Paystack • SSL Encrypted</span>
        </div>
    </div>
    

    <script src="https://js.paystack.co/v1/inline.js"></script> 
    <script>
        const public_key = "<?= $public_key ?>";
        const payBtn = document.getElementById('payBtn');
        const payLoader = document.getElementById('payLoader');

        function payWithPaystack() {
            if (!public_key) {
                alert('Payment gateway is not configured. Please contact support.');
                return;
            }

            const email = document.getElementById('email-address').value;
            const amount = document.getElementById('amount').value;
            const reference = document.getElementById('reference').value;

            payBtn.disabled = true;
            payBtn.querySelector('span').textContent = 'Processing...';
            payLoader.classList.remove('hidden');

            let handler = PaystackPop.setup({
                key: public_key,
                email: email,
                amount: amount,
                currency: 'NGN',
                ref: reference,
                metadata: {
                    custom_fields: [
                        {
                            display_name: "Plan",
                            variable_name: "plan",
                            value: "<?= htmlspecialchars($invoice['plan_name'] ?? 'Subscription') ?>"
                        },
                        {
                            display_name: "User ID",
                            variable_name: "user_id",
                            value: "<?= $user_id ?>"
                        }
                    ]
                },
                onClose: function(){
                    payBtn.disabled = false;
                    payBtn.querySelector('span').textContent = 'Pay Now';
                    payLoader.classList.add('hidden');
                    alert('Payment window closed. You can try again.');
                },
                callback: function(response){
                    window.location.href = 'verify-paystack.php?reference=' + response.reference;
                }
            });
            handler.openIframe();
        }
    </script>
</body>
</html>