<?php
/**
 * Registration Page
 * OBGYN Research & Collaboration Platform
 */

require_once 'config/config.php';

$isMobile = preg_match('/Mobile|Android|iPhone|iPad|iPod/', $_SERVER['HTTP_USER_AGENT']);

// Redirect if already logged in
if (isLoggedIn()) {
    redirect(SITE_URL . '/researcher/dashboard.php');
}

$pageTitle = 'Register';
$error = '';
$success = '';

// Handle registration form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $firstName = sanitize($_POST['first_name'] ?? '');
    $lastName = sanitize($_POST['last_name'] ?? '');
    $email = sanitize($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirmPassword = $_POST['confirm_password'] ?? '';
    $agreeTerms = isset($_POST['agree_terms']);
    
    // Validation
    if (empty($firstName) || empty($lastName) || empty($email) || empty($password)) {
        $error = 'All fields are required.';
    } elseif (!isValidEmail($email)) {
        $error = 'Please enter a valid email address.';
    } elseif ($password !== $confirmPassword) {
        $error = 'Passwords do not match.';
    } elseif (!$agreeTerms) {
        $error = 'You must agree to the Terms of Service and Privacy Policy.';
    } else {
        // Validate password strength
        $passwordValidation = validatePasswordStrength($password);
        if (!$passwordValidation['valid']) {
            $error = implode(' ', $passwordValidation['errors']);
        } else {
            // Register user
            $result = registerUser($email, $password, $firstName, $lastName, ROLE_RESEARCHER);
            
            if ($result['success']) {
                $success = $result['message'];
                // Clear form
                $_POST = [];
            } else {
                $error = $result['message'];
            }
        }
    }
}

// Include appropriate header based on device
if ($isMobile) {
    include 'templates/mobile-header.php';
} else {
    include 'templates/header.php';
}
?>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8 col-lg-6">
            <div class="card shadow-lg my-5">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <i class="fas fa-user-plus fa-3x text-primary mb-3"></i>
                        <h2 class="fw-bold">Create Account</h2>
                        <p class="text-muted">Join our research community</p>
                    </div>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($success): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="fas fa-check-circle"></i> <?php echo e($success); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                        <div class="text-center mt-3">
                            <a href="<?php echo SITE_URL; ?>/login.php" class="btn btn-primary">
                                <i class="fas fa-sign-in-alt"></i> Go to Login
                            </a>
                        </div>
                    <?php else: ?>
                        <form method="POST" action="" class="needs-validation" novalidate>
                            <?php echo csrfField(); ?>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="first_name" class="form-label">First Name *</label>
                                    <input type="text" class="form-control" id="first_name" name="first_name" 
                                           value="<?php echo e($_POST['first_name'] ?? ''); ?>" 
                                           placeholder="John" required>
                                    <div class="invalid-feedback">
                                        Please enter your first name.
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="last_name" class="form-label">Last Name *</label>
                                    <input type="text" class="form-control" id="last_name" name="last_name" 
                                           value="<?php echo e($_POST['last_name'] ?? ''); ?>" 
                                           placeholder="Doe" required>
                                    <div class="invalid-feedback">
                                        Please enter your last name.
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <label for="email" class="form-label">Email Address *</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-envelope"></i></span>
                                    <input type="email" class="form-control" id="email" name="email" 
                                           value="<?php echo e($_POST['email'] ?? ''); ?>" 
                                           placeholder="your.email@example.com" required>
                                    <div class="invalid-feedback">
                                        Please enter a valid email address.
                                    </div>
                                </div>
                                <small class="text-muted">We'll send a verification email to this address.</small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="password" class="form-label">Password *</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                    <input type="password" class="form-control" id="password" name="password" 
                                           placeholder="Create a strong password" required>
                                    <button class="btn btn-outline-secondary" type="button" id="togglePassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <div class="invalid-feedback">
                                        Please enter a password.
                                    </div>
                                </div>
                                <small class="text-muted">
                                    Must be at least 8 characters with uppercase, lowercase, number, and special character.
                                </small>
                            </div>
                            
                            <div class="mb-3">
                                <label for="confirm_password" class="form-label">Confirm Password *</label>
                                <div class="input-group">
                                    <span class="input-group-text"><i class="fas fa-lock"></i></span>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                                           placeholder="Re-enter your password" required>
                                    <button class="btn btn-outline-secondary" type="button" id="toggleConfirmPassword">
                                        <i class="fas fa-eye"></i>
                                    </button>
                                    <div class="invalid-feedback">
                                        Passwords do not match.
                                    </div>
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="agree_terms" name="agree_terms" required>
                                    <label class="form-check-label" for="agree_terms">
                                        I agree to the 
                                        <a href="<?php echo SITE_URL; ?>/public/terms.php" target="_blank">Terms of Service</a> 
                                        and 
                                        <a href="<?php echo SITE_URL; ?>/public/privacy.php" target="_blank">Privacy Policy</a>
                                    </label>
                                    <div class="invalid-feedback">
                                        You must agree to the terms and conditions.
                                    </div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 py-2">
                                <i class="fas fa-user-plus"></i> Create Account
                            </button>
                        </form>

<script>
// Live validation for registration form
document.addEventListener('DOMContentLoaded', function () {
    const form = document.querySelector('form.needs-validation');
    const firstName = document.getElementById('first_name');
    const lastName = document.getElementById('last_name');
    const email = document.getElementById('email');
    const password = document.getElementById('password');
    const confirmPassword = document.getElementById('confirm_password');
    const agreeTerms = document.getElementById('agree_terms');

    // Email regex
    function isValidEmail(email) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
    }

    // Password strength
    function isStrongPassword(pw) {
        return pw.length >= 8 && /[A-Z]/.test(pw) && /[a-z]/.test(pw) && /[0-9]/.test(pw) && /[^A-Za-z0-9]/.test(pw);
    }

    function validateField(input, valid, message) {
        if (valid) {
            input.classList.remove('is-invalid');
            input.classList.add('is-valid');
        } else {
            input.classList.remove('is-valid');
            input.classList.add('is-invalid');
            if (message) {
                let feedback = input.parentElement.querySelector('.invalid-feedback');
                if (feedback) feedback.textContent = message;
            }
        }
    }

    firstName.addEventListener('input', function () {
        validateField(firstName, firstName.value.trim().length > 0, 'Please enter your first name.');
    });
    lastName.addEventListener('input', function () {
        validateField(lastName, lastName.value.trim().length > 0, 'Please enter your last name.');
    });
    email.addEventListener('input', function () {
        validateField(email, isValidEmail(email.value), 'Please enter a valid email address.');
    });
    password.addEventListener('input', function () {
        validateField(password, isStrongPassword(password.value), 'Password must be at least 8 characters, include uppercase, lowercase, number, and special character.');
        // Also check confirm password
        validateField(confirmPassword, password.value === confirmPassword.value && confirmPassword.value.length > 0, 'Passwords do not match.');
    });
    confirmPassword.addEventListener('input', function () {
        validateField(confirmPassword, password.value === confirmPassword.value && confirmPassword.value.length > 0, 'Passwords do not match.');
    });
    agreeTerms.addEventListener('change', function () {
        if (agreeTerms.checked) {
            agreeTerms.classList.remove('is-invalid');
            agreeTerms.classList.add('is-valid');
        } else {
            agreeTerms.classList.remove('is-valid');
            agreeTerms.classList.add('is-invalid');
        }
    });
});
</script>
                        
                        <hr class="my-4">
                        
                        <div class="text-center">
                            <p class="mb-0">Already have an account? 
                                <a href="<?php echo SITE_URL; ?>/login.php" class="text-decoration-none fw-bold">
                                    Login Here
                                </a>
                            </p>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
            
            <div class="text-center mb-4">
                <a href="<?php echo SITE_URL; ?>/index.php" class="text-decoration-none">
                    <i class="fas fa-arrow-left"></i> Back to Home
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Toggle password visibility
document.getElementById('togglePassword').addEventListener('click', function() {
    const passwordInput = document.getElementById('password');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        passwordInput.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
});

document.getElementById('toggleConfirmPassword').addEventListener('click', function() {
    const passwordInput = document.getElementById('confirm_password');
    const icon = this.querySelector('i');
    
    if (passwordInput.type === 'password') {
        passwordInput.type = 'text';
        icon.classList.remove('fa-eye');
        icon.classList.add('fa-eye-slash');
    } else {
        passwordInput.type = 'password';
        icon.classList.remove('fa-eye-slash');
        icon.classList.add('fa-eye');
    }
});

// Password match validation
document.getElementById('confirm_password').addEventListener('input', function() {
    const password = document.getElementById('password').value;
    const confirmPassword = this.value;
    
    if (password !== confirmPassword) {
        this.setCustomValidity('Passwords do not match');
    } else {
        this.setCustomValidity('');
    }
});
</script>

<?php // Include appropriate footer based on device
if ($isMobile) {
    include 'templates/mobile-footer.php';
} else {
    include 'templates/footer.php';
} ?>
