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

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

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

// Get list of approved companies for internal candidate selection
$database = new Database();
$db = $database->getConnection();
$stmt = $db->prepare("SELECT id, name FROM companies WHERE status = 'approved' ORDER BY name");
$stmt->execute();
$companies = $stmt->fetchAll();

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'];
    $candidate_type = $_POST['candidate_type'] ?? 'external';
    $employee_code = sanitize($_POST['employee_code'] ?? '');
    $company_id = ($candidate_type === 'internal' && isset($_POST['company_id'])) ? (int)$_POST['company_id'] : null;
    
    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 {
            // Validate fields for internal candidates
            if ($candidate_type === 'internal') {
                if (empty($employee_code)) {
                    $error = 'Employee code is required for internal candidates.';
                } elseif (empty($company_id)) {
                    $error = 'Please select your company.';
                }
            }
            
            if (!$error) {
        $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']);
                $is_foreign_national = $_POST['is_foreign_national'] ?? 'no';
                $passport_number = ($is_foreign_national === 'yes') ? sanitize($_POST['passport_number'] ?? '') : null;
                $sa_id_number = ($is_foreign_national === 'no') ? sanitize($_POST['sa_id_number'] ?? '') : null;
                $country = ($is_foreign_national === 'yes') ? sanitize($_POST['country'] ?? '') : null;
                
                if (empty($first_name) || empty($last_name)) {
                    $error = 'First name and last name are required.';
                } elseif ($is_foreign_national === 'yes' && empty($passport_number)) {
                    $error = 'Passport number is required for foreign nationals.';
                } elseif ($is_foreign_national === 'yes' && empty($country)) {
                    $error = 'Country is required for foreign nationals.';
                } elseif ($is_foreign_national === 'no' && empty($sa_id_number)) {
                    $error = 'South African ID number is required for SA citizens/permanent residents.';
                } elseif ($is_foreign_national === 'no' && !preg_match('/^\d{13}$/', $sa_id_number)) {
                    $error = 'South African ID number must be exactly 13 digits.';
                } else {
                    // Set approval status based on candidate type
                    $hr_approval_status = ($candidate_type === 'internal') ? 'pending' : 'approved';
                    
                    $stmt = $db->prepare("
                        INSERT INTO candidates (first_name, last_name, email, password, phone, candidate_type, employee_code, company_id, hr_approval_status, is_foreign_national, passport_number, sa_id_number, country) 
                        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$first_name, $last_name, $email, $hashed_password, $phone, $candidate_type, $employee_code, $company_id, $hr_approval_status, $is_foreign_national, $passport_number, $sa_id_number, $country]);
                    
                    if ($candidate_type === 'internal') {
                        $success = 'Registration successful! Your account is pending company approval. You will be notified 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">
    <style>
        .candidate-type-card {
            cursor: pointer;
            transition: all 0.3s ease;
            border-color: #dee2e6 !important;
        }
        
        .candidate-type-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .candidate-type-card.selected {
            border-color: #0d6efd !important;
            background-color: #f8f9fa;
        }
        
        .candidate-type-card.selected.external {
            border-color: #0d6efd !important;
        }
        
        .candidate-type-card.selected.internal {
            border-color: #198754 !important;
        }
        
        .cursor-pointer {
            cursor: pointer;
        }
    </style>
</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 fw-bold">Candidate Type *</label>
                                <div class="row">
                                    <div class="col-md-6">
                                        <div class="card border-2 candidate-type-card" data-type="external">
                                            <div class="card-body text-center py-4">
                                                <input type="radio" class="form-check-input d-none" id="external" name="candidate_type" value="external" <?php echo (!isset($_POST['candidate_type']) || $_POST['candidate_type'] === 'external') ? 'checked' : ''; ?>>
                                                <label for="external" class="w-100 cursor-pointer">
                                                    <i class="fas fa-user-plus fa-3x text-primary mb-3"></i>
                                                    <h5 class="text-primary mb-2">External Candidate</h5>
                                                    <p class="text-muted mb-0 small">Job seekers from outside the organization</p>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-6">
                                        <div class="card border-2 candidate-type-card" data-type="internal">
                                            <div class="card-body text-center py-4">
                                                <input type="radio" class="form-check-input d-none" id="internal" name="candidate_type" value="internal" <?php echo (isset($_POST['candidate_type']) && $_POST['candidate_type'] === 'internal') ? 'checked' : ''; ?>>
                                                <label for="internal" class="w-100 cursor-pointer">
                                                    <i class="fas fa-building fa-3x text-success mb-3"></i>
                                                    <h5 class="text-success mb-2">Internal Employee</h5>
                                                    <p class="text-muted mb-0 small">Current employees seeking new positions</p>
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Internal Candidate Fields -->
                            <div id="internalCandidateSection" class="mb-4" style="display: none;">
                                <div class="alert alert-warning">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Internal Candidates:</strong> Your registration requires company approval and will be reviewed before activation.
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="company_id" class="form-label">Select Your Company *</label>
                                        <select class="form-select" id="company_id" name="company_id">
                                            <option value="">Choose 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="col-md-6 mb-3">
                                        <label for="employee_code" class="form-label">Employee Code *</label>
                                        <input type="text" class="form-control" id="employee_code" name="employee_code" 
                                               placeholder="Enter your employee code" 
                                               value="<?php echo isset($_POST['employee_code']) ? htmlspecialchars($_POST['employee_code']) : ''; ?>">
                                    </div>
                                </div>
                                <div class="form-text">Contact your company's HR department if you don't know your employee code.</div>
                            </div>
                            
                            <!-- 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>
                            
                            
                            <!-- Foreign National Section -->
                            <div class="card bg-light mb-4">
                                <div class="card-header">
                                    <h6 class="mb-0">
                                        <i class="fas fa-globe me-2"></i>Nationality Status
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <label class="form-label">Are you a foreign national? *</label>
                                        <div class="row">
                                            <div class="col-md-6">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="is_foreign_national" id="nationality_no" value="no" 
                                                           <?php echo (!isset($_POST['is_foreign_national']) || $_POST['is_foreign_national'] === 'no') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="nationality_no">
                                                        <strong>No</strong> - South African Citizen/Permanent Resident
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="is_foreign_national" id="nationality_yes" value="yes" 
                                                           <?php echo (isset($_POST['is_foreign_national']) && $_POST['is_foreign_national'] === 'yes') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="nationality_yes">
                                                        <strong>Yes</strong> - Foreign National
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- SA ID Number Section -->
                                    <div id="saIdSection" class="mb-3" style="display: block;">
                                        <label for="sa_id_number" class="form-label">South African ID Number *</label>
                                        <input type="text" class="form-control" id="sa_id_number" name="sa_id_number" 
                                               placeholder="Enter your 13-digit SA ID number" 
                                               maxlength="13"
                                               pattern="[0-9]{13}"
                                               value="<?php echo isset($_POST['sa_id_number']) ? htmlspecialchars($_POST['sa_id_number']) : ''; ?>">
                                        <div id="saIdFeedback" class="form-text mt-1"></div>
                                        <div class="form-text">
                                            <i class="fas fa-id-card me-1"></i>Enter your 13-digit South African ID number (e.g., 9001015009087)
                                        </div>
                                    </div>
                                    
                                    <!-- Passport Section -->
                                    <div id="passportSection" class="mb-3" style="display: none;">
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label for="passport_number" class="form-label">Passport Number *</label>
                                                <input type="text" class="form-control" id="passport_number" name="passport_number" 
                                                       placeholder="Enter your passport number" 
                                                       value="<?php echo isset($_POST['passport_number']) ? htmlspecialchars($_POST['passport_number']) : ''; ?>">
                                                <div class="form-text">
                                                    <i class="fas fa-passport me-1"></i>Enter your passport number
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label for="country" class="form-label">Country of Origin *</label>
                                                <select class="form-select" id="country" name="country">
                                                    <option value="">Select your country...</option>
                                                    <optgroup label="Popular Countries">
                                                        <?php 
                                                        $popular_countries = getPopularCountries();
                                                        foreach ($popular_countries as $country): 
                                                        ?>
                                                            <option value="<?php echo htmlspecialchars($country); ?>" 
                                                                    <?php echo (isset($_POST['country']) && $_POST['country'] === $country) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($country); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                    <optgroup label="All Countries">
                                                        <?php 
                                                        $all_countries = getCountriesList();
                                                        foreach ($all_countries as $country): 
                                                            // Skip if already in popular list
                                                            if (in_array($country, $popular_countries)) continue;
                                                        ?>
                                                            <option value="<?php echo htmlspecialchars($country); ?>" 
                                                                    <?php echo (isset($_POST['country']) && $_POST['country'] === $country) ? 'selected' : ''; ?>>
                                                                <?php echo htmlspecialchars($country); ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </optgroup>
                                                </select>
                                                <div class="form-text">
                                                    <i class="fas fa-globe me-1"></i>Select your country of citizenship
                                                </div>
                                            </div>
                                        </div>
                                        <div class="alert alert-info mb-0">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <strong>Note:</strong> Please ensure your passport is valid and you have the necessary work permits if required for employment in South Africa.
                                        </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>
        // Candidate type selection functionality
        document.addEventListener('DOMContentLoaded', function() {
            const candidateTypeCards = document.querySelectorAll('.candidate-type-card');
            const candidateTypeRadios = document.querySelectorAll('input[name="candidate_type"]');
            const internalCandidateSection = document.getElementById('internalCandidateSection');
            const employeeCodeInput = document.getElementById('employee_code');
            const companySelect = document.getElementById('company_id');
            
            // Initialize selection based on current radio button state
            function updateSelection() {
                candidateTypeCards.forEach(card => {
                    card.classList.remove('selected', 'external', 'internal');
                });
                
                const selectedRadio = document.querySelector('input[name="candidate_type"]:checked');
                if (selectedRadio) {
                    const selectedCard = document.querySelector('.candidate-type-card[data-type="' + selectedRadio.value + '"]');
                    if (selectedCard) {
                        selectedCard.classList.add('selected', selectedRadio.value);
                    }
                    
                    // Show/hide internal candidate section
                    if (selectedRadio.value === 'internal') {
                        internalCandidateSection.style.display = 'block';
                        employeeCodeInput.required = true;
                        companySelect.required = true;
                    } else {
                        internalCandidateSection.style.display = 'none';
                        employeeCodeInput.required = false;
                        companySelect.required = false;
                        employeeCodeInput.value = '';
                        companySelect.value = '';
                    }
                }
            }
            
            // Card click handlers
            candidateTypeCards.forEach(card => {
                card.addEventListener('click', function() {
                    const cardType = this.getAttribute('data-type');
                    const radio = document.getElementById(cardType);
                    if (radio) {
                        radio.checked = true;
                        updateSelection();
                    }
                });
            });
            
            // Radio button change handlers
            candidateTypeRadios.forEach(radio => {
                radio.addEventListener('change', updateSelection);
            });
            
            // Initialize on page load
            updateSelection();
        });
        
        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);
        
        // Foreign National Section functionality
        const nationalityRadios = document.querySelectorAll('input[name="is_foreign_national"]');
        const passportSection = document.getElementById('passportSection');
        const passportInput = document.getElementById('passport_number');
        const countrySelect = document.getElementById('country');
        const saIdSection = document.getElementById('saIdSection');
        const saIdInput = document.getElementById('sa_id_number');
        
        function updateForeignNationalSection() {
            const selectedValue = document.querySelector('input[name="is_foreign_national"]:checked')?.value;
            
            if (selectedValue === 'yes') {
                // Show passport section, hide SA ID section
                passportSection.style.display = 'block';
                saIdSection.style.display = 'none';
                passportInput.required = true;
                countrySelect.required = true;
                saIdInput.required = false;
                saIdInput.value = '';
            } else {
                // Show SA ID section, hide passport section
                saIdSection.style.display = 'block';
                passportSection.style.display = 'none';
                saIdInput.required = true;
                passportInput.required = false;
                countrySelect.required = false;
                passportInput.value = '';
                countrySelect.value = '';
            }
        }
        
        // Add event listeners for foreign national selection
        nationalityRadios.forEach(radio => {
            radio.addEventListener('change', updateForeignNationalSection);
        });
        
        // Initialize foreign national section on page load
        updateForeignNationalSection();
        
        // SA ID Number validation
        if (saIdInput) {
            saIdInput.addEventListener('input', function() {
                // Remove non-digits
                this.value = this.value.replace(/\D/g, '');
                
                // Validate format
                const feedback = document.getElementById('saIdFeedback');
                if (this.value.length === 13) {
                    if (feedback) {
                        feedback.innerHTML = '<span class="text-success"><i class="fas fa-check me-1"></i>Valid format</span>';
                    }
                } else if (this.value.length > 0) {
                    if (feedback) {
                        feedback.innerHTML = '<span class="text-danger"><i class="fas fa-times me-1"></i>Must be exactly 13 digits</span>';
                    }
                } else {
                    if (feedback) feedback.innerHTML = '';
                }
            });
        }
    </script>
</body>
</html>