<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.php';
require_once __DIR__ . '/includes/wallet.php';

// Ensure user is logged in
if (!isLoggedIn()) {
    redirect('login.php');
}

$lang = new Language($db);
$current_lang = $lang->getCurrentLanguage();
$user_id = $_SESSION['user_id'];

// Fetch user data
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

$rzp_key = getSetting('razorpay_key_id', '');
$rzp_secret = getSetting('razorpay_key_secret', '');
$subscription_price = getSetting('subscription_price', '999');

/* ---- Pay for the subscription from the wallet (virtual first, then main) ---- */
if (isset($_POST['pay_subscription_wallet'])) {
    $price = (float)$subscription_price;
    $u = $db->select("SELECT is_subscribed FROM users WHERE id = ?", [$user_id]);
    if (!empty($u) && (int)$u[0]['is_subscribed'] === 1) {
        $_SESSION['flash_error'] = "You already have an active subscription.";
        redirect('subscription.php');
    }

    $pay = wallet_spend($db, $user_id, $price, [
        'category'       => 'subscription',
        'description'    => 'Platform Subscription',
        'reference_type' => 'subscription',
    ]);

    if (!$pay['ok']) {
        $_SESSION['flash_error'] = "Insufficient wallet balance — you need ₹" . number_format($pay['short'], 2) . " more.";
    } else {
        $db->insert("UPDATE users SET is_subscribed = 1 WHERE id = ?", [$user_id]);
        // Pay the 3-level referral commission on this subscription
        distributeReferralCommission($db, $user_id, $price, 'subscription', null);
        $_SESSION['flash_success'] = "Subscription activated! Paid " . wallet_split_note($pay) . ". The referral program is now unlocked.";
    }
    redirect('subscription.php');
}

// Handle Secure Razorpay Subscription Payment
if(isset($_POST['payment_id'])) {
    $pay_id = sanitize($_POST['payment_id']);
    
    if(!empty($pay_id)) {
        // Securely verify payment with Razorpay API
        $url = "https://api.razorpay.com/v1/payments/" . $pay_id;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERPWD, $rzp_key . ":" . $rzp_secret);
        $response = curl_exec($ch);
        curl_close($ch);
        
        $rzp_data = json_decode($response, true);
        
        if (isset($rzp_data['status']) && in_array($rzp_data['status'], ['authorized', 'captured'])) {
            $paid_amount = floatval($rzp_data['amount']) / 100; 
            
            if ($paid_amount >= $subscription_price) {
                // Update user to subscribed
                $db->insert("UPDATE users SET is_subscribed = 1 WHERE id = ?", [$user_id]);
                $db->insert("INSERT INTO transactions (user_id, type, amount, description, status) VALUES (?, 'debit', ?, ?, 'Success')", [$user_id, $paid_amount, "Platform Subscription via Razorpay (Txn: $pay_id)"]);
                wallet__ledger($db, $user_id, WALLET_MAIN, 'debit', $paid_amount, wallet_balances($db, $user_id)['main'], [
                    'category'       => 'subscription',
                    'description'    => "Platform Subscription via Razorpay (Txn: $pay_id)",
                    'reference_type' => 'subscription',
                ]);

                // Pay the 3-level referral commission on this subscription
                distributeReferralCommission($db, $user_id, $paid_amount, 'subscription', null);

                $_SESSION['flash_success'] = "Subscription activated successfully! Referral program is now unlocked.";
                redirect('subscription.php');
            }
        }
        
        $_SESSION['flash_error'] = "Payment Verification Failed! Security alert generated.";
        redirect('subscription.php');
    }
}



// PRG Flash Messages Setup
$success_msg = '';
$error_msg = '';
if (isset($_SESSION['flash_success'])) {
    $success_msg = $_SESSION['flash_success'];
    unset($_SESSION['flash_success']);
}
if (isset($_SESSION['flash_error'])) {
    $error_msg = $_SESSION['flash_error'];
    unset($_SESSION['flash_error']);
}

// Re-fetch user
$user_data = $db->select("SELECT * FROM users WHERE id = ?", [$user_id]);
$user = !empty($user_data) ? $user_data[0] : null;

/* Wallet balances for the "Pay from Wallet" option */
$sub_wal = wallet_balances($db, $user_id);

$company_logo = getSetting('company_logo', 'assets/images/logo.png');
$company_logo = (strpos($company_logo, 'http') === 0) ? $company_logo : ltrim($company_logo, '/');
$company_name = getSetting('company_name', 'WBMCZ');
$dashboard_link = ($user['user_type'] == 'seller') ? 'seller/index.php' : (($user['user_type'] == 'admin') ? 'admin/index.php' : 'dashboard.php');
?>
<!DOCTYPE html>
<html lang="<?php echo $current_lang; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Subscription - <?php echo htmlspecialchars($company_name); ?></title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; scroll-behavior: smooth; } .hide-scrollbar::-webkit-scrollbar { display: none; } </style>
</head>
<body class="bg-gray-50">
    
    <!-- Top Header -->
    <header class="h-16 bg-white border-b border-gray-200 flex items-center justify-between px-4 lg:px-8 shadow-sm">
        <a href="<?php echo $dashboard_link; ?>" class="flex items-center space-x-2 text-indigo-600 hover:text-indigo-800 transition">
            <i class="fas fa-arrow-left"></i> <span class="font-bold">Back to Dashboard</span>
        </a>
        <h2 class="font-bold text-lg text-gray-800">My Subscription</h2>
    </header>

    <main class="max-w-4xl mx-auto p-4 md:p-8">
        
        <?php if ($success_msg): ?>
        <div class="mb-6 bg-emerald-50 border border-emerald-200 text-emerald-700 px-4 py-3 rounded-xl relative shadow-sm">
            <i class="fas fa-check-circle mr-2"></i> <?php echo $success_msg; ?>
        </div>
        <?php endif; ?>

        <?php if ($error_msg): ?>
        <div class="mb-6 bg-rose-50 border border-rose-200 text-rose-700 px-4 py-3 rounded-xl relative shadow-sm">
            <i class="fas fa-exclamation-circle mr-2"></i> <?php echo $error_msg; ?>
        </div>
        <?php endif; ?>

        <?php if(!isset($user['is_subscribed']) || $user['is_subscribed'] == 0): ?>
            <!-- Not Subscribed View -->
            <div class="bg-white rounded-3xl shadow-xl overflow-hidden border border-gray-100 mb-8">
                <div class="bg-gradient-to-r from-amber-500 to-orange-500 p-8 text-center text-white relative overflow-hidden">
                    <div class="absolute -right-10 -top-10 w-48 h-48 bg-white/20 rounded-full blur-2xl"></div>
                    <i class="fas fa-crown text-5xl mb-4 text-amber-200"></i>
                    <h2 class="text-3xl font-extrabold mb-2">Premium Subscription</h2>
                    <p class="text-amber-100 max-w-lg mx-auto">Unlock the full potential of your account with our premium features. Maximize your earnings and enjoy exclusive benefits.</p>
                </div>
                
                <div class="p-8">
                    <h3 class="text-xl font-bold text-gray-800 mb-6 text-center">What's included?</h3>
                    <ul class="space-y-4 max-w-xl mx-auto mb-8">
                        <?php 
                        $features_text = isset($site_settings['subscription_features']) ? $site_settings['subscription_features'] : "Unlock Referral Income\nExclusive Purchase Discounts\nUpgrade to Seller Account\nPriority Quick Support";
                        $features = array_filter(array_map('trim', explode("\n", $features_text)));
                        foreach($features as $feature): 
                        ?>
                        <li class="flex items-start">
                            <i class="fas fa-check-circle text-emerald-500 mt-1 mr-3 text-lg"></i>
                            <div>
                                <h4 class="font-bold text-gray-800"><?php echo htmlspecialchars($feature); ?></h4>
                            </div>
                        </li>
                        <?php endforeach; ?>
                    </ul>

                    <div class="text-center bg-gray-50 p-6 rounded-2xl border border-gray-200">
                        <p class="text-gray-500 font-bold uppercase tracking-widest text-sm mb-2">One-Time Fee</p>
                        <div class="text-5xl font-extrabold text-gray-900 mb-6">₹<?php echo number_format($subscription_price, 2); ?></div>
                        
                        <form id="razorpayForm" method="POST" class="hidden">
                            <input type="hidden" name="payment_id" id="rzp_payment_id">
                        </form>
                        
                        <div class="flex flex-col sm:flex-row gap-3 justify-center">
                            <button onclick="paySubscription()" class="w-full sm:w-auto bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white font-bold py-4 px-10 rounded-xl shadow-lg transition-transform transform hover:-translate-y-1 text-base flex items-center justify-center">
                                <i class="fas fa-bolt mr-2"></i> Pay with Razorpay
                            </button>

                            <?php $__can_wallet = ($sub_wal['total'] + 0.001) >= (float)$subscription_price; ?>
                            <form method="POST" class="w-full sm:w-auto" onsubmit="return confirm('Pay ₹<?php echo number_format($subscription_price, 2); ?> from your wallet?');">
                                <button type="submit" name="pay_subscription_wallet" <?php echo $__can_wallet ? '' : 'disabled'; ?>
                                        class="w-full bg-gradient-to-r from-indigo-600 to-purple-600 hover:from-indigo-700 hover:to-purple-700 text-white font-bold py-4 px-10 rounded-xl shadow-lg transition-transform transform hover:-translate-y-1 text-base flex items-center justify-center disabled:opacity-40 disabled:cursor-not-allowed disabled:transform-none">
                                    <i class="fas fa-wallet mr-2"></i> Pay from Wallet
                                </button>
                            </form>
                        </div>

                        <div class="mt-4 inline-flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] font-semibold">
                            <span class="text-amber-600"><i class="fas fa-gift mr-1"></i>Virtual ₹<?php echo number_format($sub_wal['virtual'], 2); ?></span>
                            <span class="text-slate-500"><i class="fas fa-wallet mr-1"></i>Main ₹<?php echo number_format($sub_wal['main'], 2); ?></span>
                            <span class="text-emerald-600 font-black">Total ₹<?php echo number_format($sub_wal['total'], 2); ?></span>
                        </div>
                        <?php if (!$__can_wallet): ?>
                            <p class="text-[11px] text-rose-500 mt-2 font-semibold">
                                You need ₹<?php echo number_format((float)$subscription_price - $sub_wal['total'], 2); ?> more to pay from your wallet.
                            </p>
                        <?php else: ?>
                            <p class="text-[11px] text-slate-400 mt-2">Your virtual (referral) balance is used first, the rest comes from your main wallet.</p>
                        <?php endif; ?>
                        <p class="text-xs text-gray-400 mt-3"><i class="fas fa-lock mr-1"></i> Secured by Razorpay</p>
                    </div>
                </div>
            </div>

            <script>
                const rzpKey = "<?php echo $rzp_key; ?>";
                const amount = <?php echo floatval($subscription_price); ?>;
                
                function paySubscription() {
                    var options = {
                        "key": rzpKey,
                        "amount": amount * 100, 
                        "currency": "INR",
                        "name": "<?php echo addslashes($company_name); ?>",
                        "description": "Platform Subscription",
                        "handler": function (response) {
                            document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
                            document.getElementById('razorpayForm').submit();
                        },
                        "prefill": {
                            "name": "<?php echo addslashes($user['name']); ?>",
                            "email": "<?php echo addslashes($user['email']); ?>",
                            "contact": "<?php echo addslashes($user['mobile']); ?>"
                        },
                        "theme": { "color": "#f59e0b" }
                    };
                    var rzp1 = new Razorpay(options);
                    rzp1.open();
                }
            </script>

        <?php else: ?>
            <!-- Subscribed View -->
            <div class="bg-white rounded-3xl shadow-xl overflow-hidden border border-emerald-100 mb-8">
                <div class="bg-gradient-to-r from-emerald-500 to-teal-500 p-8 text-center text-white relative overflow-hidden">
                    <i class="fas fa-check-circle text-5xl mb-4 text-emerald-200"></i>
                    <h2 class="text-3xl font-extrabold mb-2">You are Subscribed!</h2>
                    <p class="text-emerald-100 max-w-lg mx-auto">Your premium features are unlocked and fully active.</p>
                </div>
                
                <div class="p-8">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-8">
                        <a href="refer.php" class="bg-indigo-50 border border-indigo-100 p-6 rounded-2xl hover:bg-indigo-100 transition block text-center">
                            <div class="w-16 h-16 bg-indigo-500 text-white rounded-full flex items-center justify-center text-2xl mx-auto mb-4"><i class="fas fa-gift"></i></div>
                            <h3 class="font-bold text-indigo-900 text-lg mb-2">Referral System Active</h3>
                            <p class="text-sm text-indigo-700">Go to the Referral Dashboard to share your link and earn.</p>
                        </a>
                        <a href="services.php" class="bg-amber-50 border border-amber-100 p-6 rounded-2xl hover:bg-amber-100 transition block text-center">
                            <div class="w-16 h-16 bg-amber-500 text-white rounded-full flex items-center justify-center text-2xl mx-auto mb-4"><i class="fas fa-tags"></i></div>
                            <h3 class="font-bold text-amber-900 text-lg mb-2">Discounts Active</h3>
                            <p class="text-sm text-amber-700">Enjoy premium discounts when purchasing services.</p>
                        </a>
                    </div>
                    

                </div>
            </div>
        <?php endif; ?>

    </main>
</body>
</html>