<?php
session_start();
// ডাটাবেস কানেকশন
require '../includes/db.php'; 

// সেটিংস
$site_name = "Bet365"; 
$error = "";

// URL থেকে রেফারেল কোড ধরা (যদি থাকে)
$ref_code_input = isset($_GET['ref']) ? htmlspecialchars($_GET['ref']) : '';

// --- FIX: প্রতিবার পেজ লোড বা রিফ্রেশে নতুন কোড জেনারেট হবে ---
$random_code = rand(1000, 9999);

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // ইনপুট স্যানিটাইজেশন
    $username = mysqli_real_escape_string($conn, trim($_POST['username']));
    $mobile = mysqli_real_escape_string($conn, trim($_POST['mobile']));
    $email = mysqli_real_escape_string($conn, trim($_POST['email'])); // ইমেইল এখন খালিও হতে পারে
    $pass = $_POST['password'];
    $ref_code = mysqli_real_escape_string($conn, trim($_POST['ref_code'])); 
    
    // ভেরিফিকেশন কোড চেক
    $user_code = $_POST['user_code'];
    $real_code = $_POST['real_code']; 

    // ১. ভ্যালিডেশন
    if ($user_code !== $real_code) {
        $error = "যাচাইকরণ কোড ভুল হয়েছে! আবার চেষ্টা করুন।";
    } elseif (preg_match('/[^a-zA-Z0-9]/', $username)) {
        $error = "ইউজারনেমে কোনো স্পেশাল ক্যারেক্টার ব্যবহার করা যাবে না।";
    } elseif (!is_numeric($mobile)) {
        $error = "মোবাইল নম্বর শুধুমাত্র সংখ্যা হতে হবে।";
    } elseif (strlen($mobile) != 11) {
        $error = "মোবাইল নম্বর অবশ্যই ১১ সংখ্যার হতে হবে।";
    
    // [MODIFIED] ইমেইল ভ্যালিডেশন শুধুমাত্র তখনই হবে যদি ইউজার ইমেইল দেয়
    } elseif (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL)) { 
        $error = "অনুগ্রহ করে একটি সঠিক ইমেইল ঠিকানা দিন।";
        
    } elseif (strlen($pass) < 6) {
        $error = "পাসওয়ার্ড কমপক্ষে ৬ অক্ষরের হতে হবে।";
    } else {
        // ২. ডুপ্লিকেট চেক (স্মার্ট লজিক)
        // ইমেইল খালি থাকলে শুধু ইউজারনেম আর মোবাইল চেক করবে
        $check_sql = "SELECT id FROM users WHERE phone='$mobile' OR username='$username'";
        if (!empty($email)) {
            $check_sql .= " OR email='$email'";
        }
        
        $check = $conn->query($check_sql);
        
        if ($check && $check->num_rows > 0) {
            $error = "এই ইউজারনেম, মোবাইল নম্বর" . (!empty($email) ? " বা ইমেইলটি" : "") . " ইতিমধ্যে নিবন্ধিত।";
        } else {
            
            // ৩. রেফারেল লজিক
            $agent_id = 0;      
            $referrer_id = 0;   

            if (!empty($ref_code)) {
                $agent_check = $conn->query("SELECT id FROM agents WHERE referral_code = '$ref_code' LIMIT 1");
                
                if ($agent_check && $agent_check->num_rows > 0) {
                    $agent_data = $agent_check->fetch_assoc();
                    $agent_id = $agent_data['id']; 
                } else {
                    $player_check = $conn->query("SELECT id FROM users WHERE ref_code = '$ref_code' LIMIT 1");
                    
                    if ($player_check && $player_check->num_rows > 0) {
                        $player_data = $player_check->fetch_assoc();
                        $referrer_id = $player_data['id']; 
                    }
                }
            }

            // ৪. ইউজার তৈরি
            $hashed_pass = password_hash($pass, PASSWORD_DEFAULT);
            $my_new_ref_code = 'REF' . rand(10000, 99999) . time(); 
            
            // --- FIX START: ইমেইল হ্যান্ডলিং ---
            // যদি ইমেইল খালি থাকে, তাহলে আমরা একটি ডামি ভ্যালু বা ফাঁকা স্ট্রিং পাঠাবো ডাটাবেসের কনস্ট্রেইন্ট অনুযায়ী।
            // যেহেতু আপনার টেবিল স্ট্রাকচারে ইমেইল 'NO NULL' দেখাচ্ছে, তাই খালি স্ট্রিং পাঠানো নিরাপদ।
            $final_email = !empty($email) ? $email : ""; 
            // --- FIX END ---

            $sql = "INSERT INTO users (username, phone, email, password, role, status, created_at, balance, agent_id, referrer_id, ref_code) 
                    VALUES ('$username', '$mobile', '$final_email', '$hashed_pass', 'player', 'active', NOW(), 0.00, '$agent_id', '$referrer_id', '$my_new_ref_code')";
            
            if ($conn->query($sql)) {
                $new_uid = $conn->insert_id;
                
                // প্রোফাইল তৈরি
                $conn->query("INSERT INTO player_profiles (user_id) VALUES ($new_uid)");
                
                // অটো লগইন
                $_SESSION['user_id'] = $new_uid;
                $_SESSION['username'] = $username;
                $_SESSION['role'] = 'player';
                
                header("Location: dashboard.php");
                exit();
            } else {
                $error = "নিবন্ধন ব্যর্থ হয়েছে। অনুগ্রহ করে আবার চেষ্টা করুন। (Error: " . $conn->error . ")";
            }
        }
    }
}
?>
<!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>Sign up - Bet365 Style</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: #273832; 
            color: #d1d5db;
            font-family: 'Roboto', sans-serif;
            min-height: 100vh;
            display: flex; flex-direction: column;
        }

        .header-bg { 
            background-color: #137a5a; 
            padding: 15px; 
            text-align: center; 
            border-bottom: 1px solid #0e5e45; 
            position: relative; 
        }
        .close-btn { 
            position: absolute; right: 15px; top: 15px; font-size: 20px; 
            color: #a7f3d0; 
            transition: color 0.3s;
        }
        .close-btn:hover { color: white; }

        .logo-text {
            font-family: 'Arial', sans-serif;
            font-weight: 900;
            font-style: italic;
            letter-spacing: -1px;
            font-size: 30px;
        }
        .brand-yellow { color: #ffdf1b; }
        
        .form-label { 
            display: block; 
            color: #d1d5db; 
            font-size: 12px; 
            font-weight: bold;
            margin-bottom: 6px; 
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }

        .custom-input {
            width: 100%;
            background-color: #3b4c46; 
            border: 1px solid #137a5a; 
            border-radius: 4px;
            padding: 12px 15px;
            color: white;
            font-size: 14px;
            outline: none;
            transition: border 0.3s;
        }
        .custom-input:focus { border-color: #ffdf1b; background-color: #3b4c46; }
        .custom-input::placeholder { color: #8fa199; }

        .eye-icon {
            position: absolute; right: 15px; top: 12px;
            color: #8fa199; cursor: pointer;
            transition: color 0.3s;
        }
        .eye-icon:hover { color: white; }

        .verify-box {
            background-color: #ffdf1b; 
            color: #123628; 
            font-weight: bold;
            font-size: 18px;
            letter-spacing: 4px;
            padding: 10px 15px;
            border-radius: 4px;
            text-align: center;
            width: 100px;
            user-select: none;
        }
        .refresh-btn { 
            color: #ffdf1b; 
            font-size: 18px; 
            cursor: pointer; 
            margin-left: 10px; 
            transition: transform 0.3s; 
        }
        .refresh-btn:active { transform: rotate(180deg); }

        .req-list { list-style: none; padding: 0; margin-top: 8px; margin-bottom: 15px; }
        .req-item { font-size: 11px; color: #8fa199; margin-bottom: 4px; display: flex; align-items: center; gap: 5px; }
        .req-item i { font-size: 12px; }
        .req-item.valid { color: #10b981; }

        .btn-bet365 {
            background-color: #ffdf1b !important;
            color: #123628 !important; 
            width: 100%; padding: 12px;
            border-radius: 4px;
            font-weight: bold; font-size: 16px;
            margin-top: 10px;
            border: none;
            transition: 0.2s;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
        }
        .btn-bet365:hover { 
            background-color: #eacb15 !important; 
            transform: translateY(-1px);
        }

        .phone-group { 
            display: flex; 
            align-items: center; 
            background-color: #3b4c46; 
            border: 1px solid #137a5a; 
            border-radius: 4px; 
            overflow: hidden; 
        }
        .phone-group:focus-within { border-color: #ffdf1b; }
        
        .bd-flag { 
            padding: 0 15px; 
            border-right: 1px solid #137a5a; 
            display: flex; 
            align-items: center; 
            gap: 5px; 
            color: #d1d5db; 
            font-size: 13px; 
        }
        .phone-input { 
            border: none; 
            flex: 1; 
            padding: 12px 15px; 
            background: transparent; 
            color: white; 
            outline: none; 
        }
        .flag-circle { width: 15px; height: 15px; background: #006a4e; border-radius: 50%; position: relative; }
        .flag-circle::after { content: ''; width: 6px; height: 6px; background: #f42a41; border-radius: 50%; position: absolute; top: 4.5px; left: 4.5px; }
        
        .brand-link { color: #ffdf1b; transition: color 0.2s; font-weight: bold; }
        .brand-link:hover { color: white; }
    </style>
</head>
<body>

    <div class="header-bg">
        <h1 class="text-white font-bold text-lg italic">Join Now</h1>
        <a href="login.php" class="close-btn"><i class="fas fa-times"></i></a>
    </div>

    <div class="px-5 py-6">
        
        <div class="text-center mb-6">
            <span class="text-white logo-text">BET</span><span class="brand-yellow logo-text">365</span>
            <div class="text-gray-400 text-[10px] font-bold uppercase tracking-wider mt-1">Sports & Casino</div>
        </div>

        <?php if($error): ?>
            <div class="bg-red-900/80 border border-red-600 text-white px-4 py-2 rounded mb-4 text-xs text-center shadow">
                <i class="fas fa-exclamation-circle mr-1"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <form method="POST">
            
            <div class="mb-4">
                <label class="form-label">Username</label>
                <input type="text" name="username" id="usernameInput" required placeholder="4-16 chars" class="custom-input" value="<?php echo isset($_POST['username']) ? $_POST['username'] : ''; ?>">
            </div>

            <div class="mb-1">
                <label class="form-label">Password</label>
                <div class="relative">
                    <input type="password" name="password" id="password" required placeholder="6-20 characters" class="custom-input">
                    <i class="fas fa-eye-slash eye-icon" onclick="togglePass()"></i>
                </div>
            </div>

            <ul class="req-list">
                <li class="req-item" id="req-len"><i class="fas fa-check-circle"></i> Between 6~20 characters.</li>
                <li class="req-item" id="req-alpha"><i class="fas fa-check-circle"></i> At least one alphabet.</li>
                <li class="req-item" id="req-num"><i class="fas fa-check-circle"></i> At least one number.</li>
            </ul>

            <div class="mb-4">
                <label class="form-label">Phone Number</label>
                <div class="phone-group">
                    <div class="bd-flag">
                        <div class="flag-circle"></div> +880
                    </div>
                    <input type="tel" name="mobile" id="mobileInput" required placeholder="17XXXXXXXX" class="phone-input" maxlength="11" value="<?php echo isset($_POST['mobile']) ? $_POST['mobile'] : ''; ?>">
                </div>
            </div>

            <div class="mb-4">
                <label class="form-label">Email Address (Optional)</label>
                <input type="email" name="email" placeholder="example@email.com" class="custom-input" value="<?php echo isset($_POST['email']) ? $_POST['email'] : ''; ?>">
            </div>

            <div class="mb-4">
                <label class="form-label">Referral Code (Optional)</label>
                <input type="text" name="ref_code" placeholder="Enter Agent or Promo Code" class="custom-input" value="<?php echo $ref_code_input; ?>">
            </div>

            <div class="mb-6">
                <label class="form-label">Verification Code</label>
                <div class="flex items-center gap-2">
                    <input type="text" name="user_code" required placeholder="Enter code" class="custom-input" maxlength="4">
                    
                    <div class="verify-box"><?php echo $random_code; ?></div>
                    
                    <input type="hidden" name="real_code" value="<?php echo $random_code; ?>">
                    
                    <i class="fas fa-sync-alt refresh-btn" onclick="window.location.reload()"></i>
                </div>
            </div>

            <button type="submit" class="btn-bet365">Join BET365</button>

            <div class="text-center mt-4 text-xs text-gray-400">
                Already a member? <a href="login.php" class="brand-link hover:underline">Log In</a>
            </div>

            <div class="text-center mt-6 text-[10px] text-gray-500 leading-tight px-4 border-t border-gray-600 pt-4">
                By joining, I certify that I am at least 18 years old and agree to the <a href="#" class="brand-link">Terms & Conditions</a>.
            </div>

        </form>
    </div>

    <script>
        // 1. Mobile Number Validation
        const mobileInput = document.getElementById('mobileInput');
        mobileInput.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^0-9]/g, '');
            if (this.value.length > 11) this.value = this.value.slice(0, 11);
        });

        // 2. Username Validation
        const usernameInput = document.getElementById('usernameInput');
        usernameInput.addEventListener('input', function(e) {
            this.value = this.value.replace(/[^a-zA-Z0-9]/g, '');
        });

        // 3. Password Validation Highlight
        const passInput = document.getElementById('password');
        passInput.addEventListener('input', function(e) {
            const val = this.value;
            // Length
            document.getElementById('req-len').classList.toggle('valid', val.length >= 6 && val.length <= 20);
            // Alphabet
            document.getElementById('req-alpha').classList.toggle('valid', /[a-zA-Z]/.test(val));
            // Number
            document.getElementById('req-num').classList.toggle('valid', /\d/.test(val));
        });

        // Toggle Password
        function togglePass() {
            const input = document.getElementById('password');
            const icon = document.querySelector('.eye-icon');
            
            if(input.type === 'password') {
                input.type = 'text';
                icon.classList.remove('fa-eye-slash');
                icon.classList.add('fa-eye');
                icon.style.color = '#ffdf1b'; // Yellow when visible
            } else {
                input.type = 'password';
                icon.classList.remove('fa-eye');
                icon.classList.add('fa-eye-slash');
                icon.style.color = '#8fa199'; // Grey when hidden
            }
        }
    </script>

</body>
</html>