<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/includes/functions.php';
require_once __DIR__ . '/includes/Language.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;
if (!$user) { session_destroy(); redirect('login.php'); }

$subscription_price = getSetting('subscription_price', '999');

/* ============================================================================
   LOCAL DICTIONARY
   The referral copy used to come from the `translations` table, where Bangla
   and Hindi strings had been mixed into the same language. Everything on this
   page now comes from ONE array per language, so a page is never half-Bangla /
   half-Hindi again.
   ============================================================================ */
$T = [
    'bn' => [
        'title'        => 'রেফার করুন ও আয় করুন',
        'subtitle'     => 'আপনার লিঙ্ক শেয়ার করুন। আপনার রেফার করা সদস্য এবং তাদের রেফার করা সদস্যদের কেনাকাটা থেকে ৩ লেভেল পর্যন্ত কমিশন পান।',
        'your_link'    => 'আপনার রেফারেল লিঙ্ক',
        'copy'         => 'লিঙ্ক কপি করুন',
        'copied'       => 'কপি হয়েছে!',
        'total_ref'    => 'মোট সরাসরি রেফারেল',
        'total_earn'   => 'মোট আয়',
        'team'         => 'মোট টিম (৩ লেভেল)',
        'active_sub'   => 'সাবস্ক্রিপশন নিয়েছে',
        'how'          => 'রেফারেল সিস্টেম কীভাবে কাজ করে',
        's1t'          => '১. লিঙ্ক শেয়ার করুন',
        's1d'          => 'উপরের রেফারেল লিঙ্কটি কপি করে বন্ধু বা পরিচিতদের পাঠান। লিঙ্কে আপনার রেফারেল কোড যুক্ত থাকে।',
        's2t'          => '২. তিনি রেজিস্টার করবেন',
        's2d'          => 'আপনার লিঙ্ক দিয়ে রেজিস্টার করলে তিনি স্থায়ীভাবে আপনার লেভেল-১ সদস্য হিসেবে যুক্ত হয়ে যাবেন।',
        's3t'          => '৩. প্রতিটি কেনাকাটায় কমিশন',
        's3d'          => 'তিনি যখনই কোনো সার্ভিস কেনেন, নির্ধারিত কমিশন সরাসরি আপনার মেইন ওয়ালেটে জমা হয় — যা তোলা যায়। সাবস্ক্রিপশনের কমিশন ভার্চুয়াল ওয়ালেটে জমা হয়।',
        's4t'          => '৪. ৩ লেভেল পর্যন্ত',
        's4d'          => 'আপনার লেভেল-১ সদস্য যাকে আনবেন তিনি আপনার লেভেল-২, এবং তার আনা সদস্য আপনার লেভেল-৩। তিন লেভেলেই আপনি কমিশন পাবেন।',
        'note'         => 'কমিশনের হার প্রতিটি সার্ভিসের জন্য আলাদা এবং অ্যাডমিন নির্ধারণ করেন। সার্ভিস বিক্রির কমিশন মেইন ওয়ালেটে জমা হয় (ব্যাংকে তোলা যায়), আর সাবস্ক্রিপশনের কমিশন ভার্চুয়াল ওয়ালেটে জমা হয়ে যেকোনো কেনাকাটায় খরচ করা যায়।',
        'my_team'      => 'আমার রেফার করা সদস্য',
        'search_ph'    => 'নাম, মোবাইল নম্বর বা আইডি দিয়ে খুঁজুন...',
        'all_levels'   => 'সব লেভেল',
        'level'        => 'লেভেল',
        'all_status'   => 'সব সদস্য',
        'subscribed'   => 'সাবস্ক্রিপশন নিয়েছে',
        'not_sub'      => 'সাবস্ক্রিপশন নেই',
        'ordered'      => 'অর্ডার করেছে',
        'not_ordered'  => 'অর্ডার করেনি',
        'user'         => 'সদস্য',
        'joined'       => 'যোগদানের তারিখ',
        'orders'       => 'অর্ডার',
        'status'       => 'স্ট্যাটাস',
        'contact'      => 'যোগাযোগ',
        'none'         => 'এখনও কোনো রেফার করা সদস্য নেই।',
        'nomatch'      => 'এই ফিল্টারে কোনো সদস্য পাওয়া যায়নি।',
        'free_user'    => 'ফ্রি সদস্য',
        'locked_t'     => 'রেফারেল প্রোগ্রাম লক করা আছে',
        'locked_d'     => 'রেফারেল সিস্টেম চালু করতে এবং কমিশন আয় করতে একটি সক্রিয় সাবস্ক্রিপশন প্রয়োজন।',
        'benefits'     => 'সাবস্ক্রিপশনের সুবিধা',
        'one_time'     => 'এককালীন ফি',
        'subscribe'    => 'এখনই সাবস্ক্রাইব করুন',
        'help_t'       => 'সাহায্য প্রয়োজন?',
        'help_d'       => 'রেফারেল বা কমিশন সংক্রান্ত যেকোনো প্রশ্নে আমাদের সঙ্গে যোগাযোগ করুন।',
        'wa_us'        => 'হোয়াটসঅ্যাপ করুন',
        'mail_us'      => 'ইমেল করুন',
    ],
    'hi' => [
        'title'        => 'रेफ़र करें और कमाएँ',
        'subtitle'     => 'अपना लिंक साझा करें। आपके रेफ़र किए सदस्यों और उनके रेफ़रल की खरीद पर 3 लेवल तक कमीशन पाएँ।',
        'your_link'    => 'आपका रेफ़रल लिंक',
        'copy'         => 'लिंक कॉपी करें',
        'copied'       => 'कॉपी हो गया!',
        'total_ref'    => 'कुल सीधे रेफ़रल',
        'total_earn'   => 'कुल कमाई',
        'team'         => 'कुल टीम (3 लेवल)',
        'active_sub'   => 'सब्सक्रिप्शन लिया',
        'how'          => 'रेफ़रल सिस्टम कैसे काम करता है',
        's1t'          => '1. लिंक साझा करें',
        's1d'          => 'ऊपर दिया रेफ़रल लिंक कॉपी करके दोस्तों को भेजें। लिंक में आपका रेफ़रल कोड होता है।',
        's2t'          => '2. वे रजिस्टर करते हैं',
        's2d'          => 'आपके लिंक से रजिस्टर करने पर वे स्थायी रूप से आपके लेवल-1 सदस्य बन जाते हैं।',
        's3t'          => '3. हर खरीद पर कमीशन',
        's3d'          => 'जब भी वे कोई सेवा खरीदते हैं, तय कमीशन सीधे आपके मेन वॉलेट में जमा होता है — जिसे निकाला जा सकता है। सब्सक्रिप्शन का कमीशन वर्चुअल वॉलेट में जाता है।',
        's4t'          => '4. 3 लेवल तक',
        's4d'          => 'आपके लेवल-1 सदस्य जिन्हें लाते हैं वे आपके लेवल-2, और उनके लाए सदस्य लेवल-3 हैं। तीनों लेवल पर कमीशन मिलता है।',
        'note'         => 'कमीशन दर हर सेवा के लिए अलग होती है और एडमिन तय करते हैं। सेवा बिक्री का कमीशन मेन वॉलेट में जाता है (बैंक में निकाला जा सकता है), और सब्सक्रिप्शन का कमीशन वर्चुअल वॉलेट में जाकर किसी भी खरीद में इस्तेमाल होता है।',
        'my_team'      => 'मेरे रेफ़र किए सदस्य',
        'search_ph'    => 'नाम, मोबाइल नंबर या आईडी से खोजें...',
        'all_levels'   => 'सभी लेवल',
        'level'        => 'लेवल',
        'all_status'   => 'सभी सदस्य',
        'subscribed'   => 'सब्सक्रिप्शन लिया',
        'not_sub'      => 'सब्सक्रिप्शन नहीं',
        'ordered'      => 'ऑर्डर किया',
        'not_ordered'  => 'ऑर्डर नहीं किया',
        'user'         => 'सदस्य',
        'joined'       => 'जुड़ने की तारीख',
        'orders'       => 'ऑर्डर',
        'status'       => 'स्थिति',
        'contact'      => 'संपर्क',
        'none'         => 'अभी तक कोई रेफ़र किया सदस्य नहीं है।',
        'nomatch'      => 'इस फ़िल्टर में कोई सदस्य नहीं मिला।',
        'free_user'    => 'फ्री सदस्य',
        'locked_t'     => 'रेफ़रल प्रोग्राम लॉक है',
        'locked_d'     => 'रेफ़रल सिस्टम चालू करने और कमीशन कमाने के लिए सक्रिय सब्सक्रिप्शन ज़रूरी है।',
        'benefits'     => 'सब्सक्रिप्शन के फ़ायदे',
        'one_time'     => 'एकमुश्त शुल्क',
        'subscribe'    => 'अभी सब्सक्राइब करें',
        'help_t'       => 'मदद चाहिए?',
        'help_d'       => 'रेफ़रल या कमीशन से जुड़े किसी भी सवाल के लिए हमसे संपर्क करें।',
        'wa_us'        => 'व्हाट्सएप करें',
        'mail_us'      => 'ईमेल करें',
    ],
    'en' => [
        'title'        => 'Refer & Earn',
        'subtitle'     => 'Share your link. Earn commission on what your members buy — and on what their members buy, up to 3 levels.',
        'your_link'    => 'Your referral link',
        'copy'         => 'Copy link',
        'copied'       => 'Copied!',
        'total_ref'    => 'Direct referrals',
        'total_earn'   => 'Total earned',
        'team'         => 'Total team (3 levels)',
        'active_sub'   => 'Subscribed members',
        'how'          => 'How the referral system works',
        's1t'          => '1. Share your link',
        's1d'          => 'Copy the referral link above and send it to friends. The link carries your referral code.',
        's2t'          => '2. They register',
        's2d'          => 'Anyone who registers through your link is permanently attached to you as a Level 1 member.',
        's3t'          => '3. Commission on every purchase',
        's3d'          => 'Every time they buy a service, your commission is credited straight to your main wallet — ready to withdraw. Subscription commission goes to your virtual wallet.',
        's4t'          => '4. Up to 3 levels deep',
        's4d'          => 'Whoever your Level 1 member brings in becomes your Level 2, and their referrals become your Level 3. You earn on all three.',
        'note'         => 'Commission rates are set per service by the admin. Service-sale commission lands in your main wallet and can be withdrawn to your bank; subscription commission lands in your virtual wallet and can be spent on any purchase.',
        'my_team'      => 'My referred members',
        'search_ph'    => 'Search by name, mobile number or ID...',
        'all_levels'   => 'All levels',
        'level'        => 'Level',
        'all_status'   => 'All members',
        'subscribed'   => 'Subscribed',
        'not_sub'      => 'Not subscribed',
        'ordered'      => 'Has ordered',
        'not_ordered'  => 'No orders yet',
        'user'         => 'Member',
        'joined'       => 'Joined',
        'orders'       => 'Orders',
        'status'       => 'Status',
        'contact'      => 'Contact',
        'none'         => 'No referred members yet.',
        'nomatch'      => 'No member matches this filter.',
        'free_user'    => 'Free member',
        'locked_t'     => 'Referral program is locked',
        'locked_d'     => 'An active subscription is required to unlock the referral system and start earning commission.',
        'benefits'     => 'Subscription benefits',
        'one_time'     => 'One-time fee',
        'subscribe'    => 'Subscribe now',
        'help_t'       => 'Need help?',
        'help_d'       => 'Contact us about anything related to referrals or commission.',
        'wa_us'        => 'WhatsApp us',
        'mail_us'      => 'Email us',
    ],
];
$t = $T[$current_lang] ?? $T['en'];
$tx = function ($k) use ($t, $T) { return $t[$k] ?? ($T['en'][$k] ?? $k); };

/* ---------------------------- REFERRAL DATA ---------------------------- */
$referral_code = "WBMCZ" . str_pad($user_id, 4, '0', STR_PAD_LEFT);
$referral_link = SITE_URL . "/register.php?ref=" . $referral_code;

$ref_data = $db->select("SELECT COUNT(id) as total FROM users WHERE referred_by = ?", [$user_id]);
$total_referrals = !empty($ref_data[0]['total']) ? (int)$ref_data[0]['total'] : 0;

/* Total commission earned — the share ledger is the source of truth, with the
   old transaction rows kept as a fallback for pre-ledger history. */
$total_earned = 0.00;
try {
    $e = $db->select("SELECT SUM(amount) as total FROM product_share_ledger WHERE share_type = 'referral' AND beneficiary_id = ?", [$user_id]);
    $total_earned = !empty($e[0]['total']) ? (float)$e[0]['total'] : 0.00;
} catch (\Throwable $ex) {}
if ($total_earned <= 0) {
    $e = $db->select("SELECT SUM(amount) as total FROM transactions WHERE user_id = ? AND description LIKE '%Referral Commission%' AND status = 'Success'", [$user_id]);
    $total_earned = !empty($e[0]['total']) ? (float)$e[0]['total'] : 0.00;
}

/* ---- Referred members, 3 levels deep ---- */
$referred_users_list = [];
$level1 = $db->select("SELECT id, name, mobile, email, call_number, whatsapp_number, created_at, is_subscribed FROM users WHERE referred_by = ?", [$user_id]);
$l1_ids = [];
foreach ($level1 as $u) { $u['level'] = 1; $referred_users_list[] = $u; $l1_ids[] = $u['id']; }

$l2_ids = [];
if (!empty($l1_ids)) {
    $ph = implode(',', array_fill(0, count($l1_ids), '?'));
    foreach ($db->select("SELECT id, name, mobile, email, call_number, whatsapp_number, created_at, is_subscribed FROM users WHERE referred_by IN ($ph)", $l1_ids) as $u) {
        $u['level'] = 2; $referred_users_list[] = $u; $l2_ids[] = $u['id'];
    }
}
if (!empty($l2_ids)) {
    $ph = implode(',', array_fill(0, count($l2_ids), '?'));
    foreach ($db->select("SELECT id, name, mobile, email, call_number, whatsapp_number, created_at, is_subscribed FROM users WHERE referred_by IN ($ph)", $l2_ids) as $u) {
        $u['level'] = 3; $referred_users_list[] = $u;
    }
}

/* ---- Order count per member (drives the "has ordered" filter) ---- */
$order_counts = [];
$all_ids = array_column($referred_users_list, 'id');
if (!empty($all_ids)) {
    $ph = implode(',', array_fill(0, count($all_ids), '?'));
    foreach ($db->select("SELECT user_id, COUNT(id) AS c FROM orders WHERE user_id IN ($ph) GROUP BY user_id", $all_ids) as $r) {
        $order_counts[(int)$r['user_id']] = (int)$r['c'];
    }
}
foreach ($referred_users_list as &$__ru) {
    $__ru['order_count'] = $order_counts[(int)$__ru['id']] ?? 0;
}
unset($__ru);

usort($referred_users_list, function ($a, $b) { return strtotime($b['created_at']) - strtotime($a['created_at']); });

$team_total     = count($referred_users_list);
$team_subscribed = 0;
$lvl_counts = [1 => 0, 2 => 0, 3 => 0];
foreach ($referred_users_list as $r) {
    if (!empty($r['is_subscribed'])) $team_subscribed++;
    $lvl_counts[$r['level']] = ($lvl_counts[$r['level']] ?? 0) + 1;
}

$unread_notifs = $db->select("SELECT * FROM notifications WHERE user_id = ? AND is_read = 0 ORDER BY created_at DESC LIMIT 5", [$user_id]);

$wallet_balance = isset($user['wallet_balance']) ? $user['wallet_balance'] : '0.00';
$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');

/* Company contact — WhatsApp only (no direct calls) + email */
$company_phone_raw = getSetting('company_phone', '+91 9382064816');
$company_wa = preg_replace('/\D/', '', $company_phone_raw);
if (strlen($company_wa) === 10) { $company_wa = '91' . $company_wa; }
$company_email = getSetting('company_email', 'info@wbmcz.com');

$all_categories = $db->select("SELECT * FROM service_categories WHERE status = 1 ORDER BY display_order ASC");
$sidebar_subcats = [1 => [], 5 => []];
foreach ($db->select("SELECT id, category_id, title, icon_class FROM agency_sub_categories WHERE category_id IN (1,5) AND status = 1 ORDER BY category_id, id") as $__r) { $sidebar_subcats[$__r['category_id']][] = $__r; }

$referral_unlocked = (!empty($user['is_subscribed']) || ($user['user_type'] ?? 'customer') !== 'customer');
?>
<!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><?php echo htmlspecialchars($tx('title')); ?> - <?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>
    <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=Poppins:wght@600;700;800&family=Inter:wght@300;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>
<?php
require_once __DIR__ . '/includes/theme.php';
$__menu = theme_user_menu($sidebar_subcats, $all_categories);
theme_open([
    'panel'  => 'user',
    'base'   => '',
    'title'  => $tx('title'),
    'active' => 'refer',
    'user'   => $user,
    'wallet' => $wallet_balance,
    'notifs' => $unread_notifs,
    'logo'   => $company_logo,
    'brand'  => $company_name,
    'menu'   => $__menu,
    'state'  => "q: '', lvl: 'all', st: 'all'",
]);
?>

            <main class="flex-1 overflow-y-auto p-4 md:p-6 lg:p-8">

                <!-- ===== HERO ===== -->
                <div class="bg-gradient-to-br from-indigo-600 to-purple-700 rounded-3xl p-6 md:p-8 text-white shadow-lg relative overflow-hidden mb-6">
                    <div class="absolute -right-10 -top-10 w-48 h-48 bg-white/10 rounded-full blur-2xl"></div>
                    <div class="relative z-10 flex flex-col md:flex-row items-center justify-between gap-6">
                        <div class="text-center md:text-left">
                            <h2 class="text-2xl md:text-4xl font-extrabold mb-2"><?php echo htmlspecialchars($tx('title')); ?></h2>
                            <p class="text-indigo-100 text-sm md:text-base max-w-2xl"><?php echo htmlspecialchars($tx('subtitle')); ?></p>
                        </div>
                        <div class="w-20 h-20 bg-white/20 rounded-full flex items-center justify-center border border-white/30 flex-shrink-0">
                            <i class="fas fa-gift text-3xl text-yellow-300"></i>
                        </div>
                    </div>
                </div>

                <!-- ===== REFERRAL LINK ===== -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 p-6 md:p-8 mb-6 text-center">
                    <h3 class="text-lg font-bold text-gray-800 mb-4"><?php echo htmlspecialchars($tx('your_link')); ?></h3>

                    <?php if ($referral_unlocked): ?>
                        <div class="flex flex-col sm:flex-row items-center justify-center max-w-3xl mx-auto gap-3">
                            <div class="relative w-full">
                                <span class="absolute inset-y-0 left-0 flex items-center pl-4 text-gray-400"><i class="fas fa-link"></i></span>
                                <input type="text" id="refLink" value="<?php echo htmlspecialchars($referral_link); ?>" readonly class="w-full py-4 pl-12 pr-4 bg-gray-50 border border-gray-200 rounded-xl text-gray-600 font-medium focus:outline-none">
                            </div>
                            <button onclick="copyReferralLink()" class="w-full sm:w-auto bg-indigo-600 hover:bg-indigo-700 text-white font-bold py-4 px-6 rounded-xl shadow-md transition-colors flex items-center justify-center whitespace-nowrap">
                                <i class="fas fa-copy mr-2"></i> <span id="copyBtnText"><?php echo htmlspecialchars($tx('copy')); ?></span>
                            </button>
                            <?php $__share = "Join " . $company_name . " and start earning!\n\nRegister with my referral link:\n" . $referral_link; ?>
                            <a href="https://wa.me/?text=<?php echo rawurlencode($__share); ?>" target="_blank" rel="noopener noreferrer"
                               class="w-full sm:w-auto bg-[#25D366] hover:bg-[#1da851] text-white font-bold py-4 px-6 rounded-xl shadow-md transition-colors flex items-center justify-center whitespace-nowrap">
                                <i class="fab fa-whatsapp text-xl mr-2"></i> WhatsApp
                            </a>
                            <a href="mailto:?subject=<?php echo rawurlencode('Join ' . $company_name); ?>&body=<?php echo rawurlencode($__share); ?>"
                               class="w-full sm:w-auto bg-slate-800 hover:bg-slate-900 text-white font-bold py-4 px-6 rounded-xl shadow-md transition-colors flex items-center justify-center whitespace-nowrap">
                                <i class="fas fa-envelope mr-2"></i> Email
                            </a>
                        </div>
                        <p class="text-xs text-slate-400 mt-4">Referral code: <b class="text-slate-600"><?php echo htmlspecialchars($referral_code); ?></b></p>
                    <?php else: ?>
                        <div class="bg-amber-50 border border-amber-200 p-8 rounded-2xl">
                            <i class="fas fa-lock text-5xl text-amber-500 mb-4"></i>
                            <h4 class="text-amber-900 text-2xl font-extrabold mb-2"><?php echo htmlspecialchars($tx('locked_t')); ?></h4>
                            <p class="text-amber-700 mb-6"><?php echo htmlspecialchars($tx('locked_d')); ?></p>

                            <div class="max-w-md mx-auto bg-white rounded-xl p-6 border border-amber-100 shadow-sm mb-6 text-left">
                                <h5 class="font-bold text-gray-800 mb-3 text-center border-b pb-2"><?php echo htmlspecialchars($tx('benefits')); ?></h5>
                                <ul class="space-y-2 text-sm text-gray-600">
                                    <?php
                                    $features_text = getSetting('subscription_features', "Unlock Referral Income (Up to 3 Levels)\nExclusive Purchase Discounts\nUpgrade to Seller Account\nPriority Quick Support");
                                    foreach (array_filter(array_map('trim', explode("\n", $features_text))) as $feature): ?>
                                    <li><i class="fas fa-check text-emerald-500 mr-2"></i> <?php echo htmlspecialchars($feature); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                                <div class="mt-4 pt-4 border-t text-center">
                                    <span class="text-gray-500 text-xs uppercase font-bold tracking-wider"><?php echo htmlspecialchars($tx('one_time')); ?></span>
                                    <div class="text-3xl font-extrabold text-gray-900">₹<?php echo number_format((float)$subscription_price, 2); ?></div>
                                </div>
                            </div>

                            <a href="subscription.php" class="bg-gradient-to-r from-amber-500 to-orange-500 hover:from-amber-600 hover:to-orange-600 text-white font-bold py-3 px-8 rounded-xl transition-all shadow-md inline-flex items-center text-lg">
                                <i class="fas fa-bolt mr-2"></i> <?php echo htmlspecialchars($tx('subscribe')); ?>
                            </a>
                        </div>
                    <?php endif; ?>
                </div>

                <!-- ===== STATS ===== -->
                <div class="grid grid-cols-2 lg:grid-cols-4 gap-3 sm:gap-4 mb-6">
                    <?php
                    $__stats = [
                        [$tx('total_ref'),  number_format($total_referrals),        'fa-user-plus',  'bg-blue-50 text-blue-600'],
                        [$tx('team'),       number_format($team_total),             'fa-sitemap',    'bg-indigo-50 text-indigo-600'],
                        [$tx('active_sub'), number_format($team_subscribed),        'fa-crown',      'bg-amber-50 text-amber-600'],
                        [$tx('total_earn'), '₹' . number_format($total_earned, 2),  'fa-wallet',     'bg-emerald-50 text-emerald-600'],
                    ];
                    foreach ($__stats as $s): ?>
                        <div class="tp-card p-4 sm:p-5">
                            <span class="w-10 h-10 rounded-xl flex items-center justify-center <?php echo $s[3]; ?>"><i class="fas <?php echo $s[2]; ?>"></i></span>
                            <p class="text-xl sm:text-2xl font-extrabold mt-3 leading-none break-all"><?php echo $s[1]; ?></p>
                            <p class="text-[11px] text-slate-500 font-semibold mt-1"><?php echo htmlspecialchars($s[0]); ?></p>
                        </div>
                    <?php endforeach; ?>
                </div>

                <!-- ===== HOW IT WORKS (corrected copy) ===== -->
                <div class="bg-white rounded-2xl p-6 md:p-8 border border-gray-200 mb-6">
                    <h3 class="text-xl font-bold text-center text-gray-800 mb-6"><?php echo htmlspecialchars($tx('how')); ?></h3>
                    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-4 gap-4">
                        <?php
                        $__steps = [
                            ['fa-share-nodes',  'indigo',  $tx('s1t'), $tx('s1d')],
                            ['fa-user-plus',    'purple',  $tx('s2t'), $tx('s2d')],
                            ['fa-indian-rupee-sign', 'emerald', $tx('s3t'), $tx('s3d')],
                            ['fa-layer-group',  'amber',   $tx('s4t'), $tx('s4d')],
                        ];
                        foreach ($__steps as $s): ?>
                        <div class="bg-slate-50 p-5 rounded-2xl border border-slate-200">
                            <div class="w-11 h-11 bg-<?php echo $s[1]; ?>-100 text-<?php echo $s[1]; ?>-600 rounded-xl flex items-center justify-center text-lg mb-3">
                                <i class="fas <?php echo $s[0]; ?>"></i>
                            </div>
                            <h4 class="font-bold text-gray-800 mb-1.5 text-sm"><?php echo htmlspecialchars($s[2]); ?></h4>
                            <p class="text-xs text-gray-500 leading-relaxed"><?php echo htmlspecialchars($s[3]); ?></p>
                        </div>
                        <?php endforeach; ?>
                    </div>
                    <p class="text-xs text-slate-500 bg-slate-50 border border-slate-200 rounded-xl px-4 py-3 mt-5 leading-relaxed">
                        <i class="fas fa-circle-info text-slate-400 mr-1.5"></i><?php echo htmlspecialchars($tx('note')); ?>
                    </p>
                </div>

                <!-- ===== TEAM + SEARCH ===== -->
                <div class="bg-white rounded-2xl shadow-sm border border-gray-200 overflow-hidden">
                    <div class="p-5 border-b border-gray-100 bg-gray-50/50">
                        <div class="flex flex-wrap items-center justify-between gap-3 mb-4">
                            <h3 class="text-lg font-bold text-gray-800"><?php echo htmlspecialchars($tx('my_team')); ?></h3>
                            <span class="bg-indigo-100 text-indigo-700 py-1 px-3 rounded-full text-xs font-bold"
                                  x-text="$refs.tbody ? ($refs.tbody.querySelectorAll('tr.ref-row:not([hidden])').length + ' / <?php echo $team_total; ?>') : '<?php echo $team_total; ?>'"></span>
                        </div>

                        <!-- search + filters -->
                        <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
                            <div class="relative lg:col-span-2">
                                <i class="fas fa-magnifying-glass absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 text-sm"></i>
                                <input type="text" x-model="q" @input="filterRefs()"
                                       placeholder="<?php echo htmlspecialchars($tx('search_ph')); ?>"
                                       class="w-full py-3 pl-11 pr-4 bg-white border border-gray-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-indigo-500">
                            </div>
                            <select x-model="lvl" @change="filterRefs()" class="w-full py-3 px-4 bg-white border border-gray-200 rounded-xl text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <option value="all"><?php echo htmlspecialchars($tx('all_levels')); ?> (<?php echo $team_total; ?>)</option>
                                <option value="1"><?php echo htmlspecialchars($tx('level')); ?> 1 (<?php echo $lvl_counts[1]; ?>)</option>
                                <option value="2"><?php echo htmlspecialchars($tx('level')); ?> 2 (<?php echo $lvl_counts[2]; ?>)</option>
                                <option value="3"><?php echo htmlspecialchars($tx('level')); ?> 3 (<?php echo $lvl_counts[3]; ?>)</option>
                            </select>
                            <select x-model="st" @change="filterRefs()" class="w-full py-3 px-4 bg-white border border-gray-200 rounded-xl text-sm font-semibold focus:outline-none focus:ring-2 focus:ring-indigo-500">
                                <option value="all"><?php echo htmlspecialchars($tx('all_status')); ?></option>
                                <option value="sub"><?php echo htmlspecialchars($tx('subscribed')); ?></option>
                                <option value="nosub"><?php echo htmlspecialchars($tx('not_sub')); ?></option>
                                <option value="ord"><?php echo htmlspecialchars($tx('ordered')); ?></option>
                                <option value="noord"><?php echo htmlspecialchars($tx('not_ordered')); ?></option>
                            </select>
                        </div>
                    </div>

                    <div class="overflow-x-auto">
                        <table class="w-full text-left border-collapse">
                            <thead>
                                <tr class="bg-gray-50 border-b border-gray-100 text-gray-500 text-xs uppercase tracking-wider">
                                    <th class="py-3.5 px-5 font-semibold"><?php echo htmlspecialchars($tx('user')); ?></th>
                                    <th class="py-3.5 px-5 font-semibold"><?php echo htmlspecialchars($tx('level')); ?></th>
                                    <th class="py-3.5 px-5 font-semibold"><?php echo htmlspecialchars($tx('joined')); ?></th>
                                    <th class="py-3.5 px-5 font-semibold text-center"><?php echo htmlspecialchars($tx('orders')); ?></th>
                                    <th class="py-3.5 px-5 font-semibold"><?php echo htmlspecialchars($tx('status')); ?></th>
                                    <th class="py-3.5 px-5 font-semibold text-center"><?php echo htmlspecialchars($tx('contact')); ?></th>
                                </tr>
                            </thead>
                            <tbody x-ref="tbody" class="divide-y divide-gray-100 text-sm">
                                <?php if (empty($referred_users_list)): ?>
                                    <tr>
                                        <td colspan="6" class="py-10 text-center text-gray-500">
                                            <i class="fas fa-user-friends text-3xl mb-3 text-gray-300 block"></i>
                                            <?php echo htmlspecialchars($tx('none')); ?>
                                        </td>
                                    </tr>
                                <?php else: ?>
                                    <?php foreach ($referred_users_list as $r_user):
                                        $rc = trim((string)($r_user['call_number'] ?: $r_user['mobile']));
                                        $rw = preg_replace('/\D/', '', (string)($r_user['whatsapp_number'] ?: $r_user['mobile']));
                                        if ($rw !== '' && strlen($rw) === 10) { $rw = '91' . $rw; }
                                        $re = trim((string)($r_user['email'] ?? ''));
                                        $is_sub = !empty($r_user['is_subscribed']);
                                        $oc = (int)$r_user['order_count'];
                                        $hay = strtolower($r_user['name'] . ' ' . $r_user['mobile'] . ' ' . $re . ' ' . $r_user['id'] . ' wbmcz' . str_pad($r_user['id'], 4, '0', STR_PAD_LEFT));
                                    ?>
                                        <tr class="ref-row hover:bg-gray-50 transition-colors"
                                            data-search="<?php echo htmlspecialchars($hay, ENT_QUOTES); ?>"
                                            data-level="<?php echo $r_user['level']; ?>"
                                            data-sub="<?php echo $is_sub ? 1 : 0; ?>"
                                            data-orders="<?php echo $oc; ?>">
                                            <td class="py-3.5 px-5">
                                                <div class="font-bold text-gray-900"><?php echo htmlspecialchars($r_user['name']); ?></div>
                                                <div class="text-gray-500 text-xs mt-0.5">
                                                    ID #<?php echo (int)$r_user['id']; ?>
                                                    <?php if (!empty($r_user['mobile'])): ?> · <?php echo htmlspecialchars($r_user['mobile']); ?><?php endif; ?>
                                                </div>
                                            </td>
                                            <td class="py-3.5 px-5">
                                                <?php
                                                $lc = [1 => 'bg-blue-50 text-blue-700 border-blue-100', 2 => 'bg-purple-50 text-purple-700 border-purple-100', 3 => 'bg-teal-50 text-teal-700 border-teal-100'][$r_user['level']];
                                                ?>
                                                <span class="<?php echo $lc; ?> py-1 px-2.5 rounded-md text-xs font-bold border whitespace-nowrap">
                                                    <?php echo htmlspecialchars($tx('level')); ?> <?php echo $r_user['level']; ?>
                                                </span>
                                            </td>
                                            <td class="py-3.5 px-5 text-gray-500 whitespace-nowrap"><?php echo date('d M Y', strtotime($r_user['created_at'])); ?></td>
                                            <td class="py-3.5 px-5 text-center">
                                                <span class="inline-flex items-center justify-center min-w-[28px] h-7 px-2 rounded-lg text-xs font-bold <?php echo $oc > 0 ? 'bg-indigo-50 text-indigo-700' : 'bg-slate-100 text-slate-400'; ?>"><?php echo $oc; ?></span>
                                            </td>
                                            <td class="py-3.5 px-5">
                                                <?php if ($is_sub): ?>
                                                    <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-100 text-emerald-800 whitespace-nowrap">
                                                        <i class="fas fa-crown mr-1 text-amber-500"></i> <?php echo htmlspecialchars($tx('subscribed')); ?>
                                                    </span>
                                                <?php else: ?>
                                                    <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-bold bg-gray-100 text-gray-600 whitespace-nowrap"><?php echo htmlspecialchars($tx('free_user')); ?></span>
                                                <?php endif; ?>
                                            </td>
                                            <td class="py-3.5 px-5">
                                                <div class="flex items-center justify-center gap-2">
                                                    <?php if ($rc !== ''): ?>
                                                        <a href="tel:<?php echo htmlspecialchars($rc); ?>" title="Call <?php echo htmlspecialchars($rc); ?>"
                                                           class="w-9 h-9 rounded-xl bg-blue-50 hover:bg-blue-100 text-blue-600 border border-blue-100 flex items-center justify-center transition-colors">
                                                            <i class="fas fa-phone text-sm"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                    <?php if ($rw !== ''): ?>
                                                        <a href="https://wa.me/<?php echo $rw; ?>" target="_blank" rel="noopener noreferrer" title="WhatsApp"
                                                           class="w-9 h-9 rounded-xl bg-[#25D366] hover:bg-[#1da851] text-white flex items-center justify-center transition-colors">
                                                            <i class="fab fa-whatsapp text-base"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                    <?php if ($re !== ''): ?>
                                                        <a href="mailto:<?php echo htmlspecialchars($re); ?>" title="<?php echo htmlspecialchars($re); ?>"
                                                           class="w-9 h-9 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-600 border border-slate-200 flex items-center justify-center transition-colors">
                                                            <i class="fas fa-envelope text-sm"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                    <?php if ($rc === '' && $rw === '' && $re === ''): ?>
                                                        <span class="text-xs text-gray-300">&mdash;</span>
                                                    <?php endif; ?>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                    <tr id="refNoMatch" hidden>
                                        <td colspan="6" class="py-10 text-center text-gray-500">
                                            <i class="fas fa-filter-circle-xmark text-3xl mb-3 text-gray-300 block"></i>
                                            <?php echo htmlspecialchars($tx('nomatch')); ?>
                                        </td>
                                    </tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>

                <!-- ===== COMPANY CONTACT — WhatsApp only + email ===== -->
                <div class="mt-6 mb-20 bg-white rounded-2xl border border-gray-200 p-6 flex flex-col md:flex-row items-center justify-between gap-4">
                    <div class="text-center md:text-left">
                        <h4 class="font-bold text-gray-800"><?php echo htmlspecialchars($tx('help_t')); ?></h4>
                        <p class="text-sm text-gray-500 mt-1"><?php echo htmlspecialchars($tx('help_d')); ?></p>
                    </div>
                    <div class="flex flex-wrap items-center justify-center gap-3">
                        <a href="https://wa.me/<?php echo htmlspecialchars($company_wa); ?>?text=<?php echo rawurlencode('Hello ' . $company_name . ', I need help with the referral program. My member ID is WBMCZ' . str_pad($user_id, 4, '0', STR_PAD_LEFT) . '.'); ?>"
                           target="_blank" rel="noopener noreferrer"
                           class="inline-flex items-center gap-2 bg-[#25D366] hover:bg-[#1da851] text-white font-bold py-3 px-6 rounded-xl shadow-md transition-colors">
                            <i class="fab fa-whatsapp text-lg"></i> <?php echo htmlspecialchars($tx('wa_us')); ?>
                        </a>
                        <a href="mailto:<?php echo htmlspecialchars($company_email); ?>?subject=<?php echo rawurlencode('Referral support — WBMCZ' . str_pad($user_id, 4, '0', STR_PAD_LEFT)); ?>"
                           class="inline-flex items-center gap-2 bg-slate-800 hover:bg-slate-900 text-white font-bold py-3 px-6 rounded-xl shadow-md transition-colors">
                            <i class="fas fa-envelope"></i> <?php echo htmlspecialchars($tx('mail_us')); ?>
                        </a>
                    </div>
                </div>

            </main>
        </div>
    </div>

    <script>
    function copyReferralLink() {
        var copyText = document.getElementById("refLink");
        if (!copyText) return;
        copyText.select(); copyText.setSelectionRange(0, 99999);
        navigator.clipboard.writeText(copyText.value).then(function () {
            var b = document.getElementById("copyBtnText");
            var o = b.innerHTML;
            b.innerHTML = <?php echo json_encode($tx('copied')); ?>;
            setTimeout(function () { b.innerHTML = o; }, 2000);
        });
    }

    /* Search + level + status filtering, all client side */
    function filterRefs() {
        var root  = document.querySelector('[x-ref="tbody"]') || document.querySelector('tbody');
        if (!root) return;
        var qEl   = document.querySelector('[x-model="q"]');
        var lEl   = document.querySelector('[x-model="lvl"]');
        var sEl   = document.querySelector('[x-model="st"]');
        var q     = (qEl ? qEl.value : '').trim().toLowerCase();
        var lvl   = lEl ? lEl.value : 'all';
        var st    = sEl ? sEl.value : 'all';
        var rows  = root.querySelectorAll('tr.ref-row');
        var shown = 0;

        rows.forEach(function (row) {
            var ok = true;
            if (q && row.dataset.search.indexOf(q) === -1) ok = false;
            if (ok && lvl !== 'all' && row.dataset.level !== lvl) ok = false;
            if (ok && st !== 'all') {
                var sub = row.dataset.sub === '1';
                var ord = parseInt(row.dataset.orders, 10) > 0;
                if (st === 'sub'   && !sub) ok = false;
                if (st === 'nosub' &&  sub) ok = false;
                if (st === 'ord'   && !ord) ok = false;
                if (st === 'noord' &&  ord) ok = false;
            }
            row.hidden = !ok;
            if (ok) shown++;
        });

        var empty = document.getElementById('refNoMatch');
        if (empty) empty.hidden = (shown !== 0 || rows.length === 0);
    }
    </script>
</body>
</html>
