<?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'];
$job_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

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

if (!$job_id) {
    redirect('jobs.php');
}

// Get job details and verify ownership
$stmt = $db->prepare("
    SELECT * FROM jobs 
    WHERE id = ? AND company_id = ?
");
$stmt->execute([$job_id, $company_id]);
$job = $stmt->fetch();

if (!$job) {
    redirect('jobs.php');
}

// Get existing survey questions
$stmt = $db->prepare("SELECT * FROM job_survey_questions WHERE job_id = ? ORDER BY question_order ASC");
$stmt->execute([$job_id]);
$existing_survey_questions = $stmt->fetchAll();

// 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'];
    $deadline = !empty($_POST['deadline']) ? $_POST['deadline'] : null;
    $status = $_POST['status'];
    
    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 {
            // Update job
            $stmt = $db->prepare("
                UPDATE jobs SET
                    category_id = ?, title = ?, description = ?, requirements = ?,
                    salary_min = ?, salary_max = ?, location = ?, employment_type = ?, 
                    experience_level = ?, deadline = ?, status = ?
                WHERE id = ? AND company_id = ?
            ");
            
            $stmt->execute([
                $category_id ?: null,
                $title,
                $description,
                $requirements,
                $salary_min,
                $salary_max,
                $location,
                $employment_type,
                $experience_level,
                $deadline,
                $status,
                $job_id,
                $company_id
            ]);
            
            // Delete existing survey questions
            $stmt = $db->prepare("DELETE FROM job_survey_questions WHERE job_id = ?");
            $stmt->execute([$job_id]);
            
            // Handle survey questions
            if (!empty($_POST['survey_questions'])) {
                foreach ($_POST['survey_questions'] as $index => $question_data) {
                    if (!empty($question_data['question'])) {
                        $question = sanitize($question_data['question']);
                        $question_type = $question_data['type'] ?? 'text';
                        $options = '';
                        $is_required = isset($question_data['required']) ? 1 : 0;
                        
                        // 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)
                            VALUES (?, ?, ?, ?, ?, ?)
                        ");
                        $stmt->execute([$job_id, $question, $question_type, $options, $is_required, $index + 1]);
                    }
                }
            }
            
            // Check if job status changed from draft/inactive to active
            $should_notify = false;
            if ($status === 'active' && $job['status'] !== 'active' && $category_id) {
                $should_notify = true;
            }
            
            // Send notifications to interested candidates if job became active
            if ($should_notify) {
                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 update if notifications fail
                }
            }
            
            $success = 'Job updated successfully!' . 
                      ($should_notify ? ' Interested candidates have been notified via email.' : '');
            
            // Refresh job data
            $stmt = $db->prepare("SELECT * FROM jobs WHERE id = ? AND company_id = ?");
            $stmt->execute([$job_id, $company_id]);
            $job = $stmt->fetch();
            
        } catch (PDOException $e) {
            $error = 'Error updating 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>Edit 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 active" href="jobs.php">
                                <i class="fas fa-briefcase me-2"></i>Manage Jobs
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" 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-edit me-2"></i>Edit Job: <?php echo htmlspecialchars($job['title']); ?>
                        </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 New 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 htmlspecialchars($job['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 ($job['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 ($job['employment_type'] === 'full-time') ? 'selected' : ''; ?>>Full-time</option>
                                            <option value="part-time" <?php echo ($job['employment_type'] === 'part-time') ? 'selected' : ''; ?>>Part-time</option>
                                            <option value="contract" <?php echo ($job['employment_type'] === 'contract') ? 'selected' : ''; ?>>Contract</option>
                                            <option value="internship" <?php echo ($job['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 ($job['experience_level'] === 'entry') ? 'selected' : ''; ?>>Entry Level</option>
                                            <option value="mid" <?php echo ($job['experience_level'] === 'mid') ? 'selected' : ''; ?>>Mid Level</option>
                                            <option value="senior" <?php echo ($job['experience_level'] === 'senior') ? 'selected' : ''; ?>>Senior Level</option>
                                            <option value="executive" <?php echo ($job['experience_level'] === 'executive') ? 'selected' : ''; ?>>Executive</option>
                                        </select>
                                    </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 htmlspecialchars($job['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 $job['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 $job['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 $job['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 htmlspecialchars($job['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 htmlspecialchars($job['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>
                                        <button type="button" class="btn btn-outline-primary btn-sm" id="addSurveyQuestion">
                                            <i class="fas fa-plus me-1"></i>Add Question
                                        </button>
                                    </div>
                                    <p class="text-muted small mb-3">Create custom questions for candidates to answer when applying for this position.</p>
                                    
                                    <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 ($job['status'] === 'active') ? 'selected' : ''; ?>>Active (Visible to candidates)</option>
                                        <option value="draft" <?php echo ($job['status'] === 'draft') ? 'selected' : ''; ?>>Draft (Save for later)</option>
                                        <option value="paused" <?php echo ($job['status'] === 'paused') ? 'selected' : ''; ?>>Paused (Not accepting applications)</option>
                                        <option value="closed" <?php echo ($job['status'] === 'closed') ? 'selected' : ''; ?>>Closed</option>
                                    </select>
                                </div>

                                <div class="d-flex gap-2">
                                    <button type="submit" class="btn btn-primary">
                                        <i class="fas fa-save me-2"></i>Update 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;
            
            // Load existing survey questions
            const existingQuestions = <?php echo json_encode($existing_survey_questions); ?>;
            
            // Add existing questions to the form
            existingQuestions.forEach(function(questionData) {
                const options = questionData.options ? JSON.parse(questionData.options) : [];
                addSurveyQuestion({
                    question: questionData.question,
                    type: questionData.question_type,
                    options: options,
                    required: questionData.is_required == 1
                });
            });
            
            // 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">
                        <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-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');
                questions.forEach((question, index) => {
                    const header = question.querySelector('h6');
                    header.textContent = `Question ${index + 1}`;
                });
            }
        });
    </script>
</body>
</html>