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

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'];
    $job_visibility = $_POST['job_visibility'] ?? 'external';
    $deadline = !empty($_POST['deadline']) ? $_POST['deadline'] : null;
    $status = $_POST['status'];
    $remote_work = $_POST['remote_work'] ?? '';
    $benefits = isset($_POST['benefits']) && is_array($_POST['benefits']) ? $_POST['benefits'] : [];
    
    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.';
    } else {
        try {
            // Enhance the description with remote work and benefits information
            $enhanced_description = $description;
            
            // Add remote work information to description for filtering compatibility
            if ($remote_work === 'partial') {
                $enhanced_description .= "\n\nWork Arrangement: This role offers remote/hybrid work options.";
            } elseif ($remote_work === 'full') {
                $enhanced_description .= "\n\nWork Arrangement: This is a fully remote position.";
            }
            
            // Add benefits information to description for filtering compatibility
            if (!empty($benefits)) {
                $benefits_text = implode(', ', array_map(function($benefit) {
                    switch($benefit) {
                        case 'medical_aid': return 'Medical Aid';
                        case 'dental_cover': return 'Dental Cover';
                        case 'provident_fund': return 'Provident Fund';
                        case 'group_life_cover': return 'Group Life Cover';
                        case 'flexible_hours': return 'Flexible Working Hours';
                        case 'annual_bonus': return 'Annual Bonus / 13th Cheque';
                        case 'training_development': return 'Training & Development';
                        case 'transport_allowance': return 'Transport / Travel Allowance';
                        case 'cellphone_allowance': return 'Cellphone Allowance';
                        case 'study_assistance': return 'Study Assistance';
                        case 'wellness_program': return 'Wellness Program';
                        default: return ucwords(str_replace('_', ' ', $benefit));
                    }
                }, $benefits));
                $enhanced_description .= "\n\nBenefits: " . $benefits_text;
            }
            
            $stmt = $db->prepare("
                INSERT INTO jobs (
                    company_id, company_user_id, category_id, title, description, requirements,
                    salary_min, salary_max, location, employment_type, 
                    experience_level, job_visibility, deadline, status
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            ");
            
            $stmt->execute([
                $company_id, $company_user_id,
                $category_id ?: null,
                $title,
                $enhanced_description,
                $requirements,
                $salary_min,
                $salary_max,
                $location,
                $employment_type,
                $experience_level,
                $job_visibility,
                $deadline,
                $status
            ]);
            
            $job_id = $db->lastInsertId();
            
            // Handle survey questions with weight validation
            if (!empty($_POST['survey_questions'])) {
                $total_weight = 0;
                $valid_questions = [];
                
                // First pass: validate questions and calculate total weight
                foreach ($_POST['survey_questions'] as $index => $question_data) {
                    if (!empty($question_data['question'])) {
                        $weight = (float)($question_data['weight'] ?? 0);
                        if ($weight < 1 || $weight > 100) {
                            $error = 'Each question weight must be between 1% and 100%.';
                            break;
                        }
                        $total_weight += $weight;
                        $valid_questions[] = [
                            'index' => $index,
                            'question' => sanitize($question_data['question']),
                            'type' => $question_data['type'] ?? 'text',
                            'weight' => $weight,
                            'options' => $question_data['options'] ?? '',
                            'required' => isset($question_data['required']) ? 1 : 0
                        ];
                    }
                }
                
                // Only validate total weight if there are questions with weights
                if (!$error && count($valid_questions) > 0 && abs($total_weight - 100) > 0.1) {
                    $error = "Question weights must total exactly 100%. Current total: " . number_format($total_weight, 1) . "%";
                }
                
                // Insert questions if validation passed
                if (!$error) {
                    foreach ($valid_questions as $q) {
                        $options = '';
                        if (in_array($q['type'], ['select', 'radio', 'checkbox']) && !empty($q['options'])) {
                            $options = json_encode(array_filter(array_map('trim', explode("\n", $q['options']))));
                        }
                        
                        // Check if weight column exists before trying to insert
                        try {
                            $stmt = $db->prepare("
                                INSERT INTO job_survey_questions (job_id, question, question_type, options, is_required, weight, question_order)
                                VALUES (?, ?, ?, ?, ?, ?, ?)
                            ");
                            $stmt->execute([$job_id, $q['question'], $q['type'], $options, $q['required'], $q['weight'], $q['index'] + 1]);
                        } catch (PDOException $e) {
                            // If weight column doesn't exist, try without it
                            if (strpos($e->getMessage(), 'weight') !== false) {
                                $stmt = $db->prepare("
                                    INSERT INTO job_survey_questions (job_id, question, question_type, options, is_required, question_order)
                                    VALUES (?, ?, ?, ?, ?, ?)
                                ");
                                $stmt->execute([$job_id, $q['question'], $q['type'], $options, $q['required'], $q['index'] + 1]);
                            } else {
                                throw $e; // Re-throw if it's a different error
                            }
                        }
                    }
                }
            }
            
            // Only set success if no errors occurred
            if (!$error) {
                $success = 'Job posted successfully!';
                
                // Send notifications to candidates who previously applied to jobs in the same category
                if ($status === 'active') {
                    try {
                        require_once '../includes/notification_system.php';
                        $database = new Database();
                        $notification_system = new NotificationSystem($database->getConnection());
                        $notification_system->notifyPreviousApplicants($job_id);
                        error_log("Triggered candidate notifications for new job: $job_id");
                    } catch (Exception $e) {
                        error_log("Failed to send job notifications for job $job_id: " . $e->getMessage());
                        // Don't fail the job posting if notifications fail
                    }
                }
                
                // 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-6 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-6 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>

                                <!-- Job Visibility Section -->
                                <div class="card bg-light mb-4">
                                    <div class="card-header">
                                        <h6 class="mb-0">
                                            <i class="fas fa-eye me-2"></i>Job Visibility - Who can see and apply for this job?
                                        </h6>
                                    </div>
                                    <div class="card-body">
                                        <div class="row">
                                            <div class="col-md-4 mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="job_visibility" id="visibility_external" value="external" 
                                                           <?php echo (!isset($_POST['job_visibility']) || $_POST['job_visibility'] === 'external') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="visibility_external">
                                                        <strong>External Only</strong><br>
                                                        <small class="text-muted">Only external candidates can see and apply</small>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="job_visibility" id="visibility_internal" value="internal" 
                                                           <?php echo (isset($_POST['job_visibility']) && $_POST['job_visibility'] === 'internal') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="visibility_internal">
                                                        <strong>Internal Only</strong><br>
                                                        <small class="text-muted">Only your internal employees can see and apply</small>
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-4 mb-3">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="radio" name="job_visibility" id="visibility_both" value="both" 
                                                           <?php echo (isset($_POST['job_visibility']) && $_POST['job_visibility'] === 'both') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="visibility_both">
                                                        <strong>Both</strong><br>
                                                        <small class="text-muted">Both external and internal candidates can apply</small>
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="alert alert-info mb-0">
                                            <i class="fas fa-info-circle me-2"></i>
                                            <strong>Note:</strong> Internal employees must be approved by your company before they can apply for jobs.
                                        </div>
                                    </div>
                                </div>

                                <div class="row">
                                    <div class="col-md-6 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-6 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>

                                <!-- Work From Home Options -->
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="remote_work" class="form-label">Work From Home Options</label>
                                        <select class="form-select" id="remote_work" name="remote_work">
                                            <option value="" <?php echo (!isset($_POST['remote_work']) || $_POST['remote_work'] === '') ? 'selected' : ''; ?>>Office Only</option>
                                            <option value="partial" <?php echo (isset($_POST['remote_work']) && $_POST['remote_work'] === 'partial') ? 'selected' : ''; ?>>Partially Remote/Hybrid</option>
                                            <option value="full" <?php echo (isset($_POST['remote_work']) && $_POST['remote_work'] === 'full') ? 'selected' : ''; ?>>Fully Remote</option>
                                        </select>
                                        <div class="form-text">Specify if this role allows remote work</div>
                                    </div>
                                    <div class="col-md-6 mb-3">
                                        <label class="form-label">Job Benefits</label>
                                        <div class="form-text mb-2">Select the benefits offered with this position</div>
                                        <div class="row">
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="medical_aid" name="benefits[]" value="medical_aid"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('medical_aid', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="medical_aid">
                                                        <i class="fas fa-heartbeat text-danger me-1"></i>Medical Aid
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="dental_cover" name="benefits[]" value="dental_cover"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('dental_cover', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="dental_cover">
                                                        <i class="fas fa-tooth text-info me-1"></i>Dental Cover
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="provident_fund" name="benefits[]" value="provident_fund"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('provident_fund', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="provident_fund">
                                                        <i class="fas fa-piggy-bank text-success me-1"></i>Provident Fund
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="group_life_cover" name="benefits[]" value="group_life_cover"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('group_life_cover', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="group_life_cover">
                                                        <i class="fas fa-shield-alt text-primary me-1"></i>Group Life Cover
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="flexible_hours" name="benefits[]" value="flexible_hours"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('flexible_hours', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="flexible_hours">
                                                        <i class="fas fa-clock text-warning me-1"></i>Flexible Working Hours
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="annual_bonus" name="benefits[]" value="annual_bonus"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('annual_bonus', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="annual_bonus">
                                                        <i class="fas fa-gift text-success me-1"></i>Annual Bonus / 13th Cheque
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="training_development" name="benefits[]" value="training_development"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('training_development', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="training_development">
                                                        <i class="fas fa-graduation-cap text-info me-1"></i>Training & Development
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="transport_allowance" name="benefits[]" value="transport_allowance"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('transport_allowance', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="transport_allowance">
                                                        <i class="fas fa-car text-primary me-1"></i>Transport / Travel Allowance
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="cellphone_allowance" name="benefits[]" value="cellphone_allowance"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('cellphone_allowance', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="cellphone_allowance">
                                                        <i class="fas fa-mobile-alt text-success me-1"></i>Cellphone Allowance
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="study_assistance" name="benefits[]" value="study_assistance"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('study_assistance', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="study_assistance">
                                                        <i class="fas fa-book text-warning me-1"></i>Study Assistance
                                                    </label>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-2">
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="wellness_program" name="benefits[]" value="wellness_program"
                                                           <?php echo (isset($_POST['benefits']) && is_array($_POST['benefits']) && in_array('wellness_program', $_POST['benefits'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="wellness_program">
                                                        <i class="fas fa-spa text-info me-1"></i>Wellness Program
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                    </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>

                                <!-- Survey Questions Section -->
                                <div class="mb-4">
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <label class="form-label h5">Survey Questions (Optional)</label>
                                        <div class="btn-group" role="group">
                                            <button type="button" class="btn btn-outline-primary btn-sm" id="addSurveyQuestion">
                                                <i class="fas fa-plus me-1"></i>Add Question
                                            </button>
                                            <button type="button" class="btn btn-outline-success btn-sm" id="autoAssignWeights" title="Manually redistribute weights evenly across all questions">
                                                <i class="fas fa-refresh me-1"></i>Redistribute Weights
                                            </button>
                                        </div>
                                    </div>
                                    <p class="text-muted small mb-3">
                                        Create custom questions for candidates to answer when applying for this position. 
                                        <strong><i class="fas fa-magic text-primary me-1"></i>Weights are automatically calculated</strong> as you add/remove questions to ensure they always total 100%.
                                    </p>
                                    
                                    <!-- Weight Preview -->
                                    <div id="weightPreview" class="alert alert-info" style="display: none;">
                                        <h6><i class="fas fa-balance-scale me-2"></i>Question Weight Distribution</h6>
                                        <div id="weightBreakdown"></div>
                                        <div id="weightTotal" class="mt-2"></div>
                                        <small class="text-muted">
                                            <i class="fas fa-info-circle me-1"></i>Weights are automatically distributed equally and always total 100%. 
                                            <span class="text-primary">Use "Redistribute Weights" to manually recalculate if needed.</span>
                                        </small>
                                    </div>
                                    
                                    <div id="surveyQuestionsContainer">
                                        <!-- Survey questions will be added here dynamically -->
                                    </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();
            });
            
            // Auto-assign weights functionality
            document.getElementById('autoAssignWeights').addEventListener('click', function() {
                autoAssignWeights();
            });
            
            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">
                        <h6 class="mb-0">Question ${questionCounter + 1}</h6>
                        <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-5">
                            <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 class="col-md-3">
                            <label class="form-label">Weight % *</label>
                            <div class="input-group">
                                <input type="number" class="form-control question-weight-input" 
                                       name="survey_questions[${questionCounter}][weight]" 
                                       placeholder="20"
                                       value="${questionData ? questionData.weight : ''}"
                                       min="1" max="100" step="0.1" 
                                       onchange="updateWeightPreview()" required>
                                <span class="input-group-text">%</span>
                            </div>
                            <small class="text-muted weight-feedback"></small>
                        </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();
                    autoCalculateWeights(); // Auto-recalculate weights when question is removed
                    updateWeightPreview();
                });
                
                questionCounter++;
                updateQuestionNumbers();
                autoCalculateWeights(); // Automatically assign weights when question is added
                updateWeightPreview();
            }
            
            function updateQuestionNumbers() {
                const questions = document.querySelectorAll('.survey-question-item');
                questions.forEach((question, index) => {
                    const header = question.querySelector('h6');
                    header.textContent = `Question ${index + 1}`;
                });
            }
            
            function autoCalculateWeights() {
                const weightInputs = document.querySelectorAll('.question-weight-input');
                
                if (weightInputs.length === 0) {
                    return; // No questions to assign weights to
                }
                
                // Calculate equal weight for each question
                const equalWeight = 100 / weightInputs.length;
                
                // Apply the weight to each input
                weightInputs.forEach((input, index) => {
                    // For exact distribution, handle remainders
                    let assignedWeight;
                    if (index === weightInputs.length - 1) {
                        // Last question gets remainder to ensure total = 100
                        const sumSoFar = equalWeight * (weightInputs.length - 1);
                        assignedWeight = 100 - sumSoFar;
                    } else {
                        assignedWeight = equalWeight;
                    }
                    
                    // Round to 1 decimal place
                    input.value = assignedWeight.toFixed(1);
                    
                    // Add subtle visual feedback for automatic assignment
                    input.style.backgroundColor = '#e3f2fd';
                    input.style.borderColor = '#90caf9';
                    
                    // Remove the styling after a shorter delay
                    setTimeout(() => {
                        input.style.backgroundColor = '';
                        input.style.borderColor = '';
                    }, 1000);
                });
            }
            
            function autoAssignWeights() {
                const weightInputs = document.querySelectorAll('.question-weight-input');
                
                if (weightInputs.length === 0) {
                    alert('Please add some survey questions first before assigning weights.');
                    return;
                }
                
                // Show confirmation dialog for manual assignment
                const confirmMessage = `This will manually redistribute weights evenly across all ${weightInputs.length} questions.\n\nEach question will receive ${(100/weightInputs.length).toFixed(1)}% weight.\n\nDo you want to continue?`;
                
                if (!confirm(confirmMessage)) {
                    return;
                }
                
                // Use the auto-calculate function
                autoCalculateWeights();
                
                // Show success message for manual action
                const autoAssignBtn = document.getElementById('autoAssignWeights');
                const originalHTML = autoAssignBtn.innerHTML;
                autoAssignBtn.innerHTML = '<i class="fas fa-check me-1"></i>Assigned!';
                autoAssignBtn.classList.remove('btn-outline-success');
                autoAssignBtn.classList.add('btn-success');
                
                setTimeout(() => {
                    autoAssignBtn.innerHTML = originalHTML;
                    autoAssignBtn.classList.remove('btn-success');
                    autoAssignBtn.classList.add('btn-outline-success');
                }, 2000);
                
                // Update the weight preview
                updateWeightPreview();
            }
            
            function updateWeightPreview() {
                const weightInputs = document.querySelectorAll('.question-weight-input');
                const preview = document.getElementById('weightPreview');
                const breakdown = document.getElementById('weightBreakdown');
                const totalDiv = document.getElementById('weightTotal');
                
                if (weightInputs.length === 0) {
                    preview.style.display = 'none';
                    return;
                }
                
                let totalWeight = 0;
                const weights = [];
                
                weightInputs.forEach((input, index) => {
                    const weight = parseFloat(input.value) || 0;
                    totalWeight += weight;
                    weights.push({index: index + 1, weight: weight, input: input});
                });
                
                // Update individual feedback
                weights.forEach(item => {
                    const feedbackElement = item.input.parentElement.parentElement.querySelector('.weight-feedback');
                    if (item.weight < 1) {
                        feedbackElement.textContent = 'Min 1%';
                        feedbackElement.className = 'text-danger weight-feedback';
                    } else if (item.weight > 100) {
                        feedbackElement.textContent = 'Max 100%';
                        feedbackElement.className = 'text-danger weight-feedback';
                    } else {
                        feedbackElement.textContent = 'Valid';
                        feedbackElement.className = 'text-success weight-feedback';
                    }
                });
                
                // Build breakdown HTML
                let html = '<div class="row">';
                weights.forEach(item => {
                    const badgeClass = item.weight >= 1 && item.weight <= 100 ? 'bg-primary' : 'bg-danger';
                    html += `
                        <div class="col-md-6 mb-2">
                            <strong>Question ${item.index}:</strong> 
                            <span class="badge ${badgeClass}">${item.weight.toFixed(1)}%</span>
                        </div>
                    `;
                });
                html += '</div>';
                
                breakdown.innerHTML = html;
                
                // Update total
                const isValid = Math.abs(totalWeight - 100) < 0.1; // Allow small floating point errors
                const totalClass = isValid ? 'text-success' : 'text-danger';
                const totalIcon = isValid ? 'fa-check-circle' : 'fa-exclamation-triangle';
                
                totalDiv.innerHTML = `
                    <strong class="${totalClass}">
                        <i class="fas ${totalIcon} me-1"></i>
                        Total: ${totalWeight.toFixed(1)}% ${isValid ? '✓' : '(Must equal 100%)'}
                    </strong>
                `;
                
                preview.style.display = 'block';
            }
            
            // Add global updateWeightPreview function for inline event handlers
            window.updateWeightPreview = updateWeightPreview;
            
        });
    </script>
</body>
</html>