<?php
// কনফিগ এবং লগইন চেক
require 'config.php'; 
require_login(); 

// ইউজারের ব্যালেন্স এবং তথ্য সংগ্রহ
$user_id = $_SESSION['user_id'];
$stmt = $pdo->prepare("SELECT id, name, email, balance FROM users WHERE id=?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

// যদি ইউজার ডাটা না পাওয়া যায়
if (!$user) {
    $user = ['balance' => 0, 'email' => 'Unknown', 'name' => 'User'];
}

// --- সিস্টেম আপডেট: ডাটাবেজ থেকে সেটিং/নম্বর সংগ্রহ ---
try {
    $settings_stmt = $pdo->query("SELECT setting_key, setting_value FROM settings");
    $settings_raw = $settings_stmt->fetchAll();
    $settings = [];
    foreach ($settings_raw as $row) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
} catch (Exception $e) {
    $settings = [];
}

// ফর্ম হ্যান্ডেলিং
if (is_post()) {
    verify_csrf();
    $amount = (float)($_POST['amount'] ?? 0);
    $trx_id = trim($_POST['trx_id'] ?? '');
    $bkash_number = trim($_POST['bkash_number'] ?? '');
    
    $user_captcha = strtoupper(trim($_POST['captcha_code'] ?? '')); 
    $session_captcha = $_SESSION['captcha_code'] ?? ''; 
    unset($_SESSION['captcha_code']); 

    if (empty($user_captcha) || $user_captcha != $session_captcha) {
        set_flash("❌ ক্যাপচা কোডটি ভুল হয়েছে। আবার চেষ্টা করুন।","danger");
        redirect('recharge.php');
    }

    if ($amount < 100 || empty($trx_id) || empty($bkash_number)) {
        set_flash("❌ সর্বনিম্ন ১০০ টাকা এবং সঠিক তথ্য প্রদান করুন।","danger");
        redirect('recharge.php');
    }

    $stmt = $pdo->prepare("INSERT INTO recharges (user_id, amount, txn_id) VALUES (?,?,?)");
    $stmt->execute([$user_id, $amount, $trx_id]);

    if(function_exists('sendTelegramMessage')) {
        $message = "<b>🔋 New Recharge Request</b>\n\n" .
                "<b>User:</b> " . h($user['email']) . "\n" .
                "<b>Amount:</b> " . h($amount) . " BDT\n" .
                "<b>TrxID:</b> " . h($trx_id);
        sendTelegramMessage($message, $settings);
    }

    set_flash("আপনার রিকোয়েস্টটি সফলভাবে জমা হয়েছে।","success");
    redirect('recharge.php');
}

// ইতিহাস সংগ্রহ
$stmt = $pdo->prepare("SELECT * FROM recharges WHERE user_id=? ORDER BY created_at DESC");
$stmt->execute([$user_id]);
$recharges = $stmt->fetchAll();

require_once 'header.php';
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>রিচার্জ - প্রিমিয়াম পোর্টাল</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Hind+Siliguri:wght@400;500;600;700&display=swap');
        
        :root {
            --primary: #6C3FAA;
            --primary-dark: #4B2A7A;
            --accent: #FF9F43;
            --bg-light: #F8F5FD;
            --card-bg: #FFFFFF;
            --text-dark: #1E1135;
            --text-muted: #6C6A7A;
            --border: #E2DEF0;
            --success: #10B981;
            --warning: #F59E0B;
            --danger: #EF4444;
            --shadow-sm: 0 4px 15px rgba(108, 63, 170, 0.08);
            --shadow-md: 0 8px 25px rgba(108, 63, 170, 0.12);
            --shadow-lg: 0 12px 40px rgba(108, 63, 170, 0.2);
            --radius: 20px;
            --transition: all 0.3s ease;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Hind Siliguri', sans-serif;
            background: linear-gradient(135deg, #F5F0FF 0%, #EDE4FB 100%);
            color: var(--text-dark);
            min-height: 100vh;
        }

        .premium-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 2rem 1.5rem;
        }

        /* Hero Balance Card */
        .balance-hero {
            background: linear-gradient(135deg, #7B4DC7 0%, #542E90 100%);
            border-radius: var(--radius);
            padding: 2rem 2.5rem;
            color: white;
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1.5rem;
            box-shadow: var(--shadow-md);
            margin-bottom: 2.5rem;
            position: relative;
            overflow: hidden;
        }
        .balance-hero::after {
            content: '';
            position: absolute;
            width: 200px;
            height: 200px;
            background: rgba(255,255,255,0.05);
            border-radius: 50%;
            top: -50px;
            right: -50px;
        }
        .balance-info h2 {
            font-size: 1rem;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: 0.9;
            margin-bottom: 0.5rem;
        }
        .balance-amount {
            font-size: 3.2rem;
            font-weight: 700;
            line-height: 1.2;
        }
        .balance-amount span {
            font-size: 1.8rem;
            margin-right: 5px;
        }
        .balance-icon {
            background: rgba(255,255,255,0.15);
            backdrop-filter: blur(10px);
            padding: 1.5rem;
            border-radius: 50%;
            font-size: 2.5rem;
            z-index: 1;
        }

        /* Section Headers */
        .premium-title {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 1.5rem;
        }
        .premium-title .icon-circle {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
            color: white;
            width: 42px;
            height: 42px;
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 1.2rem;
            box-shadow: 0 5px 15px rgba(108,63,170,0.3);
        }
        .premium-title h4 {
            font-size: 1.25rem;
            font-weight: 700;
        }

        /* Cards */
        .premium-card {
            background: var(--card-bg);
            border-radius: var(--radius);
            padding: 2rem;
            box-shadow: var(--shadow-sm);
            border: 1px solid var(--border);
            transition: var(--transition);
            margin-bottom: 2rem;
        }
        .premium-card:hover {
            box-shadow: var(--shadow-md);
            transform: translateY(-2px);
        }

        /* Payment Method Box */
        .payment-method {
            background: #F9F7FE;
            border-radius: 16px;
            padding: 1.2rem 1.5rem;
            margin-bottom: 1rem;
            border-left: 5px solid var(--primary);
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 1rem;
            transition: var(--transition);
        }
        .payment-method:hover {
            background: #F1ECFB;
        }
        .payment-method .brand {
            font-weight: 700;
            font-size: 1.1rem;
        }
        .payment-method .number-box {
            background: white;
            border: 1px dashed var(--primary);
            padding: 8px 16px;
            border-radius: 10px;
            font-weight: 600;
            letter-spacing: 0.5px;
            user-select: all;
            cursor: pointer;
        }
        .copy-btn {
            background: white;
            border: 1px solid var(--border);
            border-radius: 10px;
            padding: 8px 12px;
            cursor: pointer;
            transition: var(--transition);
        }
        .copy-btn:hover {
            background: #6C3FAA10;
        }

        /* Form Styles */
        .form-label {
            font-weight: 600;
            font-size: 0.95rem;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
            color: var(--text-dark);
        }
        .input-group {
            display: flex;
            align-items: stretch;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.03);
        }
        .input-group-text {
            background: #F4F2F8;
            border: 1px solid var(--border);
            border-right: none;
            padding: 12px 16px;
            font-weight: 700;
            color: var(--primary);
            border-radius: 12px 0 0 12px;
        }
        .form-control {
            border: 1px solid var(--border);
            padding: 12px 16px;
            font-size: 1rem;
            border-radius: 12px;
            background: white;
            transition: var(--transition);
            width: 100%;
        }
        .input-group .form-control {
            border-left: none;
            border-radius: 0 12px 12px 0;
        }
        .form-control:focus {
            outline: none;
            border-color: var(--primary);
            box-shadow: 0 0 0 4px rgba(108,63,170,0.1);
        }

        .btn-premium {
            background: linear-gradient(135deg, #7B4DC7, #542E90);
            border: none;
            color: white;
            padding: 15px 24px;
            border-radius: 14px;
            font-weight: 700;
            font-size: 1.1rem;
            width: 100%;
            cursor: pointer;
            transition: all 0.3s;
            letter-spacing: 0.5px;
            box-shadow: 0 8px 20px rgba(108,63,170,0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
        }
        .btn-premium:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 25px rgba(108,63,170,0.4);
            background: linear-gradient(135deg, #8A5ED4, #6337A0);
        }
        .btn-premium:disabled {
            opacity: 0.7;
            transform: none;
        }

        /* Captcha box */
        .captcha-area {
            background: #F9F7FE;
            border-radius: 16px;
            padding: 1.5rem;
            text-align: center;
            border: 1px dashed var(--primary);
            margin: 1.5rem 0;
        }
        .captcha-img {
            border-radius: 12px;
            height: 54px;
            border: 1px solid var(--border);
        }
        .refresh-captcha {
            background: white;
            border: 1px solid var(--border);
            border-radius: 12px;
            padding: 12px 14px;
            cursor: pointer;
            font-size: 1rem;
            transition: var(--transition);
        }
        .refresh-captcha:hover {
            background: #F1ECFB;
        }

        /* Table */
        .recharge-history {
            background: var(--card-bg);
            border-radius: var(--radius);
            overflow: hidden;
            box-shadow: var(--shadow-sm);
        }
        .table-premium {
            width: 100%;
            border-collapse: collapse;
        }
        .table-premium thead {
            background: linear-gradient(135deg, #5A3A8A, #402568);
            color: white;
        }
        .table-premium th {
            padding: 16px 20px;
            font-weight: 600;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        .table-premium td {
            padding: 16px 20px;
            border-bottom: 1px solid #F0ECF7;
        }
        .table-premium tbody tr {
            transition: background 0.2s;
        }
        .table-premium tbody tr:hover {
            background: #FCF9FF;
        }
        .status-badge {
            padding: 6px 14px;
            border-radius: 50px;
            font-weight: 600;
            font-size: 0.8rem;
            display: inline-block;
        }
        .badge-success { background: #D1FAE5; color: #065F46; }
        .badge-danger { background: #FEE2E2; color: #991B1B; }
        .badge-warning { background: #FFF3CD; color: #856404; }

        /* Alerts */
        .alert {
            padding: 1rem 1.5rem;
            border-radius: 12px;
            margin-bottom: 1.5rem;
            display: flex;
            align-items: center;
            gap: 10px;
            font-weight: 500;
            backdrop-filter: blur(5px);
        }
        .alert-info {
            background: #EDE4FF;
            color: #3D1D6E;
        }
        .alert-danger {
            background: #FFE5E5;
            color: #A71D2A;
        }

        /* Responsive */
        @media (max-width: 768px) {
            .balance-hero {
                padding: 1.5rem;
            }
            .balance-amount {
                font-size: 2.5rem;
            }
            .premium-card {
                padding: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <div class="premium-container">
        <!-- Balance Hero -->
        <div class="balance-hero">
            <div class="balance-info">
                <h2><i class="fas fa-user-circle me-2"></i> স্বাগতম, <?php echo h($user['name']); ?></h2>
                <div class="balance-amount"><span>৳</span><?php echo number_format((float)($user['balance'] ?? 0), 2); ?></div>
                <p style="margin-top: 5px; opacity:0.8;">বর্তমান ব্যালেন্স</p>
            </div>
            <div class="balance-icon">
                <i class="fas fa-wallet"></i>
            </div>
        </div>

        <?php show_flash(); ?>

        <div class="row" style="display: flex; flex-wrap: wrap; gap: 2rem;">
            <!-- Left Column: Payment Methods -->
            <div style="flex: 1 1 350px;">
                <div class="premium-card">
                    <div class="premium-title">
                        <span class="icon-circle"><i class="fas fa-money-bill-wave"></i></span>
                        <h4>পেমেন্ট চ্যানেল</h4>
                    </div>
                    <div class="alert alert-info" style="margin-bottom: 1.5rem;">
                        <i class="fas fa-info-circle"></i> সর্বনিম্ন রিচার্জ: <strong>১০০ টাকা</strong>
                    </div>
                    
                    <?php if(!empty($settings['bikash_number'])): ?>
                    <div class="payment-method">
                        <div>
                            <span class="brand" style="color:#E2136E;"><i class="fab fa-cc-bkash"></i> বিকাশ (পার্সোনাল)</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span class="number-box" id="bkashNum"><?php echo h($settings['bikash_number']); ?></span>
                            <button class="copy-btn" onclick="copyToClipboard('bkashNum')"><i class="fas fa-copy"></i></button>
                        </div>
                    </div>
                    <?php endif; ?>

                    <?php if(!empty($settings['nagad_number'])): ?>
                    <div class="payment-method">
                        <div>
                            <span class="brand" style="color:#EC1C24;"><i class="fas fa-mobile-alt"></i> নগদ (পার্সোনাল)</span>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <span class="number-box" id="nagadNum"><?php echo h($settings['nagad_number']); ?></span>
                            <button class="copy-btn" onclick="copyToClipboard('nagadNum')"><i class="fas fa-copy"></i></button>
                        </div>
                    </div>
                    <?php endif; ?>
                    <p class="text-danger" style="font-size:0.9rem; margin-top:15px;">
                        <i class="fas fa-exclamation-triangle"></i> শুধুমাত্র Send Money প্রযোজ্য।
                    </p>
                </div>
            </div>

            <!-- Right Column: Recharge Form -->
            <div style="flex: 2 1 500px;">
                <div class="premium-card">
                    <div class="premium-title">
                        <span class="icon-circle"><i class="fas fa-paper-plane"></i></span>
                        <h4>নতুন রিচার্জ রিকোয়েস্ট</h4>
                    </div>
                    <form method="post" id="rechargeForm">
                        <?php csrf_field(); ?>
                        <div class="row" style="display: flex; gap: 20px; margin-bottom: 1.5rem;">
                            <div style="flex: 1;">
                                <label class="form-label"><i class="fas fa-taka-sign"></i> টাকার পরিমাণ</label>
                                <div class="input-group">
                                    <span class="input-group-text">৳</span>
                                    <input type="number" name="amount" class="form-control" placeholder="সর্বনিম্ন ১০০" min="100" required>
                                </div>
                            </div>
                            <div style="flex: 1;">
                                <label class="form-label"><i class="fas fa-phone"></i> আপনার পেমেন্ট নাম্বার</label>
                                <input type="tel" name="bkash_number" class="form-control" placeholder="01XXXXXXXXX" required>
                            </div>
                        </div>

                        <div style="margin-bottom: 1.5rem;">
                            <label class="form-label"><i class="fas fa-receipt"></i> ট্রানজেকশন আইডি (TrxID)</label>
                            <input type="text" name="trx_id" class="form-control text-uppercase fw-bold" placeholder="যেমন: 8N77X99L" required>
                        </div>

                        <!-- Captcha -->
                        <div class="captcha-area">
                            <label class="form-label justify-content-center"><i class="fas fa-shield-alt"></i> নিরাপত্তা কোড (Captcha)</label>
                            <div style="display: flex; justify-content: center; align-items: center; gap: 15px; margin: 15px 0;">
                                <img src="captcha.php?rand=<?php echo rand(); ?>" id="capImg" class="captcha-img">
                                <button type="button" class="refresh-captcha" onclick="refreshCaptcha()">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                            </div>
                            <input type="text" name="captcha_code" class="form-control text-center mx-auto" style="max-width: 280px;" placeholder="কোডটি লিখুন" required>
                        </div>

                        <button type="submit" class="btn-premium">
                            <i class="fas fa-check-circle"></i> সাবমিট করুন
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Recharge History -->
        <div style="margin-top: 2.5rem;">
            <div class="premium-title">
                <span class="icon-circle"><i class="fas fa-history"></i></span>
                <h4>সাম্প্রতিক রিচার্জ ইতিহাস</h4>
            </div>
            <div class="recharge-history">
                <table class="table-premium">
                    <thead>
                        <tr>
                            <th>TrxID</th>
                            <th>পরিমাণ</th>
                            <th>অবস্থা</th>
                            <th>সময়</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($recharges)): ?>
                            <?php foreach ($recharges as $r): 
                                $status = strtolower($r['status'] ?? 'pending');
                                $badgeClass = ($status == "approved") ? 'badge-success' : (($status == "rejected") ? 'badge-danger' : 'badge-warning');
                                $status_text = ($status == "approved") ? 'সফল' : (($status == "rejected") ? 'বাতিল' : 'অপেক্ষমান');
                            ?>
                            <tr>
                                <td><strong>#<?php echo h($r['txn_id'] ?? 'N/A'); ?></strong></td>
                                <td>৳ <?php echo number_format((float)($r['amount'] ?? 0), 2); ?></td>
                                <td><span class="status-badge <?php echo $badgeClass; ?>"><?php echo $status_text; ?></span></td>
                                <td style="color: #6C6A7A;"><?php echo date('d M, Y | h:i A', strtotime($r['created_at'])); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="4" style="text-align:center; padding:3rem;">কোনো লেনদেনের তথ্য পাওয়া যায়নি।</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <script>
        function copyToClipboard(elementId) {
            const el = document.getElementById(elementId);
            if (!el) return;
            const text = el.innerText;
            navigator.clipboard.writeText(text).then(() => {
                // টেম্পোরারি ফিডব্যাক
                const original = el.innerText;
                el.innerText = '✓ কপি হয়েছে';
                setTimeout(() => { el.innerText = original; }, 1500);
            }).catch(() => {
                alert('কপি করতে সমস্যা হয়েছে।');
            });
        }

        function refreshCaptcha() {
            document.getElementById('capImg').src = 'captcha.php?rand=' + Math.random();
        }

        document.getElementById('rechargeForm').addEventListener('submit', function(e) {
            const amount = parseFloat(this.querySelector('input[name="amount"]').value);
            if (isNaN(amount) || amount < 100) {
                e.preventDefault();
                alert('দুঃখিত, সর্বনিম্ন ১০০ টাকা রিচার্জ করতে হবে।');
                return false;
            }
            const btn = this.querySelector('.btn-premium');
            btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> প্রসেসিং...';
            btn.disabled = true;
        });
    </script>
</body>
</html>

<?php require_once 'footer.php'; ?>