<?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 {
    // Fallback Connection
    $conn = new mysqli('localhost', 'root', '', 'bajipari');
}

// Check Login
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];
$message = "";

// --- 1. HANDLE BONUS CLAIM ---
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    $b_id = intval($_POST['bonus_id']);
    $amount = floatval($_POST['amount']);

    if ($action == 'claim_personal') {
        // Personal Bonus Claim Logic
        $check = $conn->query("SELECT * FROM personal_bonuses WHERE id=$b_id AND user_id=$user_id AND status='pending'");
        if ($check && $check->num_rows > 0) {
            $conn->query("UPDATE users SET balance = balance + $amount WHERE id=$user_id");
            $conn->query("UPDATE personal_bonuses SET status='claimed' WHERE id=$b_id");
            $message = "অভিনন্দন! আপনি ৳$amount বোনাস পেয়েছেন।";
        }
    } elseif ($action == 'claim_global') {
        // Global Bonus Claim Logic
        $check = $conn->query("SELECT * FROM global_bonuses WHERE id=$b_id AND is_active=1");
        $already_claimed = $conn->query("SELECT id FROM bonus_claims WHERE user_id=$user_id AND bonus_id=$b_id");
        
        if ($check && $check->num_rows > 0 && ($already_claimed && $already_claimed->num_rows == 0)) {
            $conn->query("UPDATE users SET balance = balance + $amount WHERE id=$user_id");
            $conn->query("INSERT INTO bonus_claims (user_id, bonus_id) VALUES ($user_id, $b_id)");
            $message = "অভিনন্দন! গ্লোবাল বোনাস ৳$amount আপনার ব্যালেন্সে যোগ হয়েছে।";
        }
    }
}

// --- 2. FETCH DATA ---
$user = $conn->query("SELECT * FROM users WHERE id=$user_id")->fetch_assoc();

// Mock Data for Demo
$personal_claim = isset($conn) ? $conn->query("SELECT * FROM personal_bonuses WHERE user_id=$user_id AND category='claim' AND status='pending'") : false;
$cnt_claim = ($personal_claim) ? $personal_claim->num_rows : 0;
$cnt_recovery = 0; 
$cnt_promo = 0; 
$cnt_temu = 0;
?>

<!DOCTYPE html>
<html lang="bn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>পুরস্কার সেন্টার</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=Hind+Siliguri:wght@400;500;600;700&display=swap" rel="stylesheet">
    
    <style>
        body { font-family: 'Hind Siliguri', sans-serif; background-color: #f3f4f6; padding-bottom: 90px; }
        
        /* Header Gradient */
        .reward-header { 
            background: linear-gradient(180deg, #FF6B4A 0%, #FF9F4A 100%); 
            height: 240px; 
            border-bottom-left-radius: 25px; 
            border-bottom-right-radius: 25px; 
            position: relative;
        }
        
        /* Profile Card Glassmorphism */
        .profile-card { 
            background: rgba(255, 255, 255, 0.9); 
            backdrop-filter: blur(10px); 
            border-radius: 16px; 
            box-shadow: 0 10px 30px rgba(0,0,0,0.1); 
            margin-top: -80px; 
        }

        /* Grid Buttons Styling */
        .grid-btn {
            border-radius: 16px;
            padding: 20px;
            color: white;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            height: 120px;
            position: relative;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.2s;
            cursor: pointer;
        }
        .grid-btn:active { transform: scale(0.98); }
        
        /* Gradients */
        .bg-green-grad { background: linear-gradient(135deg, #34D399 0%, #10B981 100%); }
        .bg-blue-grad { background: linear-gradient(135deg, #60A5FA 0%, #3B82F6 100%); }
        .bg-pink-grad { background: linear-gradient(135deg, #F472B6 0%, #EC4899 100%); }
        .bg-orange-grad { background: linear-gradient(135deg, #FB923C 0%, #F97316 100%); }
        
        /* Icon Circle */
        .btn-icon {
            width: 45px; height: 45px; background: rgba(255,255,255,0.25); border-radius: 50%; display: flex; align-items: center; justify-content: center; margin-bottom: 8px; font-size: 20px;
        }
        
        .badge-count { 
            position: absolute; top: -2px; right: -2px; background: #EF4444; color: white; width: 20px; height: 20px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 10px; font-weight: bold; border: 2px solid white;
        }
    </style>
</head>
<body class="bg-gray-50">

    <?php if($message): ?>
    <div onclick="this.remove()" class="fixed top-4 left-4 right-4 bg-green-500 text-white p-3 rounded-lg shadow-lg z-[100] text-center text-xs animate-bounce">
        <?php echo $message; ?>
    </div>
    <?php endif; ?>

    <div class="reward-header px-4 pt-6">
        <div class="flex items-center text-white mb-6 relative z-10">
            <button onclick="window.history.back()" class="text-xl absolute left-0"><i class="fas fa-chevron-left"></i></button>
            <h1 class="text-lg font-bold w-full text-center">পুরস্কার সেন্টার</h1>
        </div>
        
        <h1 class="text-6xl font-black text-white opacity-10 text-center tracking-widest mt-4">REWARD</h1>
    </div>

    <div class="px-4">
        <div class="profile-card p-4 relative">
            
            <a href="rewardsignin.php" class="absolute top-0 right-0 bg-red-600 text-white text-[10px] font-bold px-3 py-1 rounded-bl-xl rounded-tr-xl flex items-center gap-1">
                <i class="far fa-check-square"></i> সাইন ইন <i class="fas fa-chevron-right text-[8px]"></i>
            </a>

            <div class="flex items-center gap-4">
                <div class="w-16 h-16 rounded-full border-2 border-gray-200 p-0.5">
                    <img src="../assets/images/avatar.png" onerror="this.src='https://ui-avatars.com/api/?name=<?php echo $user['username']; ?>&background=random'" class="w-full h-full object-cover rounded-full">
                </div>
                
                <div class="flex-1">
                    <div class="flex items-center gap-2">
                        <h2 class="font-bold text-gray-800 text-lg" id="usernameText"><?php echo $user['username']; ?></h2>
                        <i onclick="copyUsername()" class="far fa-copy text-gray-400 text-xs cursor-pointer active:text-green-500 transition"></i>
                    </div>
                    <p class="text-gray-500 text-xs mb-1">ডাকনাম: <?php echo $user['username']; ?> <i class="fas fa-pen text-[10px]"></i></p>
                    
                    <div class="flex items-center gap-1 text-gray-700 font-bold">
                        <span>৳ <?php echo number_format($user['balance'], 2); ?></span>
                        <i class="fas fa-sync-alt text-gray-400 text-xs animate-spin-slow"></i>
                    </div>
                </div>
            </div>

            <div class="mt-4">
                <a href="vip.php" class="flex justify-between items-center text-xs text-gray-500 mb-1 cursor-pointer hover:text-orange-500 transition">
                    <span class="flex items-center gap-1"><i class="fas fa-crown text-gray-400"></i> VIP0</span>
                    <span>সুবিধা <i class="fas fa-chevron-right text-[8px]"></i></span>
                </a>
                <div class="w-full bg-gray-200 rounded-full h-1.5">
                    <div class="bg-gray-400 h-1.5 rounded-full" style="width: 10%"></div>
                </div>
                <p class="text-right text-[10px] text-gray-400 mt-1">0 / 2</p>
            </div>
        </div>
    </div>

    <div class="px-4 mt-6 mb-6 grid grid-cols-2 gap-4">
        
        <div onclick="openModal('modal-claim')" class="grid-btn bg-green-grad">
            <div class="btn-icon relative">
                <i class="fas fa-gift"></i>
                <?php if($cnt_claim > 0): ?>
                    <div class="badge-count"><?php echo $cnt_claim; ?></div>
                <?php endif; ?>
            </div>
            <span class="text-sm font-bold">দাবি করা</span>
        </div>

        <a href="rewardsignin.php" class="grid-btn bg-blue-grad">
            <div class="btn-icon"><i class="far fa-calendar-check"></i></div>
            <span class="text-sm font-bold">সাইন ইন</span>
        </a>

        <a href="share.php" class="grid-btn bg-pink-grad">
            <div class="btn-icon"><i class="fas fa-user-plus"></i></div>
            <span class="text-sm font-bold text-center">বন্ধুদের আমন্ত্রণ জানান</span>
        </a>

        <div onclick="openModal('modal-temu')" class="grid-btn bg-orange-grad">
            <div class="btn-icon relative">
                <i class="fas fa-ticket-alt"></i>
                <?php if($cnt_temu > 0): ?>
                    <div class="badge-count"><?php echo $cnt_temu; ?></div>
                <?php endif; ?>
            </div>
            <span class="text-sm font-bold">টেমু টিকিট</span>
        </div>

    </div>

    <div id="modal-claim" class="fixed inset-0 bg-black/80 z-[60] hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl w-full max-w-sm p-5 relative">
            <button onclick="closeModal('modal-claim')" class="absolute top-2 right-3 text-gray-500 text-xl">&times;</button>
            <h3 class="text-lg font-bold text-center text-green-600 mb-4">বোনাস দাবি করুন</h3>
            
            <div class="space-y-3 max-h-60 overflow-y-auto">
                <?php if($cnt_claim > 0): ?>
                    <?php while($row = $personal_claim->fetch_assoc()): ?>
                    <form method="POST" class="bg-green-50 p-3 rounded-lg border border-green-200 flex justify-between items-center">
                        <div>
                            <p class="font-bold text-gray-800 text-sm"><?php echo $row['description']; ?></p>
                            <p class="text-green-600 font-bold">৳ <?php echo $row['amount']; ?></p>
                        </div>
                        <input type="hidden" name="action" value="claim_personal">
                        <input type="hidden" name="bonus_id" value="<?php echo $row['id']; ?>">
                        <input type="hidden" name="amount" value="<?php echo $row['amount']; ?>">
                        <button class="bg-green-500 text-white px-4 py-1.5 rounded-full text-xs font-bold shadow">দাবি</button>
                    </form>
                    <?php endwhile; ?>
                <?php else: ?>
                    <p class="text-center text-gray-400 text-sm py-4">কোন বোনাস উপলব্ধ নেই</p>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div id="modal-temu" class="fixed inset-0 bg-black/80 z-[60] hidden flex items-center justify-center p-4">
        <div class="bg-white rounded-xl w-full max-w-sm p-5 relative">
            <button onclick="closeModal('modal-temu')" class="absolute top-2 right-3 text-gray-500 text-xl">&times;</button>
            <h3 class="text-lg font-bold text-center text-orange-600 mb-4">টেমু টিকিট</h3>
            <p class="text-center text-gray-400 text-sm py-4">কোন টিকিট নেই</p>
        </div>
    </div>

    <div class="fixed bottom-0 w-full h-[70px] bg-[#1a1a1a] border-t border-gray-800 z-50 flex justify-between px-2 items-center">
        
        <a href="dashboard.php" class="flex flex-col items-center justify-center w-1/5 h-full text-gray-500 hover:text-white transition">
            <i class="fas fa-home text-xl mb-1"></i>
            <span class="text-[10px]">হোম</span>
        </a>
        
        <a href="promotions.php" class="flex flex-col items-center justify-center w-1/5 h-full text-gray-500 hover:text-white transition">
            <i class="fas fa-gift text-xl mb-1"></i>
            <span class="text-[10px]">প্রমোশন</span>
        </a>
        
        <div class="w-1/5 h-full relative flex justify-center">
            <a href="share.php" class="absolute -top-6 w-14 h-14 bg-[#1a1a1a] rounded-full border-t border-gray-800 flex items-center justify-center">
                <div class="w-11 h-11 bg-gradient-to-br from-[#F4C66E] to-[#D97706] rounded-full flex items-center justify-center text-black text-xl shadow-lg border border-[#FDE047]/20">
                    <i class="fas fa-share-alt"></i>
                </div>
            </a>
            <span class="absolute bottom-2 text-[10px] text-gray-500">শেয়ার</span>
        </div>

        <a href="rewards.php" class="flex flex-col items-center justify-center w-1/5 h-full text-[#F4C66E]">
            <i class="fas fa-trophy text-xl mb-1"></i>
            <span class="text-[10px] font-bold">পুরস্কার</span>
        </a>
        
        <a href="account.php" class="flex flex-col items-center justify-center w-1/5 h-full text-gray-500 hover:text-white transition">
            <i class="fas fa-user text-xl mb-1"></i>
            <span class="text-[10px]">সদস্য</span>
        </a>
    </div>

    <script>
        // Modal Functions
        function openModal(id) { document.getElementById(id).classList.remove('hidden'); }
        function closeModal(id) { document.getElementById(id).classList.add('hidden'); }

        // Copy Username Function
        function copyUsername() {
            // Get the username text
            const username = document.getElementById('usernameText').innerText;
            
            // Copy to clipboard
            navigator.clipboard.writeText(username).then(function() {
                alert("ডাকনাম কপি হয়েছে!");
            }, function(err) {
                console.error('Copy failed', err);
            });
        }
    </script>

</body>
</html>