<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="d-flex align-items-center mb-3">
    <a href="<?= base_url('admin/jobs') ?>" class="btn btn-li-ghost btn-sm me-2"><i class="bi bi-arrow-left"></i></a>
    <h5 class="mb-0"><?= isset($jobId) ? 'Edit Job' : 'Post a New Job' ?></h5>
</div>

<div class="li-card">
    <div class="li-card-body">
        <form id="jobForm">
            <div class="row g-3">
                <div class="col-12">
                    <label class="form-label fw-semibold">Job Title</label>
                    <input type="text" class="form-control" name="title" required>
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Description</label>
                    <textarea class="form-control" name="description" rows="6" required minlength="50" placeholder="Describe the role, responsibilities, and what makes it exciting..."></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Department</label>
                    <input type="text" class="form-control" name="department">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Location</label>
                    <input type="text" class="form-control" name="location" placeholder="e.g. Lahore, Pakistan">
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Employment Type</label>
                    <select class="form-select" name="employment_type">
                        <option value="full_time">Full-time</option>
                        <option value="part_time">Part-time</option>
                        <option value="contract">Contract</option>
                        <option value="internship">Internship</option>
                        <option value="freelance">Freelance</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Experience Level</label>
                    <select class="form-select" name="experience_level">
                        <option value="entry">Entry</option>
                        <option value="mid" selected>Mid</option>
                        <option value="senior">Senior</option>
                        <option value="lead">Lead</option>
                        <option value="executive">Executive</option>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="form-label fw-semibold">Education</label>
                    <input type="text" class="form-control" name="education_requirement" placeholder="e.g. Bachelor's">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Salary Min (PKR)</label>
                    <input type="number" class="form-control" name="salary_min">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Salary Max (PKR)</label>
                    <input type="number" class="form-control" name="salary_max">
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Required Skills</label>
                    <input type="text" class="form-control" name="skills_input" placeholder="Comma-separated, e.g. PHP, Laravel, MySQL">
                </div>
                <div class="col-12">
                    <label class="form-label fw-semibold">Benefits</label>
                    <textarea class="form-control" name="benefits" rows="2"></textarea>
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">City</label>
                    <input type="text" class="form-control" name="city">
                </div>
                <div class="col-md-6">
                    <label class="form-label fw-semibold">Country</label>
                    <input type="text" class="form-control" name="country">
                </div>
                <div class="col-12 d-flex gap-4 flex-wrap">
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_remote" id="isRemote">
                        <label class="form-check-label" for="isRemote">Remote</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_hybrid" id="isHybrid">
                        <label class="form-check-label" for="isHybrid">Hybrid</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_visa_sponsorship" id="isVisaSponsorship">
                        <label class="form-check-label" for="isVisaSponsorship">Visa Sponsorship Available</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_fresh_graduate_ok" id="isFreshGradOk">
                        <label class="form-check-label" for="isFreshGradOk">Fresh Graduate Friendly</label>
                    </div>
                    <div class="form-check">
                        <input class="form-check-input" type="checkbox" name="is_urgent" id="isUrgent">
                        <label class="form-check-label" for="isUrgent">Urgent Hiring</label>
                    </div>
                </div>
            </div>

            <hr class="my-4">
            <div class="d-flex justify-content-between">
                <a href="<?= base_url('admin/jobs') ?>" class="btn btn-li-ghost">Cancel</a>
                <div class="d-flex gap-2">
                    <button type="button" id="saveDraftBtn" class="btn btn-li-outline">Save as Draft</button>
                    <button type="button" id="publishBtn" class="btn btn-li-primary">Publish Job</button>
                </div>
            </div>
        </form>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
const jobId = <?= isset($jobId) ? (int) $jobId : 'null' ?>;

function collectPayload() {
    const form = document.getElementById('jobForm');
    const fd = new FormData(form);
    const skills = (fd.get('skills_input') || '').split(',').map(s => s.trim()).filter(Boolean);

    return {
        title: fd.get('title'),
        description: fd.get('description'),
        department: fd.get('department') || null,
        location: fd.get('location') || null,
        city: fd.get('city') || null,
        country: fd.get('country') || null,
        employment_type: fd.get('employment_type'),
        experience_level: fd.get('experience_level'),
        education_requirement: fd.get('education_requirement') || null,
        salary_min: fd.get('salary_min') || null,
        salary_max: fd.get('salary_max') || null,
        required_skills: skills,
        benefits: fd.get('benefits') || null,
        is_remote: form.isRemote.checked,
        is_hybrid: form.isHybrid.checked,
        is_visa_sponsorship: form.isVisaSponsorship.checked,
        is_fresh_graduate_ok: form.isFreshGradOk.checked,
        is_urgent: form.isUrgent.checked,
    };
}

async function saveJob(publish) {
    const payload = collectPayload();
    if (!payload.title || payload.description.length < 50) {
        showToast('Title is required and description must be at least 50 characters.', true);
        return;
    }

    try {
        let id = jobId;
        if (id) {
            await apiFetch(`/jobs/${id}`, { method: 'PUT', body: JSON.stringify(payload) });
        } else {
            const res = await apiFetch('/jobs', { method: 'POST', body: JSON.stringify(payload) });
            id = res.data.job.id;
        }
        if (publish) {
            await apiFetch(`/jobs/${id}/publish`, { method: 'POST' });
        }
        showToast(publish ? 'Job published!' : 'Draft saved.');
        setTimeout(() => window.location.href = "<?= base_url('admin/jobs') ?>", 800);
    } catch (e) {
        showToast(e.message, true);
    }
}

document.getElementById('saveDraftBtn').addEventListener('click', () => saveJob(false));
document.getElementById('publishBtn').addEventListener('click', () => saveJob(true));

<?php if (isset($jobId)): ?>
(async () => {
    try {
        const res = await apiFetch('/jobs/mine');
        const job = (res.data || []).find(j => j.id === jobId);
        if (!job) return;
        const form = document.getElementById('jobForm');
        form.title.value = job.title;
        form.description.value = job.description;
        form.department.value = job.department || '';
        form.location.value = job.location || '';
        form.city.value = job.city || '';
        form.country.value = job.country || '';
        form.employment_type.value = job.employment_type;
        form.experience_level.value = job.experience_level;
        form.education_requirement.value = job.education_requirement || '';
        form.salary_min.value = job.salary_min || '';
        form.salary_max.value = job.salary_max || '';
        form.benefits.value = job.benefits || '';
        form.isRemote.checked = !!job.is_remote;
        form.isHybrid.checked = !!job.is_hybrid;
        form.isVisaSponsorship.checked = !!job.is_visa_sponsorship;
        form.isFreshGradOk.checked = !!job.is_fresh_graduate_ok;
        form.isUrgent.checked = !!job.is_urgent;
        if (job.required_skills) {
            const skills = typeof job.required_skills === 'string' ? JSON.parse(job.required_skills) : job.required_skills;
            form.skills_input.value = (skills || []).join(', ');
        }
    } catch (e) { showToast(e.message, true); }
})();
<?php endif; ?>
</script>
<?= $this->endSection() ?>
