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

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

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Your Job Postings</h5>
    <div class="d-flex gap-2">
        <a href="<?= base_url('admin/jobs/bulk') ?>" class="btn btn-li-outline"><i class="bi bi-file-earmark-spreadsheet me-1"></i>Bulk Upload</a>
        <a href="<?= base_url('admin/jobs/create') ?>" class="btn btn-li-primary"><i class="bi bi-plus-lg me-1"></i>Post a Job</a>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body py-2">
        <select id="statusFilter" class="form-select form-select-sm" style="width:160px;">
            <option value="">All statuses</option>
            <option value="draft">Draft</option>
            <option value="published">Published</option>
            <option value="closed">Closed</option>
            <option value="expired">Expired</option>
        </select>
    </div>
</div>

<div id="jobsList"></div>
<div id="jobsEmpty" class="li-card li-card-body text-center text-muted d-none py-5">
    <i class="bi bi-briefcase display-4 d-block mb-2 text-muted"></i>
    No jobs posted yet. <a href="<?= base_url('admin/jobs/create') ?>">Post your first job</a>.
</div>

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

<?= $this->section('scripts') ?>
<script>
const BASE = "<?= rtrim(base_url(), '/') ?>";
let allJobs = [];

function statusPill(status) {
    const map = { draft: 'gray', published: 'green', closed: 'red', expired: 'yellow' };
    return `<span class="li-pill li-pill-${map[status] || 'gray'}">${status}</span>`;
}

function renderJobs() {
    const filter = document.getElementById('statusFilter').value;
    const jobs = filter ? allJobs.filter(j => j.status === filter) : allJobs;
    const list = document.getElementById('jobsList');
    const empty = document.getElementById('jobsEmpty');

    if (jobs.length === 0) {
        list.innerHTML = '';
        empty.classList.remove('d-none');
        return;
    }
    empty.classList.add('d-none');

    list.innerHTML = jobs.map(job => `
        <div class="li-card mb-2">
            <div class="li-card-body">
                <div class="d-flex justify-content-between">
                    <div>
                        <a href="${BASE}/admin/jobs/${job.id}" class="fw-bold fs-6 text-decoration-none text-dark">${escapeHtml(job.title)}</a>
                        ${statusPill(job.status)}
                        ${job.is_featured ? '<span class="li-pill li-pill-blue">Featured</span>' : ''}
                        ${job.is_urgent ? '<span class="li-pill li-pill-red">Urgent</span>' : ''}
                        <div class="text-muted small mt-1">
                            <i class="bi bi-geo-alt"></i> ${escapeHtml(job.location || 'Remote')}
                            &nbsp;·&nbsp; ${job.employment_type.replace('_',' ')}
                            &nbsp;·&nbsp; ${job.views_count || 0} views
                            &nbsp;·&nbsp; posted ${timeAgo(job.created_at)}
                        </div>
                    </div>
                    <div class="dropdown">
                        <button class="btn btn-sm btn-li-ghost" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
                        <ul class="dropdown-menu dropdown-menu-end">
                            <li><a class="dropdown-item" href="${BASE}/admin/jobs/${job.id}/edit">Edit</a></li>
                            ${job.status === 'draft' ? `<li><a class="dropdown-item" href="#" onclick="publishJob(${job.id});return false;">Publish</a></li>` : ''}
                            ${job.status === 'published' ? `<li><a class="dropdown-item" href="#" onclick="closeJob(${job.id});return false;">Close</a></li>` : ''}
                            <li><a class="dropdown-item text-danger" href="#" onclick="deleteJob(${job.id});return false;">Delete</a></li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    `).join('');
}

async function loadJobs() {
    try {
        const res = await apiFetch('/jobs/mine');
        allJobs = res.data || [];
        renderJobs();
    } catch (e) {
        showToast(e.message, true);
    }
}

async function publishJob(id) {
    try {
        await apiFetch(`/jobs/${id}/publish`, { method: 'POST' });
        showToast('Job published.');
        loadJobs();
    } catch (e) { showToast(e.message, true); }
}
async function closeJob(id) {
    try {
        await apiFetch(`/jobs/${id}/close`, { method: 'POST' });
        showToast('Job closed.');
        loadJobs();
    } catch (e) { showToast(e.message, true); }
}
async function deleteJob(id) {
    if (!confirm('Delete this job? This cannot be undone.')) return;
    try {
        await apiFetch(`/jobs/${id}`, { method: 'DELETE' });
        showToast('Job deleted.');
        loadJobs();
    } catch (e) { showToast(e.message, true); }
}

document.getElementById('statusFilter').addEventListener('change', renderJobs);
loadJobs();
</script>
<?= $this->endSection() ?>
