<?php
session_start();
require_once 'config/config.php';
require_once 'classes/Database.php';
require_once 'classes/Auth.php';
require_once 'classes/TelegramBot.php';
require_once 'classes/OTPManager.php';

if (!ALLOW_REGISTRATION) {
    header('Location: index.php');
    exit();
}

$db = Database::getInstance();
$auth = new Auth($db);

if ($auth->isLoggedIn()) {
    $auth->redirectBasedOnRole();
}

$message = '';
$message_type = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = trim($_POST['name'] ?? '');
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    
    if (empty($name) || empty($email) || empty($password)) {
        $message = 'Please fill in all fields';
        $message_type = 'danger';
    } elseif ($password !== $confirm_password) {
        $message = 'Passwords do not match';
        $message_type = 'danger';
    } elseif (strlen($password) < 6) {
        $message = 'Password must be at least 6 characters long';
        $message_type = 'danger';
    } else {
        if ($auth->register($name, $email, $password)) {
            // Get admin settings for registration mode
            $adminSettings = $db->fetch("SELECT registration_mode, otp_enabled FROM admin_settings LIMIT 1");
            
            $registrationMode = $adminSettings['registration_mode'] ?? 'otp';
            $otpEnabled = $adminSettings['otp_enabled'] ?? 1;
            
            // Check if OTP is required
            if ($otpEnabled && $registrationMode === 'otp') {
                // OTP-Based Registration Flow
                $otpManager = new OTPManager($db);
                
                // Generate and send OTP
                $result = $otpManager->generateAndSendOTP($email, $name);
                
                if ($result['success']) {
                    // Store email in session for OTP verification
                    $_SESSION['registration_email'] = $email;
                    
                    $message = '✅ Registration successful! OTP sent to ' . htmlspecialchars($email);
                    $message_type = 'success';
                    
                    // Send Telegram notification to admin
                    $newUser = $db->fetch(
                        'SELECT id, name, email, role FROM users WHERE email = ?',
                        [$email]
                    );
                    if ($newUser) {
                        $telegram = new TelegramBot(TELEGRAM_BOT_TOKEN, TELEGRAM_ADMIN_CHAT_ID);
                        $telegram->notifyNewRegistration($newUser);
                    }
                    
                    // Redirect to email verification page
                    header('Location: verify_email.php');
                    exit();
                } else {
                    $message = 'Registration successful but failed to send OTP. ' . $result['message'];
                    $message_type = 'warning';
                }
            } else {
                // Direct Registration Flow (No OTP Required)
                // Activate user immediately
                $db->query(
                    "UPDATE users SET is_active = 1, email_verified = 1, email_verified_at = NOW() WHERE email = ?",
                    [$email]
                );
                
                $newUser = $db->fetch(
                    'SELECT id, name, email, role FROM users WHERE email = ?',
                    [$email]
                );
                
                if ($newUser) {
                    // Send Telegram notification to admin
                    $telegram = new TelegramBot(TELEGRAM_BOT_TOKEN, TELEGRAM_ADMIN_CHAT_ID);
                    $telegram->notifyNewRegistration($newUser);
                }
                
                $message = '✅ Registration successful! You can now login.';
                $message_type = 'success';
            }
        } else {
            $message = 'Registration failed. Email may already be registered.';
            $message_type = 'danger';
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register - <?php echo APP_NAME; ?></title>
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <!-- Feather Icons -->
    <script src="https://unpkg.com/feather-icons"></script>
    
    <style>
        :root {
            --primary-color: #007AFF;
            --secondary-color: #F2F2F7;
            --text-color: #1C1C1E;
            --light-gray: #F5F6F8;
            --border-color: #E5E5EA;
            --shadow-color: rgba(0, 0, 0, 0.1);
        }
        
        * {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
        }
        
        .register-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 24px;
            padding: 2.5rem;
            box-shadow: 0 20px 40px var(--shadow-color);
            border: 1px solid rgba(255, 255, 255, 0.2);
            max-width: 420px;
            width: 100%;
        }
        
        .register-header {
            text-align: center;
            margin-bottom: 2rem;
        }
        
        .register-title {
            font-size: 2rem;
            font-weight: 700;
            background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 0.5rem;
        }
        
        .register-subtitle {
            color: #6C757D;
            font-size: 0.95rem;
        }
        
        .form-floating {
            margin-bottom: 1.5rem;
        }
        
        .form-control {
            border-radius: 12px;
            border: 2px solid var(--border-color);
            padding: 1rem;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: rgba(255, 255, 255, 0.8);
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(0, 122, 255, 0.25);
            background: white;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #007AFF 0%, #0056CC 100%);
            border: none;
            border-radius: 25px;
            padding: 12px 30px;
            font-weight: 600;
            font-size: 1rem;
            transition: all 0.3s ease;
            box-shadow: 0 4px 15px rgba(0, 122, 255, 0.3);
            width: 100%;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0, 122, 255, 0.4);
            background: linear-gradient(135deg, #0056CC 0%, #004499 100%);
        }
        
        .alert {
            border-radius: 12px;
            border: none;
            margin-bottom: 1.5rem;
        }
        
        .register-footer {
            text-align: center;
            margin-top: 2rem;
            padding-top: 1.5rem;
            border-top: 1px solid var(--border-color);
        }
        
        .register-footer a {
            color: var(--primary-color);
            text-decoration: none;
            font-weight: 500;
        }
        
        .register-footer a:hover {
            text-decoration: underline;
        }
        
        .password-toggle {
            position: absolute;
            right: 15px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #6C757D;
        }
        
        .floating-shapes {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: -1;
        }
        
        .shape {
            position: absolute;
            background: rgba(0, 122, 255, 0.1);
            border-radius: 50%;
            animation: float 6s ease-in-out infinite;
        }
        
        .shape:nth-child(1) {
            width: 80px;
            height: 80px;
            top: 20%;
            left: 10%;
            animation-delay: 0s;
        }
        
        .shape:nth-child(2) {
            width: 120px;
            height: 120px;
            top: 60%;
            right: 10%;
            animation-delay: 2s;
        }
        
        .shape:nth-child(3) {
            width: 60px;
            height: 60px;
            bottom: 20%;
            left: 20%;
            animation-delay: 4s;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-20px); }
        }
    </style>
</head>
<body>
    <div class="floating-shapes">
        <div class="shape"></div>
        <div class="shape"></div>
        <div class="shape"></div>
    </div>
    
    <div class="register-container">
        <div class="register-header">
            <h1 class="register-title">Create Account</h1>
            <p class="register-subtitle">Join <?php echo APP_NAME; ?></p>
        </div>
        
        <?php if ($message): ?>
        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
            <?php echo htmlspecialchars($message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        <?php endif; ?>
        
        <form method="POST" action="register.php">
            <div class="form-floating">
                <input type="text" class="form-control" id="name" name="name" placeholder="Full Name" required>
                <label for="name">Full Name</label>
            </div>
            
            <div class="form-floating">
                <input type="email" class="form-control" id="email" name="email" placeholder="name@example.com" required>
                <label for="email">Email address</label>
            </div>
            
            <div class="form-floating position-relative">
                <input type="password" class="form-control" id="password" name="password" placeholder="Password" required>
                <label for="password">Password</label>
                <span class="password-toggle" onclick="togglePassword('password')">
                    <i data-feather="eye" id="eye-icon-password"></i>
                </span>
            </div>
            
            <div class="form-floating position-relative">
                <input type="password" class="form-control" id="confirm_password" name="confirm_password" placeholder="Confirm Password" required>
                <label for="confirm_password">Confirm Password</label>
                <span class="password-toggle" onclick="togglePassword('confirm_password')">
                    <i data-feather="eye" id="eye-icon-confirm_password"></i>
                </span>
            </div>
            
            <div class="form-check mb-3">
                <input class="form-check-input" type="checkbox" id="terms" name="terms" required>
                <label class="form-check-label" for="terms">
                    I agree to the <a href="terms.php">Terms and Conditions</a>
                </label>
            </div>
            
            <button type="submit" class="btn btn-primary">
                <i data-feather="user-plus" class="me-2"></i>
                Create Account
            </button>
        </form>
        
        <div class="register-footer">
            <p class="mb-0">Already have an account? <a href="login.php">Sign in</a></p>
        </div>
    </div>

    <!-- Bootstrap JS -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- Feather Icons -->
    <script>
        feather.replace();
        
        function togglePassword(fieldId) {
            const passwordInput = document.getElementById(fieldId);
            const eyeIcon = document.getElementById('eye-icon-' + fieldId);
            
            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                eyeIcon.setAttribute('data-feather', 'eye-off');
            } else {
                passwordInput.type = 'password';
                eyeIcon.setAttribute('data-feather', 'eye');
            }
            feather.replace();
        }
    </script>
</body>
</html>