<?php
require_once __DIR__ . '/../includes/lang.php';
require_once __DIR__ . '/../db/config.php';

$error = '';
// getSetting is defined in db/config.php
$email_verify_enabled = getSetting('email_verification_enabled', '0') === '1';
$mobile_verify_enabled = getSetting('mobile_verification_enabled', '0') === '1';
$universal_code = getSetting('universal_verification_code', '');

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $reg_type = $_POST['reg_type'] ?? 'username'; // 'email' or 'username'
    $account = $_POST['account'] ?? '';
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $verify_code = $_POST['verify_code'] ?? '';
    $agree_all = isset($_POST['agree_all']);
    
    $is_verify_enabled = ($reg_type === 'email' ? $email_verify_enabled : $mobile_verify_enabled);
    
    if (empty($account) || empty($password)) {
        $error = __('fill_full_info');
    } elseif ($password !== $confirm_password) {
        $error = __('pwd_mismatch');
    } elseif ($is_verify_enabled && empty($verify_code)) {
        $error = __('enter_verify_code');
    } elseif (!$agree_all) {
        $error = __('agree_terms_error');
    } else {
        if ($is_verify_enabled) {
            $is_universal = (!empty($universal_code) && $verify_code === $universal_code);
            
            if (!$is_universal && $verify_code !== '123456') {
                // Check session for actual code
                $session_key = ($reg_type === 'email' ? 'email_code' : 'mobile_code');
                if (!isset($_SESSION[$session_key]) || $verify_code !== $_SESSION[$session_key]) {
                    $error = __('verify_code_error');
                }
            }
        }
        
        if (!$error) {
            try {
                $hash = password_hash($password, PASSWORD_DEFAULT);
                $uid = str_pad(mt_rand(0, 99999999), 8, '0', STR_PAD_LEFT);
                
                $username = $account;
                $email = '';
                
                if ($reg_type === 'email') {
                    $email = $account;
                    $username = $account;
                } else {
                    $email = $username . '@user.byro'; // Fallback
                }
                
                $ip = getRealIP();
                $stmt = db()->prepare("INSERT INTO users (username, email, password_hash, uid, credit_score, total_recharge, role, registration_ip) VALUES (?, ?, ?, ?, ?, 0, 'user', ?)");
                $stmt->execute([$username, $email, $hash, $uid, 80, $ip]);
                $userId = db()->lastInsertId();
                
    if (session_status() === PHP_SESSION_NONE) @session_start();
                $_SESSION['user_id'] = $userId;
                $_SESSION['username'] = $username;
                $_SESSION['uid'] = $uid;
                $_SESSION['role'] = 'user';
                
                // Initialize balance
                $stmt = db()->prepare("INSERT INTO user_balances (user_id, symbol, available) VALUES (?, 'USDT', 0)");
                $stmt->execute([$userId]);
                
                header('Location: /');
                exit;
            } catch (PDOException $e) {
                $error = __('account_exists');
            }
        }
    }
}

// Add API for sending verification code
if (isset($_GET['action']) && $_GET['action'] === 'send_code') {
    ob_start();
    error_reporting(0);
    ini_set('display_errors', 0);
    header('Content-Type: application/json');
    $account = $_GET['account'] ?? '';
    $type = $_GET['type'] ?? 'email';
    
    if ($type === 'email') {
        if (!filter_var($account, FILTER_VALIDATE_EMAIL)) {
            ob_clean();
            echo json_encode(['success' => false, 'error' => __('invalid_email')]);
            exit;
        }
    }
    
    $code = str_pad(mt_rand(0, 999999), 6, '0', STR_PAD_LEFT);
    if (session_status() === PHP_SESSION_NONE) session_start();
    
    if ($type === 'email') {
        $_SESSION['email_code'] = $code;
        require_once __DIR__ . '/../mail/MailService.php';
        $res = MailService::sendVerificationCode($account, $code, 'register');
        
        if (!$res['success']) {
            ob_clean();
            echo json_encode(['success' => false, 'error' => $res['error'] ?? __('send_failed')]);
            exit;
        }
    } else {
        $_SESSION['mobile_code'] = $code;
        // Logic for SMS would go here using getSetting('mobile_api_config')
        // For now, we just store it in session.
    }
    
    ob_clean();
    echo json_encode(['success' => true]);
    exit;
}

include __DIR__ . '/../includes/header.php';
?>

<style>
    body {
        background: radial-gradient(circle at top right, #1a1f26, #0b0e11);
        min-height: 100vh;
    }
    .auth-card {
        background: #1e2329 !important;
        border: 1px solid rgba(255, 255, 255, 0.05) !important;
        border-radius: 24px !important;
        box-shadow: 0 40px 100px rgba(0,0,0,0.6) !important;
    }
    .form-control {
        background: #0b0e11 !important;
        border: 1px solid #2b3139 !important;
        color: #fff !important;
        font-size: 15px !important;
        transition: all 0.3s ease;
    }
    .form-control:focus {
        border-color: var(--primary) !important;
        box-shadow: 0 0 0 4px rgba(0, 98, 255, 0.1) !important;
        background: #0b0e11 !important;
        border-radius: 12px;
    }
    .form-label {
        font-size: 14px !important;
        color: #e5e7eb !important;
        margin-bottom: 8px !important;
        font-weight: 600 !important;
    }
    .text-muted {
        color: #9ba3af !important;
    }
    .text-white {
        color: #ffffff !important;
    }
    .nav-pills .nav-link {
        color: #9ba3af;
        font-weight: 600;
        font-size: 14px;
        transition: all 0.3s;
    }
    .nav-pills .nav-link.active {
        background: var(--primary) !important;
        color: #fff !important;
        box-shadow: 0 4px 12px rgba(0, 98, 255, 0.3);
    }
    .btn-primary {
        height: 55px;
        font-size: 16px;
        font-weight: 700;
        letter-spacing: 0.5px;
    }
    .logo-text {
        background: linear-gradient(135deg, #fff 0%, #9ba3af 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        font-weight: 900 !important;
    }
</style>

<div class="container py-5">
    <div class="row justify-content-center align-items-center" style="min-height: 80vh;">
        <div class="col-md-5">
            <div class="card auth-card p-4 p-md-5">
                <div class="text-center mb-5">
                    <div class="logo-container d-inline-flex mb-4 align-items-center">
                        <img src="<?= $site_logo ?>?v=<?= $logo_v ?? time() ?>" height="40" alt="<?= $site_name ?>">
                        <span class="logo-text ms-3" style="font-size: 24px; font-weight: 900; color: #fff; letter-spacing: 1px; text-transform: uppercase;"><?= $site_name ?></span>
                    </div>
                    <h2 class="fw-bold text-white mb-2" style="font-size: 28px;"><?= __('register') ?></h2>
                    <p class="text-muted" style="font-size: 15px;"><?= __('join_secure') ?></p>
                </div>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger py-3 px-4 small border-0 bg-danger bg-opacity-10 text-danger rounded-4 mb-4">
                        <i class="bi bi-exclamation-triangle-fill me-2"></i><?= $error ?>
                    </div>
                <?php endif; ?>

                <ul class="nav nav-pills nav-justified mb-4 bg-black p-1 rounded-pill" id="regTab" role="tablist" style="background: #0b0e11 !important;">
                    <?php if ($mobile_verify_enabled): ?>
                    <li class="nav-item">
                        <button class="nav-link active rounded-pill py-2" id="username-tab" data-bs-toggle="pill" data-bs-target="#username-reg" type="button" onclick="setRegType('username')"><?= __('mobile_reg') ?></button>
                    </li>
                    <?php endif; ?>
                    <li class="nav-item">
                        <button class="nav-link <?= !$mobile_verify_enabled ? 'active' : '' ?> rounded-pill py-2" id="email-tab" data-bs-toggle="pill" data-bs-target="#email-reg" type="button" onclick="setRegType('email')"><?= __('email_reg') ?></button>
                    </li>
                </ul>

                <form method="POST" id="registerForm">
                    <input type="hidden" name="reg_type" id="reg_type" value="<?= $mobile_verify_enabled ? 'username' : 'email' ?>">
                    
                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold" id="account-label"><?= $mobile_verify_enabled ? __('mobile_number') : __('email') ?></label>
                        <input type="<?= $mobile_verify_enabled ? 'text' : 'email' ?>" name="account" id="account-input" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-4" style="background: #0b0e11 !important; border-color: #2b3139 !important;" placeholder="<?= $mobile_verify_enabled ? __('mobile_number') : __('email_placeholder') ?>" required>
                    </div>

                    <div id="verify-box" style="display: <?= ($mobile_verify_enabled || $email_verify_enabled) ? 'block' : 'none' ?>;">
                        <div class="mb-3" id="verify-field-box">
                            <label class="form-label text-muted small fw-bold" id="verify-label"><?= $mobile_verify_enabled ? __('mobile_verify') : __('email_verify') ?></label>
                            <div class="input-group">
                                <input type="text" name="verify_code" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-start-4" style="background: #0b0e11 !important; border-color: #2b3139 !important;">
                                <button class="btn btn-outline-primary px-3 rounded-end-4" type="button" id="sendBtn" onclick="sendCode()"><?= __('send_code') ?></button>
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <label class="form-label text-muted small fw-bold"><?= __('password') ?></label>
                        <input type="password" name="password" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-4" style="background: #0b0e11 !important; border-color: #2b3139 !important;" required>
                    </div>

                    <div class="mb-4">
                        <label class="form-label text-muted small fw-bold"><?= __('confirm_password') ?></label>
                        <input type="password" name="confirm_password" class="form-control bg-black border-secondary text-white py-3 px-4 rounded-4" style="background: #0b0e11 !important; border-color: #2b3139 !important;" required>
                    </div>

                    <div class="mb-4 form-check small">
                        <input type="checkbox" name="agree_all" class="form-check-input bg-black border-secondary" id="agreeCheck" required>
                        <label class="form-check-label text-white fw-medium" for="agreeCheck">
                            <?= __('agree_tos_privacy') ?>
                        </label>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 py-3 fw-bold rounded-pill mb-4 shadow-primary"><?= __('register_now') ?></button>
                    
                    <div class="text-center small text-muted">
                        <?= __('have_account') ?> <a href="/auth/login.php" class="text-primary fw-bold text-decoration-none"><?= __('login') ?></a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
function setRegType(type) {
    document.getElementById('reg_type').value = type;
    const label = document.getElementById('account-label');
    const input = document.getElementById('account-input');
    const verifyLabel = document.getElementById('verify-label');
    const verifyBox = document.getElementById('verify-box');
    
    const emailVerifyEnabled = <?= $email_verify_enabled ? 'true' : 'false' ?>;
    const mobileVerifyEnabled = <?= $mobile_verify_enabled ? 'true' : 'false' ?>;
    
    if (type === 'email') {
        label.innerText = '<?= __('email') ?>';
        input.placeholder = '<?= __('email_placeholder') ?>';
        input.type = 'email';
        if (verifyLabel) verifyLabel.innerText = '<?= __('email_verify') ?>';
        verifyBox.style.display = emailVerifyEnabled ? 'block' : 'none';
    } else {
        label.innerText = '<?= __('mobile_number') ?>';
        input.placeholder = '<?= __('mobile_number') ?>';
        input.type = 'text';
        if (verifyLabel) verifyLabel.innerText = '<?= __('mobile_verify') ?>';
        verifyBox.style.display = mobileVerifyEnabled ? 'block' : 'none';
    }
}

function sendCode() {
    const account = document.getElementById('account-input').value;
    const type = document.getElementById('reg_type').value;
    
    if (type === 'email') {
        if (!account || !account.includes('@')) {
            alert('<?= __('invalid_email') ?>');
            return;
        }
    } else {
        if (!account || account.length < 5) {
            alert('<?= __('invalid_mobile') ?>');
            return;
        }
    }
    
    const btn = document.getElementById('sendBtn');
    const oldText = btn.innerText;
    btn.disabled = true;
    
    fetch('?action=send_code&account=' + encodeURIComponent(account) + '&type=' + type)
        .then(res => {
            if (!res.ok) throw new Error('Network error: ' + res.status);
            return res.text().then(text => {
                try {
                    const jsonStart = text.indexOf('{');
                    const jsonEnd = text.lastIndexOf('}');
                    if (jsonStart !== -1 && jsonEnd !== -1) {
                        return JSON.parse(text.substring(jsonStart, jsonEnd + 1));
                    }
                    return JSON.parse(text);
                } catch(e) {
                    throw new Error('Invalid server response.');
                }
            });
        })
        .then(data => {
            if (data.success) {
                let seconds = 60;
                btn.innerText = seconds + 's';
                const timer = setInterval(() => {
                    seconds--;
                    btn.innerText = seconds + 's';
                    if (seconds <= 0) {
                        clearInterval(timer);
                        btn.innerText = '<?= __('resend') ?>';
                        btn.disabled = false;
                    }
                }, 1000);
            } else {
                alert(data.error || '<?= __('send_failed') ?>');
                btn.disabled = false;
                btn.innerText = oldText;
            }
        })
        .catch(err => {
            alert('Error: ' + err.message);
            btn.disabled = false;
            btn.innerText = oldText;
        });
}
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>