<?php
session_start();
// ডাটাবেস কানেকশন
$db_path = file_exists('includes/db.php') ? 'includes/db.php' : '../includes/db.php';
if (file_exists($db_path)) {
    require $db_path;
} else {
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// লগইন চেক
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$user_id_display = $_SESSION['user_id'] ?? '0000';

// ইনভাইটেশন কোড জেনারেট (ইউজার আইডির সাথে কিছু স্ট্রিং মিলিয়ে বা শুধু ইউজার আইডি)
// এখানে সিম্পল রাখা হয়েছে, চাইলে uniqid() বা অন্য লজিক ব্যবহার করতে পারেন
$invite_code = "QXR" . $user_id_display . "J7"; 

// রেফারেল লিংক
$base_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
$referral_link = $base_url . "/signup.php?r=" . $invite_code;

// QR Code API (Using Google Chart API for simplicity)
$qr_code_url = "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" . urlencode($referral_link);

// ড্যাশবোর্ড থেকে রেফারেল ডাটা (মক ডাটা বা ডাটাবেস থেকে আনতে পারেন)
$referral_count = 0;
$today_reward = 0;
$yesterday_reward = 0;
$total_reward = 0; // Available to claim
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Referral</title>
    <script src="https://cdn.tailwindcss.com"></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=Roboto:wght@400;500;700&display=swap" rel="stylesheet">

    <style>
        body { 
            background-color: #121619; 
            color: #d1d5db; 
            font-family: 'Roboto', sans-serif; 
            padding-bottom: 90px;
        }

        /* --- Header --- */
        .header-bg { background-color: #181c20; }

        /* --- Tabs --- */
        .tabs-container {
            display: flex;
            background-color: #181c20;
            border-bottom: 1px solid #2f3840;
        }
        .tab-btn {
            flex: 1;
            text-align: center;
            padding: 15px 0;
            font-size: 14px;
            font-weight: 500;
            color: #9ca3af;
            cursor: pointer;
            position: relative;
        }
        .tab-btn.active {
            color: #fff;
            font-weight: bold;
        }
        .tab-btn.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 2px;
            background-color: #fff; /* White underline like image */
        }

        /* --- Cards --- */
        .dark-card {
            background-color: #1c2227;
            border: 1px solid #2f3840;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        
        .section-title {
            border-left: 3px solid #eab308;
            padding-left: 8px;
            font-size: 14px;
            color: #d1d5db;
            margin-bottom: 15px;
            font-weight: 500;
        }

        /* --- Input Fields --- */
        .copy-box {
            background-color: #232a31;
            border: 1px solid #374151;
            border-radius: 4px;
            display: flex;
            align-items: center;
            padding: 2px;
            margin-top: 5px;
        }
        .copy-input {
            background: transparent;
            border: none;
            color: #fff;
            width: 100%;
            padding: 8px;
            font-size: 13px;
            outline: none;
        }
        .copy-btn {
            background-color: #eab308;
            color: #000;
            font-weight: bold;
            font-size: 12px;
            padding: 8px 15px;
            border-radius: 4px;
            white-space: nowrap;
        }
        .copy-icon-btn {
            background-color: #eab308;
            width: 35px; height: 35px;
            display: flex; align-items: center; justify-content: center;
            border-radius: 4px; color: #000;
        }

        /* --- Stats Grid --- */
        .stat-grid {
            display: grid;
            grid-template-columns: repeat(3, 1fr);
            text-align: center;
            gap: 10px;
            padding: 10px 0;
            background-color: #232a31;
            border-radius: 8px;
            margin-top: 15px;
        }
        .stat-item h4 { font-size: 10px; color: #9ca3af; margin-bottom: 5px; }
        .stat-item p { font-size: 14px; color: #fff; font-weight: bold; }

        /* --- Claim Section --- */
        .claim-row {
            display: flex; justify-content: space-between; align-items: center;
            padding-top: 10px;
        }
        .claim-btn {
            background-color: #7c5e26; /* Dark Gold/Brown */
            color: #d4b168;
            font-weight: bold;
            font-size: 12px;
            padding: 6px 20px;
            border-radius: 4px;
            border: 1px solid #d4b168;
        }

        /* --- Pyramid Image --- */
        .pyramid-img {
            width: 100%;
            max-width: 300px;
            margin: 20px auto;
            display: block;
        }

        /* --- Details Tab --- */
        .filter-bar {
            display: flex;
            background-color: #232a31;
            padding: 5px;
            margin-bottom: 2px;
        }
        .filter-btn {
            flex: 1;
            text-align: center;
            font-size: 12px;
            color: #9ca3af;
            padding: 8px 0;
            border-right: 1px solid #374151;
        }
        .filter-btn:last-child { border-right: none; }
        .filter-icon {
            background-color: #1c2227;
            width: 40px;
            display: flex; align-items: center; justify-content: center;
            border-left: 1px solid #374151;
        }

        /* Tab Content Logic */
        .tab-content { display: none; }
        .tab-content.active { display: block; }

        /* Bottom Nav */
        .bottom-nav { background-color: #000; border-top: 1px solid #222; }
        .nav-item { color: #6b7280; }
        .nav-item.active { color: #facc15; }
    </style>
</head>
<body>

    <div class="header-bg p-4 flex justify-between items-center sticky top-0 z-50">
        <a href="dashboard.php" class="text-white text-xl"><i class="fas fa-home"></i></a>
        <h1 class="text-white font-medium text-lg">Referral</h1>
        <button onclick="window.history.back()" class="text-white text-lg"><i class="fas fa-times"></i></button>
    </div>

    <div class="tabs-container sticky top-[60px] z-40">
        <div class="tab-btn active" onclick="switchTab('invite', this)">Invite</div>
        <div class="tab-btn" onclick="switchTab('details', this)">Details</div>
    </div>

    <div id="invite" class="tab-content active p-4">
        
        <div class="dark-card p-0 overflow-hidden relative">
            <div class="p-3">
                <div class="sec-title mb-2">Refer Your Friends and Earn</div>
                <img src="../assets/img/refer_banner.png" onerror="this.src='https://placehold.co/600x200/111/eab308?text=REFER+A+FRIEND'" class="w-full rounded mb-4">
                
                <div class="flex gap-4">
                    <div class="bg-white p-2 rounded w-[100px] h-[100px] flex-shrink-0">
                        <img src="<?php echo $qr_code_url; ?>" class="w-full h-full object-contain">
                    </div>
                    
                    <div class="flex-1 flex flex-col justify-between">
                        <div>
                            <p class="text-[10px] text-gray-400 mb-1">Invitation Link</p>
                            <div class="copy-box">
                                <button class="w-full text-center text-xs font-bold text-[#eab308] py-1.5" onclick="copyToClipboard('<?php echo $referral_link; ?>')">Share</button>
                            </div>
                        </div>
                        <div>
                            <p class="text-[10px] text-gray-400 mb-1">Invitation Code</p>
                            <div class="copy-box">
                                <input type="text" value="<?php echo $invite_code; ?>" readonly class="copy-input font-mono tracking-widest text-center">
                                <button class="copy-icon-btn" onclick="copyToClipboard('<?php echo $invite_code; ?>')">
                                    <i class="far fa-copy"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="stat-grid bg-[#232a31] mt-0 rounded-b-lg rounded-t-none border-t border-[#2f3840]">
                <div class="stat-item border-r border-[#374151]">
                    <h4>Referral Count</h4>
                    <p><?php echo $referral_count; ?></p>
                </div>
                <div class="stat-item border-r border-[#374151]">
                    <h4>Today's Rewards</h4>
                    <p>৳ <?php echo $today_reward; ?></p>
                </div>
                <div class="stat-item">
                    <h4>Yesterday's Rewards</h4>
                    <p>৳ <?php echo $yesterday_reward; ?></p>
                </div>
            </div>
        </div>

        <div class="dark-card">
            <div class="sec-title">Available Cash Rewards</div>
            <div class="claim-row">
                <span class="text-2xl text-[#facc15] font-bold">৳ <?php echo $total_reward; ?></span>
                <button class="claim-btn">Claim</button>
            </div>
        </div>

        <div class="dark-card">
            <div class="sec-title">How to earn more rewards</div>
            <p class="text-xs text-gray-400 leading-relaxed mb-4">
                All referrer will receive certain cash reward percentage for every referee when they play games on <?php echo 'Banglabet'; ?>.
            </p>
            
            <img src="../assets/img/refer_pyramid.png" onerror="this.src='https://placehold.co/400x200/1c2227/666?text=Pyramid+Chart'" class="pyramid-img">
            
            <p class="text-[10px] text-gray-500 text-center mb-1">Be diligent in referring, be the upline and earn up to 3 tiers easily!</p>
            <p class="text-sm text-[#facc15] font-bold text-center">Welcome to lifetime commissions!</p>
        </div>

    </div>

    <div id="details" class="tab-content">
        
        <div class="filter-bar">
            <div class="filter-btn text-white font-bold">Bonus Type-All</div>
            <div class="filter-btn">Status-All</div>
            <div class="filter-btn">Today</div>
            <div class="filter-icon">
                <i class="fas fa-filter text-white text-xs"></i>
            </div>
        </div>
        
        <div class="flex bg-[#2a3239] text-[10px] text-gray-400 py-2 px-2 border-b border-[#374151]">
            <div class="flex-1 text-center border-r border-[#374151]">Bonus Type</div>
            <div class="flex-1 text-center border-r border-[#374151]">Invited users</div>
            <div class="flex-1 text-center border-r border-[#374151]">Reward amount</div>
            <div class="flex-1 text-center">Status</div>
        </div>

        <div class="flex flex-col items-center justify-center h-[300px]">
            <img src="https://cdn-icons-png.flaticon.com/512/7486/7486747.png" class="w-16 h-16 opacity-20 invert mb-3">
            <p class="text-gray-600 text-xs">No Data</p>
        </div>

    </div>

    <div class="fixed bottom-0 left-0 w-full h-[60px] bottom-nav z-50 flex justify-between items-center px-6">
        <a href="index.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-home text-lg mb-1"></i>
            <span class="text-[10px]">Home</span>
        </a>
        <a href="promotions.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-gift text-lg mb-1"></i>
            <span class="text-[10px]">Promotions</span>
        </a>
        <a href="deposit.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-wallet text-lg mb-1"></i>
            <span class="text-[10px]">Deposit</span>
        </a>
        <a href="account.php" class="flex flex-col items-center justify-center nav-item">
            <i class="fas fa-user text-lg mb-1"></i>
            <span class="text-[10px]">My Account</span>
        </a>
    </div>

    <script>
        function switchTab(tabId, btn) {
            // Hide all tabs
            document.querySelectorAll('.tab-content').forEach(el => el.classList.remove('active'));
            // Show selected tab
            document.getElementById(tabId).classList.add('active');
            
            // Remove active class from buttons
            document.querySelectorAll('.tab-btn').forEach(el => el.classList.remove('active'));
            // Add active class to clicked button
            btn.classList.add('active');
        }

        function copyToClipboard(text) {
            navigator.clipboard.writeText(text).then(function() {
                // Simple toast or alert
                alert('Copied: ' + text); 
            }, function(err) {
                console.error('Could not copy text: ', err);
            });
        }
        
        // Share function using Web Share API
        function shareLink() {
            if (navigator.share) {
                navigator.share({
                    title: 'Join RUPOSHI88',
                    text: 'Join me on RUPOSHI88 and earn rewards!',
                    url: '<?php echo $referral_link; ?>',
                })
                .then(() => console.log('Successful share'))
                .catch((error) => console.log('Error sharing', error));
            } else {
                copyToClipboard('<?php echo $referral_link; ?>');
            }
        }
    </script>

</body>
</html>