<?php
require_once '../config/config.php';

if (isLoggedIn()) {
    redirect('../index.php');
}

$error = '';
$success = '';
// Only allow candidate registration for public
$user_type = 'candidate';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $user_type = 'candidate'; // Force candidate type for public registration
    $email = sanitize($_POST['email']);
    $password = $_POST['password'];
    $confirm_password = $_POST['confirm_password'];
    
    if (empty($email) || empty($password) || empty($confirm_password)) {
        $error = 'All fields are required.';
    } elseif ($password !== $confirm_password) {
        $error = 'Passwords do not match.';
    } else {
        // Check password complexity
        $complexity_errors = validatePasswordComplexity($password);
        if (!empty($complexity_errors)) {
            $error = implode('<br>', $complexity_errors);
        } else {
        $database = new Database();
        $db = $database->getConnection();
        
        // Check if email already exists in all tables
        $check_tables = ['candidates', 'companies', 'admins'];
        
        $email_exists = false;
        foreach ($check_tables as $table) {
            $stmt = $db->prepare("SELECT id FROM $table WHERE email = ?");
            $stmt->execute([$email]);
            if ($stmt->fetch()) {
                $email_exists = true;
                break;
            }
        }
        
        if ($email_exists) {
            $error = 'Email address is already registered.';
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);
            
            try {
                // Only allow candidate registration
                $first_name = sanitize($_POST['first_name']);
                $last_name = sanitize($_POST['last_name']);
                $phone = sanitize($_POST['phone']);
                
                if (empty($first_name) || empty($last_name)) {
                    $error = 'First name and last name are required.';
                } else {
                    $stmt = $db->prepare("
                        INSERT INTO candidates (first_name, last_name, email, password, phone) 
                        VALUES (?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$first_name, $last_name, $email, $hashed_password, $phone]);
                    $success = 'Registration successful! You can now login to your account.';
                }
            } catch (PDOException $e) {
                $error = 'Registration 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">
    <title>Register - <?php echo SITE_NAME; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="../assets/css/style.css" rel="stylesheet">
</head>
<body class="bg-light">
    <div class="container">
        <div class="row justify-content-center py-5">
            <div class="col-md-8 col-lg-6">
                <div class="card shadow">
                    <div class="card-body p-5">
                        <div class="text-center mb-4">
                            <h2 class="fw-bold text-primary">
                                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
                            </h2>
                            <p class="text-muted">Create your candidate account</p>
                        </div>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger">
                                <i class="fas fa-exclamation-circle me-2"></i><?php echo $error; ?>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($success): ?>
                            <div class="alert alert-success">
                                <i class="fas fa-check-circle me-2"></i><?php echo $success; ?>
                                <div class="mt-2">
                                    <a href="login.php" class="btn btn-success btn-sm">Login Now</a>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" id="registrationForm">
                            <!-- Candidate Fields -->
                            <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 isset($_POST['first_name']) ? htmlspecialchars($_POST['first_name']) : ''; ?>" required>
                                </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 isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ''; ?>" required>
                                </div>
                            </div>
                            
                            <!-- Common Fields -->
                            <div class="mb-3">
                                <label for="email" class="form-label">Email Address</label>
                                <input type="email" class="form-control" id="email" name="email" 
                                       value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required>
                            </div>
                            
                            <div class="mb-3">
                                <label for="phone" class="form-label">Phone Number</label>
                                <input type="tel" class="form-control" id="phone" name="phone" 
                                       value="<?php echo isset($_POST['phone']) ? htmlspecialchars($_POST['phone']) : ''; ?>">
                            </div>
                            
                            <div class="alert alert-info">
                                <h6><i class="fas fa-info-circle me-1"></i>Password Requirements:</h6>
                                <ul class="mb-0 small">
                                    <li>At least 8 characters long</li>
                                    <li>Contains at least one uppercase letter (A-Z)</li>
                                    <li>Contains at least one lowercase letter (a-z)</li>
                                    <li>Contains at least one number (0-9)</li>
                                    <li>Contains at least one special character (!@#$%^&*)</li>
                                </ul>
                            </div>

                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="password" class="form-label">Password *</label>
                                    <input type="password" class="form-control" id="password" name="password" required>
                                    <div id="passwordStrength" class="mt-2"></div>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="confirm_password" class="form-label">Confirm Password *</label>
                                    <input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
                                    <div id="passwordMatch" class="form-text"></div>
                                </div>
                            </div>
                            
                            <button type="submit" class="btn btn-primary w-100 mb-3">
                                <i class="fas fa-user-plus me-2"></i>Create Candidate Account
                            </button>
                        </form>
                        
                        <div class="text-center">
                            <p class="mb-0">Already have an account? 
                                <a href="login.php" class="text-primary">Login here</a>
                            </p>
                            <a href="../index.php" class="text-muted">
                                <i class="fas fa-arrow-left me-1"></i>Back to Home
                            </a>
                        </div>
                        
                        <hr class="my-4">
                        
                        <div class="text-center">
                            <small class="text-muted">
                                <strong>Are you a company?</strong><br>
                                Companies are registered by administrators only.<br>
                                Please contact support for company registration.
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function checkPasswordStrength(password) {
            const requirements = [
                { regex: /.{8,}/, text: 'At least 8 characters', met: false },
                { regex: /[A-Z]/, text: 'Uppercase letter', met: false },
                { regex: /[a-z]/, text: 'Lowercase letter', met: false },
                { regex: /[0-9]/, text: 'Number', met: false },
                { regex: /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/, text: 'Special character', met: false }
            ];

            let score = 0;
            let html = '<div class="row">';

            requirements.forEach((req, index) => {
                req.met = req.regex.test(password);
                if (req.met) score++;
                
                const color = req.met ? 'text-success' : 'text-danger';
                const icon = req.met ? 'fa-check' : 'fa-times';
                
                html += `<div class="col-6 small ${color}">
                    <i class="fas ${icon} me-1"></i>${req.text}
                </div>`;
            });

            html += '</div>';

            let strength = '';
            let strengthClass = '';
            if (score === 0) {
                strength = '';
            } else if (score < 3) {
                strength = 'Weak';
                strengthClass = 'text-danger';
            } else if (score < 5) {
                strength = 'Medium';
                strengthClass = 'text-warning';
            } else {
                strength = 'Strong';
                strengthClass = 'text-success';
            }

            if (strength) {
                html += `<div class="mt-2 ${strengthClass}"><strong>Password Strength: ${strength}</strong></div>`;
            }

            return { html, score, isStrong: score === 5 };
        }

        function validateForm() {
            const password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm_password').value;

            const strength = checkPasswordStrength(password);
            const passwordsMatch = password === confirmPassword && password.length > 0;

            // Update password match indicator
            const matchDiv = document.getElementById('passwordMatch');
            if (confirmPassword.length > 0) {
                if (passwordsMatch) {
                    matchDiv.innerHTML = '<span class="text-success"><i class="fas fa-check me-1"></i>Passwords match</span>';
                } else {
                    matchDiv.innerHTML = '<span class="text-danger"><i class="fas fa-times me-1"></i>Passwords do not match</span>';
                }
            } else {
                matchDiv.innerHTML = '';
            }
        }

        // Real-time validation
        document.getElementById('password').addEventListener('input', function() {
            const strength = checkPasswordStrength(this.value);
            document.getElementById('passwordStrength').innerHTML = strength.html;
            validateForm();
        });

        document.getElementById('confirm_password').addEventListener('input', validateForm);
    </script>
</body>
</html>