<?php
require_once __DIR__ . '/header.php';

$error = '';
$success = '';
$ref_code = isset($_GET['ref']) ? sanitize($_GET['ref']) : '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $name = sanitize($_POST['name']);
    $phone = sanitize($_POST['phone']);
    $email = sanitize($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    $business_name = sanitize($_POST['business_name']);
    $business_category = sanitize($_POST['business_category']);
    $full_address = sanitize($_POST['full_address']);
    $state = sanitize($_POST['state'] ?? '');
    $district = sanitize($_POST['district'] ?? '');
    $pincode = sanitize($_POST['pincode'] ?? '');
    $referral_code_input = isset($_POST['referral_code']) ? sanitize($_POST['referral_code']) : '';
    
    $referred_by = null;
    $ref_error = false;

    if (!empty($referral_code_input)) {
        if (strpos(strtoupper($referral_code_input), 'WBMCZ') === 0) {
            $ref_id = (int) str_replace('WBMCZ', '', strtoupper($referral_code_input));
            $check_ref = $db->select("SELECT id FROM users WHERE id = ?", [$ref_id]);
            if (!empty($check_ref)) {
                $referred_by = $ref_id;
            } else {
                $ref_error = true;
            }
        } else {
            $ref_error = true;
        }
    }
    
    // Validate
    if (empty($name) || empty($phone) || empty($email) || empty($password) || empty($business_name) || empty($full_address) || empty($state) || empty($district) || empty($pincode)) {
        $error = $lang->translate('fill_all_fields', 'সব ফিল্ড পূরণ করুন।');
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = $lang->translate('valid_email', 'বৈধ ইমেইল ঠিকানা দিন।');
    } elseif ($password !== $confirm_password) {
        $error = $lang->translate('password_mismatch', 'পাসওয়ার্ড মিলছে না!');
    } elseif ($ref_error) {
        $error = $lang->translate('invalid_referral', 'Invalid Referral Code.');
    } else {
        // Check if phone already exists
        $existing = $db->select("SELECT id FROM users WHERE mobile = ?", [$phone]);
        if (!empty($existing)) {
            $error = $lang->translate('phone_exists', 'এই ফোন নম্বরটি আগেই নিবন্ধিত হয়েছে।');
        } else {
            // Hash the password
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            // Insert into users
            $query_user = "INSERT INTO users (name, mobile, email, password, user_type, status, state, district, pincode, referred_by) VALUES (?, ?, ?, ?, 'seller', 0, ?, ?, ?, ?)";
            $user_id = $db->insert($query_user, [$name, $phone, $email, $hashed_password, $state, $district, $pincode, $referred_by]);
            
            if ($user_id) {
                // Insert into sellers
                $query_seller = "INSERT INTO sellers (user_id, name, phone, email, business_name, business_category, full_address, status) 
                                 VALUES (?, ?, ?, ?, ?, ?, ?, 0)";
                $seller_id = $db->insert($query_seller, [$user_id, $name, $phone, $email, $business_name, $business_category, $full_address]);
                
                if ($seller_id) {
                    
                    // Send Welcome Email
                    $subject = "Welcome to WBMCZ Seller Hub!";
                    $message = "
                    <html>
                    <body style='font-family: Arial, sans-serif; line-height: 1.6; color: #333;'>
                        <div style='max-w-md; margin: 0 auto; padding: 20px; border: 1px solid #ddd; border-radius: 10px;'>
                            <h2 style='color: #7e22ce;'>Welcome, $name!</h2>
                            <p>Thank you for registering your business (<b>$business_name</b>) as a seller on WBMCZ.</p>
                            <p>Your account is currently <strong>under review</strong> by our admin team. We will notify you once it is approved so you can start selling.</p>
                            <br>
                            <p>Best Regards,<br><strong>Team WBMCZ</strong></p>
                        </div>
                    </body>
                    </html>";
                    
                    $headers = "MIME-Version: 1.0\r\n";
                    $headers .= "Content-type:text/html;charset=UTF-8\r\n";
                    $headers .= "From: WBMCZ <no-reply@wbmcz.online>\r\n";
                    $headers .= "Reply-To: no-reply@wbmcz.online\r\n";
                    
                    @mail($email, $subject, $message, $headers);

                    $success = $lang->translate('seller_registration_success', 'আপনার সেলার রেজিস্ট্রেশন সফল হয়েছে! অ্যাডমিন অ্যাপ্রুভের পর আপনি লগইন করতে পারবেন।');
                } else {
                    $error = $lang->translate('registration_failed', 'রেজিস্ট্রেশন ব্যর্থ হয়েছে। আবার চেষ্টা করুন।');
                }
            } else {
                $error = $lang->translate('registration_failed', 'ইউজার রেজিস্ট্রেশন তৈরি করা যায়নি।');
            }
        }
    }
}
?>

<div class="min-h-screen bg-gray-50 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-2xl w-full space-y-8 bg-white rounded-2xl shadow-xl p-8">
        <div class="text-center">
            <img src="<?php echo $company_logo; ?>" alt="Logo" class="h-16 w-auto mx-auto mb-4">
            
            <h2 class="text-3xl font-extrabold text-gray-900"><?php echo $lang->translate('seller_registration', 'সেলার রেজিস্ট্রেশন'); ?></h2>
            <p class="mt-2 text-sm text-gray-600">
                <?php echo $lang->translate('seller_register_desc', 'বিক্রেতা হন এবং কমিশন আয় করুন'); ?>
            </p>
        </div>
        
        <?php if ($error): ?>
        <div class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert">
            <span class="block sm:inline"><?php echo $error; ?></span>
        </div>
        <?php endif; ?>
        
        <?php if ($success): ?>
        <div class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative" role="alert">
            <span class="block sm:inline"><?php echo $success; ?></span>
        </div>
        <?php endif; ?>
        
        <form class="mt-8 space-y-6" method="POST">
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('name', 'আপনার নাম'); ?></label>
                    <input id="name" name="name" type="text" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('enter_full_name', 'পুরো নাম লিখুন'); ?>">
                </div>
                
                <div>
                    <label for="phone" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('phone_number', 'ফোন নম্বর'); ?></label>
                    <input id="phone" name="phone" type="tel" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('enter_10_digit', '১০ সংখ্যার নম্বর দিন'); ?>">
                </div>
                
                <div>
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('email', 'ইমেইল'); ?></label>
                    <input id="email" name="email" type="email" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('enter_email', 'আপনার ইমেইল দিন'); ?>">
                </div>
                
                <div>
                    <label for="business_name" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('business_name', 'ব্যবসার নাম'); ?></label>
                    <input id="business_name" name="business_name" type="text" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('enter_business_name', 'আপনার ব্যবসার নাম লিখুন'); ?>">
                </div>

                <div>
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('password', 'পাসওয়ার্ড'); ?></label>
                    <input id="password" name="password" type="password" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('enter_password', 'পাসওয়ার্ড দিন'); ?>">
                </div>

                <div>
                    <label for="confirm_password" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('confirm_password', 'পাসওয়ার্ড কনফার্ম করুন'); ?></label>
                    <input id="confirm_password" name="confirm_password" type="password" required 
                           class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                           placeholder="<?php echo $lang->translate('confirm_password', 'পাসওয়ার্ড কনফার্ম করুন'); ?>">
                </div>
                
                <div class="md:col-span-2">
                    <label for="business_category" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('business_category', 'ব্যবসার ক্যাটাগরি'); ?></label>
                    <select id="business_category" name="business_category" 
                            class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent">
                        <option value=""><?php echo $lang->translate('select', 'নির্বাচন করুন'); ?></option>
                        <option value="retailer"><?php echo $lang->translate('retailer', 'রিটেইলার'); ?></option>
                        <option value="distributor"><?php echo $lang->translate('distributor', 'ডিস্ট্রিবিউটর'); ?></option>
                        <option value="franchise"><?php echo $lang->translate('franchise', 'ফ্র্যাঞ্চাইজি'); ?></option>
                        <option value="other"><?php echo $lang->translate('other', 'অন্যান্য'); ?></option>
                    </select>
                </div>
            </div>
            
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mt-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('state', 'রাজ্য'); ?></label>
                    <input name="state" type="text" required class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="রাজ্য লিখুন">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('district', 'জেলা'); ?></label>
                    <input name="district" type="text" required class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="জেলা লিখুন">
                </div>
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('pincode', 'পিন কোড'); ?></label>
                    <input name="pincode" type="text" required class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="পিন কোড">
                </div>
            </div>
            
            <div class="mt-4">
                <label for="full_address" class="block text-sm font-medium text-gray-700 mb-2"><?php echo $lang->translate('full_address', 'সম্পূর্ণ ঠিকানা'); ?></label>
                <textarea id="full_address" name="full_address" rows="3" required
                          class="appearance-none rounded-lg relative block w-full px-3 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent"
                          placeholder="<?php echo $lang->translate('enter_full_address', 'আপনার সম্পূর্ণ ঠিকানা লিখুন'); ?>"></textarea>
            </div>
            
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-1"><?php echo $lang->translate('referral_code', 'Referral Code (Optional)'); ?></label>
                <input name="referral_code" type="text" value="<?php echo htmlspecialchars($ref_code); ?>" class="appearance-none rounded-lg relative block w-full px-4 py-3 border border-gray-300 placeholder-gray-500 text-gray-900 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent" placeholder="e.g. WBMCZ0001">
            </div>
            
            <div>
                <button type="submit" 
                        class="group relative w-full flex justify-center py-3 px-4 border border-transparent text-sm font-medium rounded-lg text-white bg-purple-600 hover:bg-purple-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-purple-500">
                    <?php echo $lang->translate('register_seller', 'সেলার হিসেবে রেজিস্টার করুন'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

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