<?= $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">Bulk Job Posting</h5>
</div>

<div class="li-card mb-3" id="planStatusCard">
    <div class="li-card-body">
        <div id="planStatusBody">Loading your current plan limits...</div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body">
        <h6 class="mb-2">How it works</h6>
        <ol class="text-muted small mb-3">
            <li>Download the CSV template below</li>
            <li>Fill in one row per job (up to 200 jobs per upload)</li>
            <li>Set <code>publish</code> to <code>yes</code> to publish immediately, or <code>no</code> to save as drafts you can review and publish individually later</li>
            <li>Upload the completed file</li>
        </ol>
        <a href="<?= base_url('admin/jobs/bulk/template') ?>" class="btn btn-li-outline btn-sm"><i class="bi bi-download me-1"></i>Download CSV Template</a>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-body">
        <h6 class="mb-2">Upload Your CSV</h6>
        <input type="file" id="csvFile" accept=".csv" class="form-control mb-2">
        <button class="btn btn-li-primary" onclick="uploadCsv()" id="uploadBtn"><i class="bi bi-upload me-1"></i>Upload &amp; Create Jobs</button>
        <div id="uploadProgress" class="text-muted small mt-2 d-none">Uploading and processing...</div>
    </div>
</div>

<div id="resultsCard" class="li-card d-none">
    <div class="li-card-header d-flex justify-content-between">
        <span>Results</span>
        <span><span class="li-pill li-pill-green" id="successCount">0 created</span> <span class="li-pill li-pill-yellow" id="dupCount">0 duplicates skipped</span> <span class="li-pill li-pill-red" id="failCount">0 failed</span></span>
    </div>
    <div class="li-card-body">
        <div id="resultsBody"></div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
async function loadPlanStatus() {
    try {
        const res = await apiFetch('/billing/subscription');
        const { plan, usage } = res.data;
        const used = usage?.jobs_posted_used || 0;
        const limit = plan.job_posting_limit;
        const remaining = limit == -1 ? '∞' : Math.max(0, limit - used);

        document.getElementById('planStatusBody').innerHTML = `
            <div class="d-flex justify-content-between align-items-center">
                <div>
                    <strong>${escapeHtml(plan.name)} Plan</strong> —
                    <span class="text-muted">${used} of ${limit == -1 ? 'unlimited' : limit} jobs posted this period</span>
                </div>
                <span class="li-pill li-pill-${remaining === 0 ? 'red' : 'blue'}">${remaining} slot${remaining === 1 ? '' : 's'} remaining</span>
            </div>
            ${remaining === 0 ? '<div class="text-danger small mt-2">You\'ve reached your plan\'s job posting limit. Rows beyond this will fail — contact your platform admin to reset usage or upgrade your plan before uploading a large batch.</div>' : ''}
        `;
    } catch (e) {
        document.getElementById('planStatusBody').innerHTML = '<span class="text-muted small">Could not load plan status.</span>';
    }
}

async function uploadCsv() {
    const fileInput = document.getElementById('csvFile');
    if (!fileInput.files.length) { showToast('Choose a CSV file first.', true); return; }

    const uploadBtn = document.getElementById('uploadBtn');
    const progress = document.getElementById('uploadProgress');
    uploadBtn.disabled = true;
    progress.classList.remove('d-none');

    const fd = new FormData();
    fd.append('csv', fileInput.files[0]);

    try {
        const res = await fetch(`${API_BASE}/jobs/bulk-upload`, { method: 'POST', body: fd, credentials: 'include' });
        const json = await res.json();
        if (!json.success) throw new Error(json.errors?.[0]?.message || 'Upload failed.');

        renderResults(json.data);
        showToast(`${json.data.created.length} job(s) created.`);
    } catch (e) {
        showToast(e.message, true);
    } finally {
        uploadBtn.disabled = false;
        progress.classList.add('d-none');
    }
}

function renderResults(data) {
    document.getElementById('resultsCard').classList.remove('d-none');
    document.getElementById('successCount').textContent = `${data.created.length} created`;
    document.getElementById('dupCount').textContent = `${data.skipped_duplicates.length} duplicates skipped`;
    document.getElementById('failCount').textContent = `${data.failed.length} failed`;

    let html = '';
    if (data.created.length) {
        html += '<h6 class="text-success">Created</h6><ul class="small mb-3">';
        data.created.forEach(c => {
            html += `<li>Row ${c.row}: <strong>${escapeHtml(c.title)}</strong> — <span class="li-pill li-pill-${c.status === 'published' ? 'green' : 'gray'}">${c.status}</span></li>`;
        });
        html += '</ul>';
    }
    if (data.skipped_duplicates.length) {
        html += '<h6 class="text-warning">Skipped — Already Exists</h6><ul class="small mb-3">';
        data.skipped_duplicates.forEach(d => {
            html += `<li>Row ${d.row}: <strong>${escapeHtml(d.title)}</strong> — <span class="text-muted">${escapeHtml(d.note)}</span></li>`;
        });
        html += '</ul>';
    }
    if (data.failed.length) {
        html += '<h6 class="text-danger">Failed</h6><ul class="small mb-0">';
        data.failed.forEach(f => {
            html += `<li>Row ${f.row}: <strong>${escapeHtml(f.title)}</strong> — <span class="text-danger">${escapeHtml(f.error)}</span></li>`;
        });
        html += '</ul>';
    }
    document.getElementById('resultsBody').innerHTML = html;
}

loadPlanStatus();
</script>
<?= $this->endSection() ?>
