<?php
require_once 'config.php';

$error = '';
$success = '';

// Initialize variables for form data
$first_name = '';
$last_name = '';
$email = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $password = $_POST['password'];

    // Reset error
    $error = '';

    // Field validations - Allow letters, hyphens, and spaces only
    if (empty($first_name)) {
        $error = "First name is required.";
    } elseif (strlen($first_name) < 2) {
        $error = "First name must be at least 2 characters.";
    } elseif (strlen($first_name) > 50) {
        $error = "First name cannot exceed 50 characters.";
    } elseif (!preg_match("/^[a-zA-Z- ]+$/", $first_name)) {
        $error = "First name can only contain letters (A-Z, a-z), hyphens (-), and spaces.";
    }

    elseif (empty($last_name)) {
        $error = "Last name is required.";
    } elseif (strlen($last_name) < 2) {
        $error = "Last name must be at least 2 characters.";
    } elseif (strlen($last_name) > 50) {
        $error = "Last name cannot exceed 50 characters.";
    } elseif (!preg_match("/^[a-zA-Z- ]+$/", $last_name)) {
        $error = "Last name can only contain letters (A-Z, a-z), hyphens (-), and spaces.";
    }

    elseif (empty($email)) {
        $error = "Email address is required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Please enter a valid email address (e.g., name@example.com).";
    } elseif (strlen($email) > 100) {
        $error = "Email address cannot exceed 100 characters.";
    }

    elseif (empty($password)) {
        $error = "Password is required.";
    } elseif (strlen($password) < 8) {
        $error = "Password must be at least 8 characters long.";
    }

    // If no validation errors, proceed with database check
    if (empty($error)) {
        $stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $stmt->execute([$email]);
        if ($stmt->fetch()) {
            $error = "Email already registered. Please sign in.";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            $sql = "INSERT INTO users (first_name, last_name, email, password) VALUES (?, ?, ?, ?)";
            $stmt = $pdo->prepare($sql);
            if ($stmt->execute([$first_name, $last_name, $email, $hashed_password])) {
                $_SESSION['temp_user'] = [
                    'first_name' => $first_name,
                    'last_name' => $last_name,
                    'email' => $email
                ];
                $success = "Account created! Redirecting to sign in...";
                header("refresh:2;url=signin.php");
            } else {
                $error = "Sign up failed. Please try again.";
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
    <title>Sign Up | ARC 2026</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 20px;
            position: relative;
            overflow-x: hidden;
        }
        body::before {
            content: '';
            position: absolute;
            width: 100%;
            height: 100%;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="rgba(255,255,255,0.1)" fill-opacity="1" d="M0,96L48,112C96,128,192,160,288,160C384,160,480,128,576,122.7C672,117,768,139,864,154.7C960,171,1056,181,1152,165.3C1248,149,1344,107,1392,85.3L1440,64L1440,320L1392,320C1344,320,1248,320,1152,320C1056,320,960,320,864,320C768,320,672,320,576,320C480,320,384,320,288,320C192,320,96,320,48,320L0,320Z"></path></svg>') no-repeat bottom;
            background-size: cover;
            bottom: 0;
            left: 0;
            pointer-events: none;
        }
        .container {
            max-width: 500px;
            width: 100%;
            background: rgba(255, 255, 255, 0.98);
            border-radius: 32px;
            box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
            overflow: hidden;
            position: relative;
            z-index: 1;
            animation: slideUp 0.5s ease-out;
        }
        @keyframes slideUp {
            from {
                opacity: 0;
                transform: translateY(30px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }
        .header {
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            padding: 40px 30px;
            text-align: center;
            color: white;
        }
        .header h1 {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
        }
        .header p {
            font-size: 14px;
            opacity: 0.9;
        }
        .form-content {
            padding: 40px 30px;
        }
        .input-group {
            margin-bottom: 24px;
            position: relative;
        }
        .input-group i {
            position: absolute;
            left: 16px;
            top: 50%;
            transform: translateY(-50%);
            color: #9ca3af;
            font-size: 18px;
            z-index: 1;
            pointer-events: none;
        }
        .input-group input {
            width: 100%;
            padding: 14px 16px 14px 48px;
            border: 2px solid #e5e7eb;
            border-radius: 16px;
            font-size: 15px;
            font-family: 'Inter', sans-serif;
            transition: all 0.3s;
            background: #f9fafb;
        }
        .input-group input:focus {
            outline: none;
            border-color: #2a5298;
            background: white;
            box-shadow: 0 0 0 4px rgba(42, 82, 152, 0.1);
        }
        /* Hint styling */
        .hint {
            display: block;
            font-size: 12px;
            color: #6b7280;
            margin-top: 6px;
            margin-left: 48px;
        }
        .input-group.error input {
            border-color: #dc2626;
            background-color: #fef2f2;
        }
        .input-group.error .hint {
            color: #dc2626;
        }
        .btn {
            width: 100%;
            padding: 14px;
            background: linear-gradient(135deg, #1e3c72 0%, #2a5298 100%);
            color: white;
            border: none;
            border-radius: 16px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s, box-shadow 0.2s;
            font-family: 'Inter', sans-serif;
        }
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 25px -5px rgba(30, 60, 114, 0.4);
        }
        .btn:active {
            transform: translateY(0);
        }
        .footer-link {
            text-align: center;
            margin-top: 24px;
            color: #6b7280;
            font-size: 14px;
        }
        .footer-link a {
            color: #2a5298;
            text-decoration: none;
            font-weight: 600;
        }
        .footer-link a:hover {
            text-decoration: underline;
        }
        .alert {
            padding: 14px 16px;
            border-radius: 16px;
            margin-bottom: 24px;
            font-size: 14px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .alert-error {
            background: #fee2e2;
            color: #dc2626;
            border-left: 4px solid #dc2626;
        }
        .alert-success {
            background: #dcfce7;
            color: #16a34a;
            border-left: 4px solid #16a34a;
        }
        /* Password character counter */
        .password-counter {
            margin-left: 48px;
            margin-top: 6px;
            font-size: 11px;
            color: #6b7280;
        }
        .password-counter.valid {
            color: #10b981;
        }
        .password-counter.invalid {
            color: #dc2626;
        }
        /* Character counter for name fields */
        .char-counter {
            margin-left: 48px;
            margin-top: 4px;
            font-size: 11px;
            color: #6b7280;
        }
        .char-counter.warning {
            color: #f59e0b;
        }
        .char-counter.danger {
            color: #dc2626;
        }
        /* Password strength indicator */
        .password-strength {
            margin-left: 48px;
            margin-top: 6px;
            display: flex;
            gap: 6px;
            align-items: center;
        }
        .strength-bar {
            height: 4px;
            flex: 1;
            background: #e5e7eb;
            border-radius: 2px;
            transition: all 0.3s;
        }
        .strength-bar.weak { background: #dc2626; }
        .strength-bar.medium { background: #f59e0b; }
        .strength-bar.strong { background: #10b981; }
        .strength-text {
            font-size: 11px;
            color: #6b7280;
            min-width: 50px;
        }
        @media (max-width: 640px) {
            .container {
                margin: 10px;
            }
            .header {
                padding: 30px 20px;
            }
            .header h1 {
                font-size: 24px;
            }
            .form-content {
                padding: 30px 20px;
            }
            .hint {
                margin-left: 40px;
                font-size: 10px;
            }
            .char-counter, .password-counter, .password-strength {
                margin-left: 40px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1><i class="fas fa-chalkboard-user"></i> ARC 2026</h1>
            <p>Fill in the information below to sign up.</p>
        </div>
        <div class="form-content">
            <?php if($error): ?>
                <div class="alert alert-error">
                    <i class="fas fa-exclamation-circle"></i>
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle"></i>
                    <?php echo htmlspecialchars($success); ?>
                </div>
            <?php endif; ?>
            
            <form method="POST" action="" id="signupForm">
                <div class="input-group" id="firstNameGroup">
                    <i class="fas fa-user"></i>
                    <input type="text" name="first_name" id="firstName" placeholder="First Name" 
                           value="<?php echo htmlspecialchars($first_name); ?>">
                    <span class="hint">2-50 characters, letters, hyphens, and spaces only</span>
                    <div class="char-counter" id="firstNameCounter"></div>
                </div>
                
                <div class="input-group" id="lastNameGroup">
                    <i class="fas fa-user"></i>
                    <input type="text" name="last_name" id="lastName" placeholder="Last Name" 
                           value="<?php echo htmlspecialchars($last_name); ?>">
                    <span class="hint">2-50 characters, letters, hyphens, and spaces only</span>
                    <div class="char-counter" id="lastNameCounter"></div>
                </div>
                
                <div class="input-group" id="emailGroup">
                    <i class="fas fa-envelope"></i>
                    <input type="email" name="email" id="email" placeholder="Email Address" 
                           value="<?php echo htmlspecialchars($email); ?>">
                    <span class="hint">Enter a valid email address (e.g., name@example.com)</span>
                </div>
                
                <div class="input-group" id="passwordGroup">
                    <i class="fas fa-lock"></i>
                    <input type="password" name="password" id="password" placeholder="Password (minimum 8 characters)">
                    <span class="hint">Password must be at least 8 characters long</span>
                    <div class="password-counter" id="passwordCounter">
                        <i class="fas fa-info-circle"></i> Minimum 8 characters
                    </div>
                    <div class="password-strength" id="passwordStrength">
                        <div class="strength-bar"></div>
                        <div class="strength-bar"></div>
                        <div class="strength-bar"></div>
                        <div class="strength-text" id="strengthText"></div>
                    </div>
                </div>
                
                <button type="submit" class="btn">
                    <i class="fas fa-user-plus"></i> Create Account
                </button>
            </form>
            <div class="footer-link">
                Already have an account? <a href="signin.php">Sign In</a>
            </div>
        </div>
    </div>

    <script>
        // Allow letters, spaces, and hyphens only for name fields
        function restrictToValidNameCharacters(inputElement) {
            inputElement.addEventListener('input', function(e) {
                this.value = this.value.replace(/[^a-zA-Z- ]/g, '');
            });
        }
        
        // Update character counter for name fields
        function updateNameCounter(inputId, counterId, minLength = 2, maxLength = 50) {
            const input = document.getElementById(inputId);
            const counter = document.getElementById(counterId);
            const length = input.value.length;
            
            if (length === 0) {
                counter.innerHTML = '';
                counter.className = 'char-counter';
            } else if (length < minLength) {
                counter.innerHTML = `⚠️ ${length}/${minLength} minimum characters needed`;
                counter.className = 'char-counter warning';
            } else if (length > maxLength) {
                counter.innerHTML = `❌ ${length}/${maxLength} - Too many characters`;
                counter.className = 'char-counter danger';
            } else {
                counter.innerHTML = `✓ ${length} characters (good)`;
                counter.className = 'char-counter';
            }
        }
        
        // Check password strength
        function checkPasswordStrength() {
            const password = document.getElementById('password').value;
            const bars = document.querySelectorAll('#passwordStrength .strength-bar');
            const strengthText = document.getElementById('strengthText');
            
            let strength = 0;
            
            if (password.length >= 8) strength++;
            if (password.length >= 12) strength++;
            if (/[A-Z]/.test(password)) strength++;
            if (/[a-z]/.test(password)) strength++;
            if (/[0-9]/.test(password)) strength++;
            if (/[^a-zA-Z0-9]/.test(password)) strength++;
            
            let level = 0;
            let message = '';
            
            if (password.length === 0) {
                level = 0;
                message = '';
            } else if (strength <= 2) {
                level = 1;
                message = 'Weak';
            } else if (strength <= 4) {
                level = 2;
                message = 'Medium';
            } else {
                level = 3;
                message = 'Strong';
            }
            
            // Update bars
            bars.forEach((bar, index) => {
                bar.className = 'strength-bar';
                if (index < level) {
                    if (level === 1) bar.classList.add('weak');
                    else if (level === 2) bar.classList.add('medium');
                    else if (level === 3) bar.classList.add('strong');
                }
            });
            
            strengthText.textContent = message;
        }
        
        // Real-time validation functions
        function validateFirstName() {
            const input = document.getElementById('firstName');
            const group = document.getElementById('firstNameGroup');
            const value = input.value.trim();
            
            updateNameCounter('firstName', 'firstNameCounter', 2, 50);
            
            if (value === '') {
                group.classList.add('error');
                return false;
            } else if (value.length < 2) {
                group.classList.add('error');
                return false;
            } else if (value.length > 50) {
                group.classList.add('error');
                return false;
            } else if (!/^[a-zA-Z- ]+$/.test(value)) {
                group.classList.add('error');
                return false;
            } else {
                group.classList.remove('error');
                return true;
            }
        }
        
        function validateLastName() {
            const input = document.getElementById('lastName');
            const group = document.getElementById('lastNameGroup');
            const value = input.value.trim();
            
            updateNameCounter('lastName', 'lastNameCounter', 2, 50);
            
            if (value === '') {
                group.classList.add('error');
                return false;
            } else if (value.length < 2) {
                group.classList.add('error');
                return false;
            } else if (value.length > 50) {
                group.classList.add('error');
                return false;
            } else if (!/^[a-zA-Z- ]+$/.test(value)) {
                group.classList.add('error');
                return false;
            } else {
                group.classList.remove('error');
                return true;
            }
        }
        
        function validateEmail() {
            const input = document.getElementById('email');
            const group = document.getElementById('emailGroup');
            const value = input.value.trim();
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            
            if (value === '') {
                group.classList.add('error');
                return false;
            } else if (!emailRegex.test(value)) {
                group.classList.add('error');
                return false;
            } else if (value.length > 100) {
                group.classList.add('error');
                return false;
            } else {
                group.classList.remove('error');
                return true;
            }
        }
        
        function validatePassword() {
            const password = document.getElementById('password').value;
            const group = document.getElementById('passwordGroup');
            const counter = document.getElementById('passwordCounter');
            
            if (password === '') {
                group.classList.add('error');
                counter.innerHTML = '<i class="fas fa-info-circle"></i> Password is required (minimum 8 characters)';
                counter.className = 'password-counter invalid';
                return false;
            } else if (password.length < 8) {
                group.classList.add('error');
                let remaining = 8 - password.length;
                counter.innerHTML = `<i class="fas fa-exclamation-circle"></i> Need ${remaining} more character${remaining !== 1 ? 's' : ''} to reach minimum 8`;
                counter.className = 'password-counter invalid';
                return false;
            } else {
                group.classList.remove('error');
                counter.innerHTML = '<i class="fas fa-check-circle"></i> Password length is good!';
                counter.className = 'password-counter valid';
                return true;
            }
        }
        
        // Update password counter in real-time
        function updatePasswordCounter() {
            const password = document.getElementById('password').value;
            const counter = document.getElementById('passwordCounter');
            
            if (password.length === 0) {
                counter.innerHTML = '<i class="fas fa-info-circle"></i> Minimum 8 characters';
                counter.className = 'password-counter';
            } else if (password.length < 8) {
                let remaining = 8 - password.length;
                counter.innerHTML = `<i class="fas fa-exclamation-circle"></i> Need ${remaining} more character${remaining !== 1 ? 's' : ''} (${password.length}/8)`;
                counter.className = 'password-counter invalid';
            } else {
                counter.innerHTML = `<i class="fas fa-check-circle"></i> Great! ${password.length} characters (minimum met)`;
                counter.className = 'password-counter valid';
            }
            
            checkPasswordStrength();
        }
        
        // Apply restriction to name inputs (letters, spaces, hyphens only)
        const firstNameInput = document.getElementById('firstName');
        const lastNameInput = document.getElementById('lastName');
        restrictToValidNameCharacters(firstNameInput);
        restrictToValidNameCharacters(lastNameInput);
        
        // Add event listeners for real-time validation
        firstNameInput.addEventListener('input', validateFirstName);
        lastNameInput.addEventListener('input', validateLastName);
        document.getElementById('email').addEventListener('input', validateEmail);
        document.getElementById('password').addEventListener('input', function() {
            updatePasswordCounter();
            validatePassword();
        });
        
        // Form submission validation
        document.getElementById('signupForm').addEventListener('submit', function(e) {
            const isFirstNameValid = validateFirstName();
            const isLastNameValid = validateLastName();
            const isEmailValid = validateEmail();
            const isPasswordValid = validatePassword();
            
            if (!isFirstNameValid || !isLastNameValid || !isEmailValid || !isPasswordValid) {
                e.preventDefault();
                // Scroll to first error
                const firstError = document.querySelector('.input-group.error input');
                if (firstError) {
                    firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    firstError.focus();
                }
            }
        });
        
        // Initial validation on page load if there are values
        if (firstNameInput.value) {
            updateNameCounter('firstName', 'firstNameCounter', 2, 50);
            validateFirstName();
        }
        if (lastNameInput.value) {
            updateNameCounter('lastName', 'lastNameCounter', 2, 50);
            validateLastName();
        }
        if (document.getElementById('email').value) validateEmail();
        if (document.getElementById('password').value) {
            updatePasswordCounter();
            validatePassword();
        }
    </script>
</body>
</html>