<?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';

if (!isLoggedIn()) { redirect('login.php'); }

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

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

// Handle Successful Razorpay Payment
if(isset($_POST['payment_id']) && isset($_POST['amount'])) {
    $amount = floatval($_POST['amount']);
    $pay_id = sanitize($_POST['payment_id']);
    
    if($amount > 0 && !empty($pay_id)) {
        // Add to wallet
        wallet_credit($db, $user_id, WALLET_MAIN, $amount, ['category' => 'deposit', 'description' => 'Wallet top-up', 'skip_legacy' => true]);
        
        // Add Transaction
        $db->insert("INSERT INTO transactions (user_id, type, amount, description, status) VALUES (?, 'credit', ?, ?, 'Success')", [$user_id, $amount, "Wallet Recharge via Razorpay (Txn: $pay_id)"]);
        
        echo "<script>alert('Wallet Recharged Successfully!'); window.location.href='wallet.php';</script>";
        exit;
    }
}

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$company_name = getSetting('company_name', 'WBMCZ');
$rzp_key = getSetting('razorpay_key_id', '');
?>
<!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>Add Money to Wallet - <?php echo $company_name; ?></title>
    <script src="https://cdn.tailwindcss.com"></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@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <style> body { font-family: 'Inter', sans-serif; background-color: #f8fafc;} </style>
</head>
<body class="flex items-center justify-center min-h-screen px-4">

    <div class="w-full max-w-md bg-white rounded-2xl shadow-xl overflow-hidden">
        <div class="bg-gradient-to-r from-emerald-500 to-teal-600 px-6 py-8 text-white text-center">
            <div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto mb-3 border border-white/30 shadow-inner">
                <i class="fas fa-wallet text-2xl"></i>
            </div>
            <h2 class="text-2xl font-bold">Add Money</h2>
            <p class="text-sm opacity-90 mt-1">Current Balance: ₹<?php echo number_format($wallet_balance, 2); ?></p>
        </div>
        
        <div class="p-6 md:p-8 text-center">
            <div class="mb-6">
                <label class="block text-sm font-bold text-gray-700 mb-2 text-left">Enter Amount (₹)</label>
                <input type="number" id="amount_input" min="1" step="1" class="w-full px-4 py-4 bg-gray-50 border border-gray-200 rounded-xl focus:bg-white focus:outline-none focus:ring-2 focus:ring-emerald-500 text-2xl font-bold text-gray-800 transition-all text-center" placeholder="0.00">
            </div>
            
            <div class="flex gap-2 mb-8">
                <button onclick="document.getElementById('amount_input').value = 100" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-bold text-gray-600 hover:bg-emerald-50 hover:text-emerald-600 transition-colors">+ ₹100</button>
                <button onclick="document.getElementById('amount_input').value = 500" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-bold text-gray-600 hover:bg-emerald-50 hover:text-emerald-600 transition-colors">+ ₹500</button>
                <button onclick="document.getElementById('amount_input').value = 1000" class="flex-1 py-2 border border-gray-200 rounded-lg text-sm font-bold text-gray-600 hover:bg-emerald-50 hover:text-emerald-600 transition-colors">+ ₹1000</button>
            </div>

            <form id="razorpayForm" method="POST" class="hidden">
                <input type="hidden" name="amount" id="rzp_amount">
                <input type="hidden" name="payment_id" id="rzp_payment_id">
            </form>

            <button onclick="payViaRazorpay()" class="w-full bg-slate-800 hover:bg-slate-900 text-white font-bold py-4 px-6 rounded-xl shadow-md transition-colors text-lg flex items-center justify-center">
                <i class="fas fa-shield-alt mr-2"></i> Pay Securely with Razorpay
            </button>
            
            <a href="dashboard.php" class="block mt-4 text-sm text-gray-500 hover:text-gray-800 font-medium">Cancel and go back</a>
        </div>
    </div>

    <script>
    const rzpKey = "<?php echo $rzp_key; ?>";
    const companyName = "<?php echo $company_name; ?>";
    const userName = "<?php echo addslashes($user['name']); ?>";
    const userEmail = "<?php echo addslashes($user['email']); ?>";
    const userPhone = "<?php echo addslashes($user['mobile']); ?>";

    function payViaRazorpay() {
        const amount = parseFloat(document.getElementById('amount_input').value);
        if(isNaN(amount) || amount <= 0) {
            alert('Please enter a valid amount!');
            return;
        }

        var options = {
            "key": rzpKey,
            "amount": amount * 100, // Amount in paise
            "currency": "INR",
            "name": companyName,
            "description": "Wallet Recharge",
            "handler": function (response) {
                // Payment successful, submit details to PHP
                document.getElementById('rzp_amount').value = amount;
                document.getElementById('rzp_payment_id').value = response.razorpay_payment_id;
                document.getElementById('razorpayForm').submit();
            },
            "prefill": {
                "name": userName,
                "email": userEmail,
                "contact": userPhone
            },
            "theme": {
                "color": "#10b981"
            }
        };
        var rzp1 = new Razorpay(options);
        rzp1.open();
    }
    </script>
</body>
</html>
