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

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

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

// Get companies for internal candidate selection
$database = new Database();
$db = $database->getConnection();
$companies = [];
try {
    $stmt = $db->prepare("SELECT id, name FROM companies WHERE status = 'approved' ORDER BY name");
    $stmt->execute();
    $companies = $stmt->fetchAll();
} catch (PDOException $e) {
    // Continue without companies if query fails
}

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 connection already initialized above
        
        // 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 {
                // Allow candidate registration with internal/external choice
                $first_name = sanitize($_POST['first_name']);
                $last_name = sanitize($_POST['last_name']);
                $phone = sanitize($_POST['phone']);
                $candidate_type = sanitize($_POST['candidate_type']);
                $nationality = sanitize($_POST['nationality']);
                $id_number = null;
                $passport_number = null;
                $company_id = null;
                $employee_id = null;
                $current_department = null;
                $current_position = null;
                $approval_status = 'approved'; // External candidates are auto-approved
                
                // Handle nationality and identification
                if ($nationality === 'south_african') {
                    $id_number = sanitize($_POST['id_number']);
                    if (empty($id_number)) {
                        $error = 'South African ID number is required.';
                    } elseif (!preg_match('/^[0-9]{13}$/', $id_number)) {
                        $error = 'South African ID number must be exactly 13 digits.';
                    }
                } elseif ($nationality === 'foreign') {
                    $passport_number = sanitize($_POST['passport_number']);
                    if (empty($passport_number)) {
                        $error = 'Passport number is required for foreign nationals.';
                    }
                } else {
                    $error = 'Please select your nationality.';
                }
                
                if (empty($first_name) || empty($last_name) || empty($candidate_type)) {
                    $error = 'First name, last name, and candidate type are required.';
                } elseif ($candidate_type === 'internal') {
                    // Internal candidate validation
                    $company_id = (int)$_POST['company_id'];
                    $employee_id = sanitize($_POST['employee_id']);
                    $current_department = sanitize($_POST['current_department']);
                    $current_position = sanitize($_POST['current_position']);
                    $approval_status = 'pending'; // Internal candidates need approval
                    
                    if (empty($company_id) || empty($employee_id) || empty($current_department) || empty($current_position)) {
                        $error = 'All internal candidate fields are required.';
                    }
                }
                
                if (!$error) {
                    $stmt = $db->prepare("
                        INSERT INTO candidates (first_name, last_name, email, password, phone, candidate_type, nationality, id_number, passport_number, company_id, employee_id, current_department, current_position, approval_status) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$first_name, $last_name, $email, $hashed_password, $phone, $candidate_type, $nationality, $id_number, $passport_number, $company_id, $employee_id, $current_department, $current_position, $approval_status]);
                    
                    if ($candidate_type === 'internal') {
                        $success = 'Registration successful! Your account is pending approval from your company HR. You will receive an email once approved.';
                    } else {
                        $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 Type Selection -->
                            <div class="mb-4">
                                <label class="form-label">Candidate Type *</label>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="candidate_type" id="external" value="external" 
                                                   <?php echo (!isset($_POST['candidate_type']) || $_POST['candidate_type'] === 'external') ? 'checked' : ''; ?> onchange="toggleInternalFields()">
                                            <label class="form-check-label" for="external">
                                                <i class="fas fa-user me-2"></i>External Candidate
                                                <small class="d-block text-muted">Job seeker from outside the company</small>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="form-check">
                                            <input class="form-check-input" type="radio" name="candidate_type" id="internal" value="internal" 
                                                   <?php echo (isset($_POST['candidate_type']) && $_POST['candidate_type'] === 'internal') ? 'checked' : ''; ?> onchange="toggleInternalFields()">
                                            <label class="form-check-label" for="internal">
                                                <i class="fas fa-building me-2"></i>Internal Candidate
                                                <small class="d-block text-muted">Current employee seeking internal transfer</small>
                                            </label>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Basic 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>

                            <!-- Nationality Section -->
                            <div class="card mb-3">
                                <div class="card-header bg-info text-white">
                                    <h6 class="mb-0"><i class="fas fa-flag me-2"></i>Nationality & Identification</h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">Nationality *</label>
                                        <div>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="nationality" id="south_african" value="south_african" 
                                                       <?php echo (!isset($_POST['nationality']) || $_POST['nationality'] === 'south_african') ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="south_african">
                                                    <i class="fas fa-flag me-1"></i>South African
                                                </label>
                                            </div>
                                            <div class="form-check form-check-inline">
                                                <input class="form-check-input" type="radio" name="nationality" id="foreign" value="foreign"
                                                       <?php echo (isset($_POST['nationality']) && $_POST['nationality'] === 'foreign') ? 'checked' : ''; ?>>
                                                <label class="form-check-label" for="foreign">
                                                    <i class="fas fa-globe me-1"></i>Foreign National
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <div id="south_african_id" class="mb-3">
                                        <label for="id_number" class="form-label">South African ID Number *</label>
                                        <input type="text" class="form-control" id="id_number" name="id_number" 
                                               maxlength="13" pattern="[0-9]{13}"
                                               value="<?php echo isset($_POST['id_number']) ? htmlspecialchars($_POST['id_number']) : ''; ?>"
                                               placeholder="e.g. 9001015009087">
                                        <div class="form-text">Enter your 13-digit South African ID number</div>
                                    </div>
                                    
                                    <div id="foreign_passport" class="mb-3" style="display: none;">
                                        <label for="passport_number" class="form-label">Passport Number *</label>
                                        <input type="text" class="form-control" id="passport_number" name="passport_number" 
                                               maxlength="20"
                                               value="<?php echo isset($_POST['passport_number']) ? htmlspecialchars($_POST['passport_number']) : ''; ?>"
                                               placeholder="e.g. A12345678">
                                        <div class="form-text">Enter your international passport number</div>
                                    </div>
                                </div>
                            </div>

                            <!-- Internal Candidate Fields -->
                            <div id="internalFields" style="display: none;">
                                <div class="card mb-3">
                                    <div class="card-header bg-primary text-white">
                                        <h6 class="mb-0"><i class="fas fa-building me-2"></i>Internal Candidate Information</h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label for="company_id" class="form-label">Your Company *</label>
                                            <select class="form-control" id="company_id" name="company_id">
                                                <option value="">Select your company...</option>
                                                <?php foreach ($companies as $company): ?>
                                                    <option value="<?php echo $company['id']; ?>" 
                                                            <?php echo (isset($_POST['company_id']) && $_POST['company_id'] == $company['id']) ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($company['name']); ?>
                                                    </option>
                                                <?php endforeach; ?>
                                            </select>
                                        </div>
                                        
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="employee_id" class="form-label">Employee ID *</label>
                                                <input type="text" class="form-control" id="employee_id" name="employee_id" 
                                                       value="<?php echo isset($_POST['employee_id']) ? htmlspecialchars($_POST['employee_id']) : ''; ?>"
                                                       placeholder="e.g. EMP001">
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="current_department" class="form-label">Current Department *</label>
                                                <input type="text" class="form-control" id="current_department" name="current_department" 
                                                       value="<?php echo isset($_POST['current_department']) ? htmlspecialchars($_POST['current_department']) : ''; ?>"
                                                       placeholder="e.g. IT Support">
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="current_position" class="form-label">Current Position *</label>
                                            <input type="text" class="form-control" id="current_position" name="current_position" 
                                                   value="<?php echo isset($_POST['current_position']) ? htmlspecialchars($_POST['current_position']) : ''; ?>"
                                                   placeholder="e.g. Junior IT Support Specialist">
                                        </div>
                                        
                                        <div class="alert alert-warning">
                                            <i class="fas fa-exclamation-triangle me-2"></i>
                                            <strong>Note:</strong> Internal candidate registrations require approval from your company's HR department before your account is activated.
                                        </div>
                                    </div>
                                </div>
                            </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 toggleInternalFields() {
            const internalRadio = document.getElementById('internal');
            const internalFields = document.getElementById('internalFields');
            const requiredInternalFields = ['company_id', 'employee_id', 'current_department', 'current_position'];
            
            if (internalRadio.checked) {
                internalFields.style.display = 'block';
                // Make internal fields required
                requiredInternalFields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) field.required = true;
                });
            } else {
                internalFields.style.display = 'none';
                // Remove required attribute from internal fields
                requiredInternalFields.forEach(fieldId => {
                    const field = document.getElementById(fieldId);
                    if (field) field.required = false;
                });
            }
        }
        
        // Initialize form on page load
        document.addEventListener('DOMContentLoaded', function() {
            toggleInternalFields();
            <?php if (isset($_POST['candidate_type']) && $_POST['candidate_type'] === 'internal'): ?>
                document.getElementById('internalFields').style.display = 'block';
            <?php endif; ?>
        });

        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);

        // Nationality toggle functionality
        function toggleNationalityFields() {
            const southAfricanRadio = document.getElementById('south_african');
            const foreignRadio = document.getElementById('foreign');
            const southAfricanDiv = document.getElementById('south_african_id');
            const foreignDiv = document.getElementById('foreign_passport');
            const idInput = document.getElementById('id_number');
            const passportInput = document.getElementById('passport_number');

            if (southAfricanRadio.checked) {
                southAfricanDiv.style.display = 'block';
                foreignDiv.style.display = 'none';
                idInput.required = true;
                passportInput.required = false;
                passportInput.value = '';
            } else if (foreignRadio.checked) {
                southAfricanDiv.style.display = 'none';
                foreignDiv.style.display = 'block';
                idInput.required = false;
                passportInput.required = true;
                idInput.value = '';
            }
        }

        // Initialize nationality fields on page load
        document.addEventListener('DOMContentLoaded', function() {
            toggleNationalityFields();
            
            // Add event listeners to nationality radio buttons
            document.getElementById('south_african').addEventListener('change', toggleNationalityFields);
            document.getElementById('foreign').addEventListener('change', toggleNationalityFields);
        });
    </script>
</body>
</html>