<?php
require_once '../config/config.php';
requireLogin('company');

$database = new Database();
$db = $database->getConnection();

$company_id = $_SESSION['company_id'];
$company_user_id = $_SESSION['user_id'];

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

// Get job categories
$stmt = $db->prepare("SELECT * FROM job_categories ORDER BY name");
$stmt->execute();
$categories = $stmt->fetchAll();

// Get available job benefits
$stmt = $db->prepare("SELECT * FROM job_benefits WHERE is_active = 1 ORDER BY display_order, name");
$stmt->execute();
$available_benefits = $stmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = sanitize($_POST['title']);
    $category_id = (int)$_POST['category_id'];
    $description = sanitize($_POST['description']);
    $requirements = sanitize($_POST['requirements']);
    $salary_min = !empty($_POST['salary_min']) ? (float)$_POST['salary_min'] : null;
    $salary_max = !empty($_POST['salary_max']) ? (float)$_POST['salary_max'] : null;
    $location = sanitize($_POST['location']);
    $employment_type = $_POST['employment_type'];
    $experience_level = $_POST['experience_level'];
    $deadline = !empty($_POST['deadline']) ? $_POST['deadline'] : null;
    $status = $_POST['status'];
    $job_type = $_POST['job_type'];
    $work_location_type = $_POST['work_location_type'];
    
    // Validate survey questions
    $survey_questions = $_POST['survey_questions'] ?? [];
    $valid_survey_questions = [];
    
    foreach ($survey_questions as $question_data) {
        if (!empty($question_data['question'])) {
            $valid_survey_questions[] = $question_data;
        }
    }
    
    if (empty($title) || empty($description) || empty($location)) {
        $error = 'Title, description, and location are required.';
    } elseif ($salary_min && $salary_max && $salary_min > $salary_max) {
        $error = 'Minimum salary cannot be greater than maximum salary.';
    } elseif (empty($valid_survey_questions)) {
        $error = 'At least one survey question is required for candidate evaluation.';
    } else {
        try {
            $stmt = $db->prepare("
                INSERT INTO jobs (
                    company_id, company_user_id, category_id, title, description, requirements,
                    salary_min, salary_max, location, work_location_type, employment_type, 
                    experience_level, deadline, status, job_type
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $company_id, $company_user_id,
                $category_id ?: null,
                $title,
                $description,
                $requirements,
                $salary_min,
                $salary_max,
                $location,
                $work_location_type,
                $employment_type,
                $experience_level,
                $deadline,
                $status,
                $job_type
            ]);
            
            $job_id = $db->lastInsertId();
            
            // Handle job benefits selection
            $selected_benefits = $_POST['benefits'] ?? [];
            
            if (!empty($selected_benefits)) {
                $stmt = $db->prepare("INSERT INTO job_benefit_selections (job_id, benefit_id) VALUES (?, ?)");
                foreach ($selected_benefits as $benefit_id) {
                    $benefit_id = (int)$benefit_id;
                    if ($benefit_id > 0) {
                        $stmt->execute([$job_id, $benefit_id]);
                    }
                }
            }
            
            // Handle survey questions with automatic weight distribution
            if (!empty($valid_survey_questions)) {
                $total_questions = count($valid_survey_questions);
                $base_weight = 100.00 / $total_questions; // Equal distribution
                $remaining_weight = 100.00;
                
                foreach ($valid_survey_questions as $index => $question_data) {
                    $question = sanitize($question_data['question']);
                    $question_type = $question_data['type'] ?? 'text';
                    $options = '';
                    $is_required = isset($question_data['required']) ? 1 : 0;
                    
                    // Calculate weight - give any remainder to the last question to ensure exactly 100%
                    if ($index === $total_questions - 1) {
                        $weight = $remaining_weight; // Last question gets remaining weight
                    } else {
                        $weight = round($base_weight, 2);
                        $remaining_weight -= $weight;
                    }
                    
                    // Handle options for select/radio/checkbox
                    if (in_array($question_type, ['select', 'radio', 'checkbox']) && !empty($question_data['options'])) {
                        $options = json_encode(array_filter(array_map('trim', explode("\n", $question_data['options']))));
                    }
                    
                    $stmt = $db->prepare("
                        INSERT INTO job_survey_questions (job_id, question, question_type, options, is_required, question_order, weight)
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                    ");
                    $stmt->execute([$job_id, $question, $question_type, $options, $is_required, $index + 1, $weight]);
                }
            }
            
            // Send notifications to interested candidates if job status is active
            if ($status === 'active' && $category_id) {
                try {
                    require_once '../includes/notification_system_smtp.php';
                    $notificationSystem = new NotificationSystemSMTP($db);
                    $notificationSystem->notifyNewJobPosting($job_id);
                } catch (Exception $e) {
                    error_log("Error sending new job notifications: " . $e->getMessage());
                    // Don't fail the job posting if notifications fail
                }
            }
            
            $success = 'Job posted successfully with survey questions!' . 
                      ($status === 'active' && $category_id ? ' Interested candidates have been notified via email.' : '');
            
            // Clear form data on success
            $_POST = [];
            
        } catch (PDOException $e) {
            $error = 'Error posting job. 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>Post New Job - <?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>
    <!-- Navigation -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container-fluid">
            <a class="navbar-brand" href="../index.php">
                <i class="fas fa-briefcase me-2"></i><?php echo SITE_NAME; ?>
            </a>
            
            <div class="navbar-nav ms-auto">
                <span class="navbar-text me-3">
                    Welcome, <?php echo htmlspecialchars($_SESSION['company_name']); ?>
                </span>
                <a class="nav-link" href="../auth/logout.php">
                    <i class="fas fa-sign-out-alt me-1"></i>Logout
                </a>
            </div>
        </div>
    </nav>

    <div class="container-fluid">
        <div class="row">
            <!-- Sidebar -->
            <nav class="col-md-3 col-lg-2 sidebar">
                <div class="position-sticky">
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="dashboard.php">
                                <i class="fas fa-tachometer-alt me-2"></i>Dashboard
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-building me-2"></i>Company Profile
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="post-job.php">
                                <i class="fas fa-plus-circle me-2"></i>Post New Job
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="applications.php">
                                <i class="fas fa-file-alt me-2"></i>Applications
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="interviews.php">
                                <i class="fas fa-calendar-alt me-2"></i>Interviews
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="change-password.php">
                                <i class="fas fa-lock me-2"></i>Change Password
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- Main Content -->
            <main class="col-md-9 col-lg-10 px-md-4">
                <div class="py-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h1 class="h2">
                            <i class="fas fa-plus-circle me-2"></i>Post New Job
                        </h1>
                        <a href="jobs.php" class="btn btn-outline-secondary">
                            <i class="fas fa-arrow-left me-1"></i>Back to Jobs
                        </a>
                    </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="jobs.php" class="btn btn-success btn-sm me-2">View All Jobs</a>
                                <a href="post-job.php" class="btn btn-outline-success btn-sm">Post Another Job</a>
                            </div>
                        </div>
                    <?php endif; ?>

                    <div class="card">
                        <div class="card-body">
                            <form method="POST">
                                <div class="row">
                                    <div class="col-md-8 mb-3">
                                        <label for="title" class="form-label">Job Title *</label>
                                        <input type="text" class="form-control" id="title" name="title" 
                                               value="<?php echo isset($_POST['title']) ? htmlspecialchars($_POST['title']) : ''; ?>" 
                                               placeholder="e.g. Senior Software Developer" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="category_id" class="form-label">Category</label>
                                        <select class="form-select" id="category_id" name="category_id">
                                            <option value="">Select Category</option>
                                            <?php foreach ($categories as $category): ?>
                                                <option value="<?php echo $category['id']; ?>" 
                                                        <?php echo (isset($_POST['category_id']) && $_POST['category_id'] == $category['id']) ? 'selected' : ''; ?>>
                                                    <?php echo htmlspecialchars($category['name']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="employment_type" class="form-label">Employment Type</label>
                                        <select class="form-select" id="employment_type" name="employment_type">
                                            <option value="full-time" <?php echo (isset($_POST['employment_type']) && $_POST['employment_type'] === 'full-time') ? 'selected' : ''; ?>>Full-time</option>
                                            <option value="part-time" <?php echo (isset($_POST['employment_type']) && $_POST['employment_type'] === 'part-time') ? 'selected' : ''; ?>>Part-time</option>
                                            <option value="contract" <?php echo (isset($_POST['employment_type']) && $_POST['employment_type'] === 'contract') ? 'selected' : ''; ?>>Contract</option>
                                            <option value="internship" <?php echo (isset($_POST['employment_type']) && $_POST['employment_type'] === 'internship') ? 'selected' : ''; ?>>Internship</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="experience_level" class="form-label">Experience Level</label>
                                        <select class="form-select" id="experience_level" name="experience_level">
                                            <option value="entry" <?php echo (isset($_POST['experience_level']) && $_POST['experience_level'] === 'entry') ? 'selected' : ''; ?>>Entry Level</option>
                                            <option value="mid" <?php echo (isset($_POST['experience_level']) && $_POST['experience_level'] === 'mid') ? 'selected' : ''; ?>>Mid Level</option>
                                            <option value="senior" <?php echo (isset($_POST['experience_level']) && $_POST['experience_level'] === 'senior') ? 'selected' : ''; ?>>Senior Level</option>
                                            <option value="executive" <?php echo (isset($_POST['experience_level']) && $_POST['experience_level'] === 'executive') ? 'selected' : ''; ?>>Executive</option>
                                        </select>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="job_type" class="form-label">Job Type *</label>
                                        <select class="form-select" id="job_type" name="job_type" required>
                                            <option value="both" <?php echo (!isset($_POST['job_type']) || $_POST['job_type'] === 'both') ? 'selected' : ''; ?>>All Candidates</option>
                                            <option value="internal" <?php echo (isset($_POST['job_type']) && $_POST['job_type'] === 'internal') ? 'selected' : ''; ?>>Internal Only</option>
                                            <option value="external" <?php echo (isset($_POST['job_type']) && $_POST['job_type'] === 'external') ? 'selected' : ''; ?>>External Only</option>
                                        </select>
                                        <div class="form-text">
                                            <small>
                                                <strong>Internal:</strong> Only current employees can apply<br>
                                                <strong>External:</strong> Only external candidates can apply<br>
                                                <strong>All:</strong> Both internal and external candidates can apply
                                            </small>
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="location" class="form-label">Location *</label>
                                        <input type="text" class="form-control" id="location" name="location" 
                                               value="<?php echo isset($_POST['location']) ? htmlspecialchars($_POST['location']) : ''; ?>" 
                                               placeholder="e.g. New York, NY" required>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="work_location_type" class="form-label">Work Location *</label>
                                        <select class="form-select" id="work_location_type" name="work_location_type" required>
                                            <option value="office" <?php echo (!isset($_POST['work_location_type']) || $_POST['work_location_type'] === 'office') ? 'selected' : ''; ?>>
                                                Office-based
                                            </option>
                                            <option value="remote" <?php echo (isset($_POST['work_location_type']) && $_POST['work_location_type'] === 'remote') ? 'selected' : ''; ?>>
                                                Work from Home
                                            </option>
                                            <option value="hybrid" <?php echo (isset($_POST['work_location_type']) && $_POST['work_location_type'] === 'hybrid') ? 'selected' : ''; ?>>
                                                Hybrid
                                            </option>
                                        </select>
                                        <div class="form-text">
                                            <small>
                                                <strong>Office:</strong> Full-time office presence<br>
                                                <strong>Remote:</strong> Work from home/anywhere<br>
                                                <strong>Hybrid:</strong> Mix of office and remote work
                                            </small>
                                        </div>
                                    </div>
                                    <div class="col-md-4 mb-3">
                                        <label for="deadline" class="form-label">Application Deadline</label>
                                        <input type="date" class="form-control" id="deadline" name="deadline" 
                                               value="<?php echo isset($_POST['deadline']) ? $_POST['deadline'] : ''; ?>" 
                                               min="<?php echo date('Y-m-d'); ?>">
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="salary_min" class="form-label">Minimum Salary (Optional)</label>
                                        <div class="input-group">
                                            <span class="input-group-text">R</span>
                                            <input type="number" class="form-control" id="salary_min" name="salary_min" 
                                                   value="<?php echo isset($_POST['salary_min']) ? $_POST['salary_min'] : ''; ?>" 
                                                   placeholder="300000" min="0" step="5000">
                                        </div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label for="salary_max" class="form-label">Maximum Salary (Optional)</label>
                                        <div class="input-group">
                                            <span class="input-group-text">R</span>
                                            <input type="number" class="form-control" id="salary_max" name="salary_max" 
                                                   value="<?php echo isset($_POST['salary_max']) ? $_POST['salary_max'] : ''; ?>" 
                                                   placeholder="500000" min="0" step="5000">
                                        </div>
                                    </div>
                                </div>

                                <div class="mb-3">
                                    <label for="description" class="form-label">Job Description *</label>
                                    <textarea class="form-control" id="description" name="description" rows="6" 
                                              placeholder="Describe the role, responsibilities, and what you're looking for..." required><?php echo isset($_POST['description']) ? htmlspecialchars($_POST['description']) : ''; ?></textarea>
                                </div>

                                <div class="mb-3">
                                    <label for="requirements" class="form-label">Requirements & Qualifications</label>
                                    <textarea class="form-control" id="requirements" name="requirements" rows="5" 
                                              placeholder="List the required skills, experience, education, etc."><?php echo isset($_POST['requirements']) ? htmlspecialchars($_POST['requirements']) : ''; ?></textarea>
                                </div>

                                <!-- Job Benefits Section -->
                                <div class="mb-4">
                                    <label class="form-label h5">Job Benefits</label>
                                    <p class="text-muted small mb-3">Select all benefits that apply to this position. These will be displayed to candidates.</p>
                                    
                                    <div class="row">
                                        <?php 
                                        $selected_benefits = $_POST['benefits'] ?? [];
                                        foreach ($available_benefits as $index => $benefit): 
                                        ?>
                                            <div class="col-md-4 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" 
                                                           name="benefits[]" 
                                                           value="<?php echo $benefit['id']; ?>" 
                                                           id="benefit_<?php echo $benefit['id']; ?>"
                                                           <?php echo in_array($benefit['id'], $selected_benefits) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="benefit_<?php echo $benefit['id']; ?>">
                                                        <i class="<?php echo $benefit['icon']; ?> me-2 text-primary"></i>
                                                        <?php echo htmlspecialchars($benefit['name']); ?>
                                                    </label>
                                                </div>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                    
                                    <div class="mt-3">
                                        <button type="button" class="btn btn-outline-secondary btn-sm" id="selectAllBenefits">
                                            <i class="fas fa-check-double me-1"></i>Select All
                                        </button>
                                        <button type="button" class="btn btn-outline-secondary btn-sm ms-2" id="clearAllBenefits">
                                            <i class="fas fa-times me-1"></i>Clear All
                                        </button>
                                        <span class="text-muted ms-3 small">
                                            <span id="selectedBenefitsCount">0</span> benefits selected
                                        </span>
                                    </div>
                                </div>

                                <!-- Survey Questions Section -->
                                <div class="mb-4">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <div>
                                            <label class="form-label h5">Survey Questions *</label>
                                            <div id="weightDisplay" class="badge bg-info text-white ms-2">
                                                Total Weight: <span id="totalWeight">0</span>%
                                            </div>
                                        </div>
                                        <button type="button" class="btn btn-outline-primary btn-sm" id="addSurveyQuestion">
                                            <i class="fas fa-plus me-1"></i>Add Question
                                        </button>
                                    </div>
                                    <div class="alert alert-info small">
                                        <i class="fas fa-info-circle me-2"></i>
                                        <strong>Required:</strong> Each job must have at least one survey question for candidate evaluation. 
                                        Weights are automatically distributed equally across all questions to total 100%.
                                    </div>
                                    
                                    <div id="surveyQuestionsContainer">
                                        <!-- Survey questions will be added here dynamically -->
                                    </div>
                                    
                                    <div id="noQuestionsAlert" class="alert alert-warning" style="display: none;">
                                        <i class="fas fa-exclamation-triangle me-2"></i>
                                        At least one survey question is required. Click "Add Question" to get started.
                                    </div>
                                </div>

                                <div class="mb-4">
                                    <label for="status" class="form-label">Status</label>
                                    <select class="form-select" id="status" name="status">
                                        <option value="active" <?php echo (!isset($_POST['status']) || $_POST['status'] === 'active') ? 'selected' : ''; ?>>Active (Visible to candidates)</option>
                                        <option value="draft" <?php echo (isset($_POST['status']) && $_POST['status'] === 'draft') ? 'selected' : ''; ?>>Draft (Save for later)</option>
                                    </select>
                                </div>

                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>Post Job
                                    </button>
                                    <a href="jobs.php" class="btn btn-outline-secondary">Cancel</a>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            let questionCounter = 0;
            
            // Add survey question functionality
            document.getElementById('addSurveyQuestion').addEventListener('click', function() {
                addSurveyQuestion();
            });
            
            function addSurveyQuestion(questionData = null) {
                const container = document.getElementById('surveyQuestionsContainer');
                const questionDiv = document.createElement('div');
                questionDiv.className = 'survey-question-item border rounded p-3 mb-3';
                questionDiv.dataset.questionIndex = questionCounter;
                
                questionDiv.innerHTML = `
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <div>
                            <h6 class="mb-0">Question ${questionCounter + 1}</h6>
                            <small class="text-muted">Weight: <span class="question-weight">0</span>%</small>
                        </div>
                        <button type="button" class="btn btn-outline-danger btn-sm remove-question">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                    
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <label class="form-label">Question Text *</label>
                            <input type="text" class="form-control" 
                                   name="survey_questions[${questionCounter}][question]" 
                                   placeholder="Enter your question here..." 
                                   value="${questionData ? questionData.question : ''}" required>
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Question Type</label>
                            <select class="form-select question-type-select" 
                                    name="survey_questions[${questionCounter}][type]">
                                <option value="text" ${questionData && questionData.type === 'text' ? 'selected' : ''}>Short Text</option>
                                <option value="textarea" ${questionData && questionData.type === 'textarea' ? 'selected' : ''}>Long Text</option>
                                <option value="select" ${questionData && questionData.type === 'select' ? 'selected' : ''}>Dropdown</option>
                                <option value="radio" ${questionData && questionData.type === 'radio' ? 'selected' : ''}>Multiple Choice</option>
                                <option value="checkbox" ${questionData && questionData.type === 'checkbox' ? 'selected' : ''}>Checkboxes</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="options-container" style="display: none;">
                        <label class="form-label">Options (one per line)</label>
                        <textarea class="form-control" 
                                  name="survey_questions[${questionCounter}][options]" 
                                  rows="3" 
                                  placeholder="Option 1\nOption 2\nOption 3">${questionData && questionData.options ? questionData.options.join('\n') : ''}</textarea>
                    </div>
                    
                    <div class="form-check mt-2">
                        <input class="form-check-input" type="checkbox" 
                               name="survey_questions[${questionCounter}][required]" 
                               id="required_${questionCounter}" 
                               ${questionData && questionData.required ? 'checked' : ''}>
                        <label class="form-check-label" for="required_${questionCounter}">
                            This question is required
                        </label>
                    </div>
                `;
                
                container.appendChild(questionDiv);
                
                // Add event listeners for the new question
                const typeSelect = questionDiv.querySelector('.question-type-select');
                const optionsContainer = questionDiv.querySelector('.options-container');
                
                // Show/hide options based on question type
                function toggleOptions() {
                    const selectedType = typeSelect.value;
                    if (['select', 'radio', 'checkbox'].includes(selectedType)) {
                        optionsContainer.style.display = 'block';
                    } else {
                        optionsContainer.style.display = 'none';
                    }
                }
                
                typeSelect.addEventListener('change', toggleOptions);
                toggleOptions(); // Initial check
                
                // Remove question functionality
                questionDiv.querySelector('.remove-question').addEventListener('click', function() {
                    questionDiv.remove();
                    updateQuestionNumbers();
                });
                
                questionCounter++;
                updateQuestionNumbers();
            }
            
            function updateQuestionNumbers() {
                const questions = document.querySelectorAll('.survey-question-item');
                const totalQuestions = questions.length;
                
                // Show/hide no questions alert
                const noQuestionsAlert = document.getElementById('noQuestionsAlert');
                if (totalQuestions === 0) {
                    noQuestionsAlert.style.display = 'block';
                } else {
                    noQuestionsAlert.style.display = 'none';
                }
                
                // Calculate and display weights
                if (totalQuestions > 0) {
                    const baseWeight = 100 / totalQuestions;
                    let remainingWeight = 100;
                    
                    questions.forEach((question, index) => {
                        const header = question.querySelector('h6');
                        const weightSpan = question.querySelector('.question-weight');
                        
                        // Update question number
                        header.textContent = `Question ${index + 1}`;
                        
                        // Calculate weight - give any remainder to the last question
                        let weight;
                        if (index === totalQuestions - 1) {
                            weight = remainingWeight; // Last question gets remaining weight
                        } else {
                            weight = Math.round(baseWeight * 100) / 100; // Round to 2 decimal places
                            remainingWeight -= weight;
                        }
                        
                        weightSpan.textContent = weight.toFixed(2);
                    });
                    
                    // Update total weight display
                    document.getElementById('totalWeight').textContent = '100.00';
                } else {
                    document.getElementById('totalWeight').textContent = '0.00';
                }
            }
            
            // Initialize with at least one question
            addSurveyQuestion();
            
            // Benefits selection functionality
            function updateBenefitsCount() {
                const checkedBenefits = document.querySelectorAll('input[name="benefits[]"]:checked');
                document.getElementById('selectedBenefitsCount').textContent = checkedBenefits.length;
            }
            
            // Select all benefits
            document.getElementById('selectAllBenefits').addEventListener('click', function() {
                const benefitCheckboxes = document.querySelectorAll('input[name="benefits[]"]');
                benefitCheckboxes.forEach(checkbox => {
                    checkbox.checked = true;
                });
                updateBenefitsCount();
            });
            
            // Clear all benefits
            document.getElementById('clearAllBenefits').addEventListener('click', function() {
                const benefitCheckboxes = document.querySelectorAll('input[name="benefits[]"]');
                benefitCheckboxes.forEach(checkbox => {
                    checkbox.checked = false;
                });
                updateBenefitsCount();
            });
            
            // Update count when individual checkboxes change
            document.querySelectorAll('input[name="benefits[]"]').forEach(checkbox => {
                checkbox.addEventListener('change', updateBenefitsCount);
            });
            
            // Initialize benefits count
            updateBenefitsCount();
        });
    </script>
</body>
</html>