<?php
require_once '../includes/db.php';
require_once '../includes/functions.php';

requireEmployer();

$userId = getUserId();
$pageTitle = 'Post a Job';

$categories = getCategories($pdo);
$locations = getLocations($pdo);

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

$editId = intval($_GET['edit'] ?? 0);
$job = null;

if ($editId) {
    $stmt = $pdo->prepare("SELECT * FROM jobs WHERE id = ? AND employer_id = ?");
    $stmt->execute([$editId, $userId]);
    $job = $stmt->fetch();
    
    if (!$job) {
        flash('error', 'Job not found.');
        header('Location: manage-jobs.php');
        exit;
    }
    
    $pageTitle = 'Edit Job';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $title = trim($_POST['title'] ?? '');
    $description = trim($_POST['description'] ?? '');
    $requirements = trim($_POST['requirements'] ?? '');
    $benefits = trim($_POST['benefits'] ?? '');
    $categoryId = intval($_POST['category_id'] ?? 0);
    $locationId = intval($_POST['location_id'] ?? 0);
    $jobType = $_POST['job_type'] ?? 'full-time';
    $experienceLevel = $_POST['experience_level'] ?? 'entry';
    $educationLevel = $_POST['education_level'] ?? 'any';
    $competitiveSalary = isset($_POST['competitive_salary']);
    $salaryMin = $competitiveSalary ? null : (intval($_POST['salary_min'] ?? 0) ?: null);
    $salaryMax = $competitiveSalary ? null : (intval($_POST['salary_max'] ?? 0) ?: null);
    $salaryCurrency = $_POST['salary_currency'] ?? 'USD';
    $salaryType = $_POST['salary_type'] ?? 'yearly';
    $deadline = $_POST['application_deadline'] ?? null;
    $isOverseas = isset($_POST['is_overseas']) ? 1 : 0;
    
    if (empty($title) || empty($description) || empty($categoryId) || empty($locationId)) {
        $error = 'Please fill in all required fields.';
    } else {
        try {
            if ($editId && $job) {
                $stmt = $pdo->prepare("
                    UPDATE jobs SET 
                        title = ?, description = ?, requirements = ?, benefits = ?,
                        category_id = ?, location_id = ?, job_type = ?, experience_level = ?,
                        salary_min = ?, salary_max = ?, salary_currency = ?, salary_period = ?,
                        application_deadline = ?, is_overseas = ?, 
                        education_level = ?, status = 'pending', updated_at = CURRENT_TIMESTAMP
                    WHERE id = ? AND employer_id = ?
                ");
                $stmt->execute([$title, $description, $requirements, $benefits, $categoryId, $locationId, $jobType, $experienceLevel, $salaryMin, $salaryMax, $salaryCurrency, $salaryType, $deadline ?: null, $isOverseas, $educationLevel, $editId, $userId]);
                
                flash('success', 'Job updated successfully! It will be reviewed by admin.');
                header('Location: manage-jobs.php');
                exit;
            } else {
                $stmt = $pdo->prepare("
                    INSERT INTO jobs (employer_id, title, slug, description, requirements, benefits, category_id, location_id, job_type, experience_level, salary_min, salary_max, salary_currency, salary_period, application_deadline, is_overseas, education_level, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending')
                ");
                $slug = generateSlug($title) . '-' . time();
                $stmt->execute([$userId, $title, $slug, $description, $requirements, $benefits, $categoryId, $locationId, $jobType, $experienceLevel, $salaryMin, $salaryMax, $salaryCurrency, $salaryType, $deadline ?: null, $isOverseas, $educationLevel]);
                
                flash('success', 'Job posted successfully! It will be reviewed by admin before going live.');
                header('Location: manage-jobs.php');
                exit;
            }
        } catch (PDOException $e) {
            $error = 'Failed to save job: ' . $e->getMessage();
        }
    }
}

require_once '../includes/dashboard-header.php';
?>

        <?php if ($error): ?>
            <div class="alert alert-danger"><i class="fas fa-times-circle"></i> <?php echo $error; ?></div>
        <?php endif; ?>
        
        <div class="card">
            <div class="card-body">
                <form method="POST" action="">
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 25px;">
                        <div class="form-group">
                            <label>Job Title *</label>
                            <input type="text" name="title" class="form-control" placeholder="e.g., Senior Software Developer" required value="<?php echo sanitize($job['title'] ?? $_POST['title'] ?? ''); ?>">
                        </div>
                        
                        <div class="form-group">
                            <label>Category *</label>
                            <select name="category_id" class="form-control" required>
                                <option value="">Select Category</option>
                                <?php foreach ($categories as $cat): ?>
                                    <option value="<?php echo $cat['id']; ?>" <?php echo ($job['category_id'] ?? $_POST['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>>
                                        <?php echo sanitize($cat['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Location *</label>
                            <select name="location_id" class="form-control" required>
                                <option value="">Select Location</option>
                                <?php foreach ($locations as $loc): ?>
                                    <option value="<?php echo $loc['id']; ?>" <?php echo ($job['location_id'] ?? $_POST['location_id'] ?? '') == $loc['id'] ? 'selected' : ''; ?>>
                                        <?php echo sanitize($loc['name']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Job Type</label>
                            <select name="job_type" class="form-control">
                                <?php 
                                $jobTypes = ['full-time' => 'Full Time', 'part-time' => 'Part Time', 'contract' => 'Contract', 'internship' => 'Internship', 'remote' => 'Remote'];
                                foreach ($jobTypes as $value => $label): 
                                ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($job['job_type'] ?? $_POST['job_type'] ?? 'full-time') === $value ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Experience Level</label>
                            <select name="experience_level" class="form-control">
                                <?php 
                                $expLevels = ['fresh' => 'Fresh Graduate', 'entry' => '1-3 Years', 'mid' => '3-5 Years', 'senior' => '5+ Years', 'executive' => 'Executive'];
                                foreach ($expLevels as $value => $label): 
                                ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($job['experience_level'] ?? $_POST['experience_level'] ?? 'entry') === $value ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Job Sector</label>
                            <select name="job_sector" class="form-control">
                                <?php 
                                $jobSectors = ['private' => 'Private', 'government' => 'Government', 'semi-government' => 'Semi-Government', 'ngo' => 'NGO'];
                                foreach ($jobSectors as $value => $label): 
                                ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($job['job_sector'] ?? $_POST['job_sector'] ?? 'private') === $value ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                        <div class="form-group">
                            <label>Education Level Required</label>
                            <select name="education_level" class="form-control">
                                <?php 
                                $eduLevels = ['any' => 'Any Education', 'high_school' => 'High School / Matric', 'diploma' => 'Diploma / Intermediate', 'bachelors' => 'Bachelor\'s Degree', 'masters' => 'Master\'s Degree', 'phd' => 'PhD / Doctorate'];
                                foreach ($eduLevels as $value => $label): 
                                ?>
                                    <option value="<?php echo $value; ?>" <?php echo ($job['education_level'] ?? $_POST['education_level'] ?? 'any') === $value ? 'selected' : ''; ?>>
                                        <?php echo $label; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        
                    </div>
                    
                    <div style="background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%); padding: 20px; border-radius: var(--radius); margin: 20px 0 0 0; color: white;">
                        <h3 style="margin-bottom: 15px; font-size: 1.1rem;"><i class="fas fa-door-open"></i> Walk-in Interview</h3>
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="filter-option" style="display: inline-flex; align-items: center; gap: 10px; cursor: pointer; color: white;">
                                <input type="checkbox" name="is_walkin" id="is_walkin" <?php echo (!empty($job['is_walkin']) || isset($_POST['is_walkin'])) ? 'checked' : ''; ?> style="width: 20px; height: 20px;">
                                <span style="font-weight: 500;">This job offers walk-in interviews</span>
                            </label>
                            <p style="font-size: 0.85rem; opacity: 0.9; margin-top: 8px; margin-bottom: 0;">
                                <i class="fas fa-info-circle"></i> Check this if candidates can walk-in for interviews without prior appointment. This will add a prominent badge to attract more applicants.
                            </p>
                        </div>
                    </div>
                    
                    <div style="background: linear-gradient(135deg, #0891b2 0%, #0e7490 100%); padding: 20px; border-radius: var(--radius); margin: 20px 0; color: white;">
                        <h3 style="margin-bottom: 15px; font-size: 1.1rem;"><i class="fas fa-globe-americas"></i> 🌍 International Position</h3>
                        <div class="form-group" style="margin-bottom: 0;">
                            <label class="filter-option" style="display: inline-flex; align-items: center; gap: 10px; cursor: pointer; color: white;">
                                <input type="checkbox" name="is_overseas" id="is_overseas" <?php echo (!empty($job['is_overseas']) || isset($_POST['is_overseas'])) ? 'checked' : ''; ?> style="width: 20px; height: 20px;">
                                <span style="font-weight: 500;">This is an overseas/international position</span>
                            </label>
                            <p style="font-size: 0.85rem; opacity: 0.9; margin-top: 8px; margin-bottom: 0;">
                                <i class="fas fa-info-circle"></i> Check this if the job is based outside your home country (e.g., UAE, Saudi Arabia, Qatar, Singapore, etc.). This will highlight your job in the Overseas Jobs section.
                            </p>
                        </div>
                    </div>
                    
                    <div style="background: var(--gray-50); padding: 20px; border-radius: var(--radius); margin: 20px 0;">
                        <h3 style="margin-bottom: 15px; font-size: 1.1rem;"><i class="fas fa-dollar-sign"></i> Salary Information</h3>
                        
                        <div class="form-group" style="margin-bottom: 15px;">
                            <label class="filter-option" style="display: inline-flex; align-items: center; gap: 8px; cursor: pointer;">
                                <input type="checkbox" name="competitive_salary" id="competitive_salary" <?php echo (empty($job['salary_min']) && empty($job['salary_max']) && $job) ? 'checked' : ''; ?> onchange="toggleSalaryFields()">
                                <span>Competitive salary (hide specific amounts)</span>
                            </label>
                        </div>
                        
                        <div id="salary_fields" style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
                            <div class="form-group">
                                <label>Minimum Salary</label>
                                <input type="number" name="salary_min" id="salary_min" class="form-control" placeholder="e.g., 50000" value="<?php echo $job['salary_min'] ?? $_POST['salary_min'] ?? ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>Maximum Salary</label>
                                <input type="number" name="salary_max" id="salary_max" class="form-control" placeholder="e.g., 80000" value="<?php echo $job['salary_max'] ?? $_POST['salary_max'] ?? ''; ?>">
                            </div>
                            
                            <div class="form-group">
                                <label>Currency</label>
                                <select name="salary_currency" class="form-control">
                                    <?php 
                                    $currencies = [
                                        'USD' => 'USD ($) - US Dollar',
                                        'EUR' => 'EUR (€) - Euro',
                                        'GBP' => 'GBP (£) - British Pound',
                                        'AED' => 'AED (د.إ) - UAE Dirham',
                                        'SAR' => 'SAR (﷼) - Saudi Riyal',
                                        'QAR' => 'QAR (﷼) - Qatari Riyal',
                                        'KWD' => 'KWD (د.ك) - Kuwaiti Dinar',
                                        'BHD' => 'BHD (د.ب) - Bahraini Dinar',
                                        'OMR' => 'OMR (﷼) - Omani Rial',
                                        'SGD' => 'SGD ($) - Singapore Dollar',
                                        'MYR' => 'MYR (RM) - Malaysian Ringgit',
                                        'CAD' => 'CAD ($) - Canadian Dollar',
                                        'AUD' => 'AUD ($) - Australian Dollar',
                                        'PKR' => 'PKR (Rs) - Pakistani Rupee',
                                        'INR' => 'INR (₹) - Indian Rupee'
                                    ];
                                    foreach ($currencies as $code => $label): 
                                    ?>
                                        <option value="<?php echo $code; ?>" <?php echo ($job['salary_currency'] ?? $_POST['salary_currency'] ?? 'USD') === $code ? 'selected' : ''; ?>>
                                            <?php echo $label; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="form-group">
                                <label>Salary Type</label>
                                <select name="salary_type" class="form-control">
                                    <?php 
                                    $salaryTypes = ['yearly' => 'Yearly', 'monthly' => 'Monthly', 'hourly' => 'Hourly'];
                                    foreach ($salaryTypes as $value => $label): 
                                    ?>
                                        <option value="<?php echo $value; ?>" <?php echo ($job['salary_type'] ?? $_POST['salary_type'] ?? 'yearly') === $value ? 'selected' : ''; ?>>
                                            <?php echo $label; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                        </div>
                    </div>
                    
                    <script>
                    function toggleSalaryFields() {
                        const checkbox = document.getElementById('competitive_salary');
                        const fields = document.getElementById('salary_fields');
                        fields.style.opacity = checkbox.checked ? '0.5' : '1';
                        fields.style.pointerEvents = checkbox.checked ? 'none' : 'auto';
                    }
                    document.addEventListener('DOMContentLoaded', toggleSalaryFields);
                    </script>
                    
                    <div class="form-group">
                        <label>Job Description *</label>
                        <textarea name="description" class="form-control" rows="6" placeholder="Describe the job responsibilities and duties..." required><?php echo sanitize($job['description'] ?? $_POST['description'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Requirements</label>
                        <textarea name="requirements" class="form-control" rows="4" placeholder="List the required skills, qualifications, and experience..."><?php echo sanitize($job['requirements'] ?? $_POST['requirements'] ?? ''); ?></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>Benefits</label>
                        <textarea name="benefits" class="form-control" rows="3" placeholder="List the benefits and perks..."><?php echo sanitize($job['benefits'] ?? $_POST['benefits'] ?? ''); ?></textarea>
                    </div>
                    
                    <div style="display: flex; gap: 15px;">
                        <button type="submit" class="btn btn-primary btn-lg">
                            <i class="fas fa-save"></i> <?php echo $editId ? 'Update Job' : 'Post Job'; ?>
                        </button>
                        <a href="manage-jobs.php" class="btn btn-outline btn-lg">Cancel</a>
                    </div>
                </form>
            </div>
        </div>

<?php require_once '../includes/dashboard-footer.php'; ?>
