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

<?= $this->section('content') ?>
<h5 class="mb-3">Platform Reports</h5>

<div class="row g-3 mb-3">
    <div class="col-md-3"><div class="li-card li-card-body text-center"><div class="li-stat-num" id="revTotal">—</div><div class="li-stat-label">Revenue (30d)</div></div></div>
    <div class="col-md-3"><div class="li-card li-card-body text-center"><div class="li-stat-num" id="agTotal">—</div><div class="li-stat-label">Total Agencies</div></div></div>
    <div class="col-md-3"><div class="li-card li-card-body text-center"><div class="li-stat-num" id="candTotal">—</div><div class="li-stat-label">Candidates</div></div></div>
    <div class="col-md-3"><div class="li-card li-card-body text-center"><div class="li-stat-num" id="jobsTotal">—</div><div class="li-stat-label">Published Jobs</div></div></div>
</div>

<div class="row g-3">
    <div class="col-md-6">
        <div class="li-card mb-3">
            <div class="li-card-header">Agencies by Status</div>
            <div class="li-card-body" id="agStatusBody">Loading...</div>
        </div>
    </div>
    <div class="col-md-6">
        <div class="li-card mb-3">
            <div class="li-card-header">Subscriptions by Plan</div>
            <div class="li-card-body" id="subPlanBody">Loading...</div>
        </div>
    </div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header d-flex justify-content-between">
        <span>Plan Change Requests</span>
        <span class="li-pill li-pill-yellow"><span id="pendingPlanRequestsCount">0</span> pending</span>
    </div>
    <div class="li-card-body" id="planRequestsBody">Loading...</div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header d-flex justify-content-between">
        <span>Hires by Agency</span>
        <span class="li-pill li-pill-green"><span id="totalHiresCount">0</span> total hires</span>
    </div>
    <div class="li-card-body" id="hiresByAgencyBody">Loading...</div>
</div>

<div class="li-card mb-3">
    <div class="li-card-header">Candidate Lookup — Applications &amp; Hire History</div>
    <div class="li-card-body">
        <div class="d-flex gap-2 mb-3">
            <input type="number" id="candidateUserIdInput" class="form-control form-control-sm" style="max-width:200px;" placeholder="Candidate User ID">
            <button class="btn btn-li-primary btn-sm" onclick="loadCandidateReport()">Look Up</button>
        </div>
        <div id="candidateReportBody" class="text-muted small">Enter a candidate's user ID (visible on the Registered Users page) to see their full application and hire history.</div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
async function loadPlatformReports() {
    try {
        const rev = await apiFetch('/admin/reports/revenue');
        const total = (rev.data || []).reduce((sum, r) => sum + Number(r.total_revenue || 0), 0);
        document.getElementById('revTotal').textContent = 'PKR ' + total.toLocaleString();
    } catch (e) {}

    try {
        const ag = await apiFetch('/admin/reports/agencies');
        document.getElementById('agTotal').textContent = ag.data.total;
        document.getElementById('agStatusBody').innerHTML = (ag.data.by_status || []).map(s => `
            <div class="d-flex justify-content-between border-bottom py-1"><span class="text-muted small">${s.status}</span><span class="fw-semibold small">${s.count}</span></div>
        `).join('');
    } catch (e) {}

    try {
        const cand = await apiFetch('/admin/reports/candidates');
        document.getElementById('candTotal').textContent = cand.data.total;
    } catch (e) {}

    try {
        const jobs = await apiFetch('/admin/reports/jobs');
        document.getElementById('jobsTotal').textContent = jobs.data.by_status?.find(s => s.status === 'published')?.count || 0;
    } catch (e) {}

    try {
        const sub = await apiFetch('/admin/reports/subscriptions');
        document.getElementById('subPlanBody').innerHTML = (sub.data.by_plan || []).map(s => `
            <div class="d-flex justify-content-between border-bottom py-1"><span class="text-muted small">${escapeHtml(s.plan_name)}</span><span class="fw-semibold small">${s.count}</span></div>
        `).join('') || '<span class="text-muted small">No active subscriptions yet.</span>';
    } catch (e) {}

    await loadHiresByAgency();
    await loadPlanRequests();
}

async function loadPlanRequests() {
    try {
        const res = await apiFetch('/admin/agencies/plan-requests/pending');
        const requests = res.data.requests || [];
        document.getElementById('pendingPlanRequestsCount').textContent = requests.length;

        if (requests.length === 0) {
            document.getElementById('planRequestsBody').innerHTML = '<p class="text-muted small mb-0">No pending plan change requests.</p>';
            return;
        }

        document.getElementById('planRequestsBody').innerHTML = requests.map(r => `
            <div class="d-flex justify-content-between align-items-center border-bottom py-2">
                <div>
                    <strong>${escapeHtml(r.company_name)}</strong>
                    <div class="text-muted small">
                        ${escapeHtml(r.current_plan_name || 'No plan')} → <strong>${escapeHtml(r.requested_plan_name)}</strong>
                        (PKR ${Number(r.requested_plan_price).toLocaleString()}/mo, ${escapeHtml(r.billing_cycle)})
                    </div>
                    <div class="text-muted small">Requested by ${escapeHtml(r.requested_by_name)} · ${formatDateTime(r.created_at)}</div>
                </div>
                <div class="d-flex gap-2">
                    <button class="btn btn-li-primary btn-sm" onclick="approvePlanRequest(${r.id})">Approve</button>
                    <button class="btn btn-li-outline btn-sm" onclick="rejectPlanRequest(${r.id})">Reject</button>
                </div>
            </div>
        `).join('');
    } catch (e) {
        document.getElementById('planRequestsBody').innerHTML = `<p class="text-danger small mb-0">${e.message}</p>`;
    }
}

async function approvePlanRequest(id) {
    if (!confirm('Approve this plan change? It will take effect immediately.')) return;
    try {
        const res = await apiFetch(`/admin/agencies/plan-requests/${id}/approve`, { method: 'POST' });
        showToast(res.data.message);
        loadPlanRequests();
    } catch (e) { showToast(e.message, true); }
}

async function rejectPlanRequest(id) {
    const note = prompt('Optional note for the agency (why this was declined):');
    if (note === null) return; // cancelled
    try {
        await apiFetch(`/admin/agencies/plan-requests/${id}/reject`, { method: 'POST', body: JSON.stringify({ note }) });
        showToast('Request rejected.');
        loadPlanRequests();
    } catch (e) { showToast(e.message, true); }
}

async function loadHiresByAgency() {
    try {
        const res = await apiFetch('/admin/reports/hires-by-agency');
        const { agencies, total_hires } = res.data;
        document.getElementById('totalHiresCount').textContent = total_hires;

        if (agencies.length === 0) {
            document.getElementById('hiresByAgencyBody').innerHTML = '<p class="text-muted small mb-0">No hires recorded yet.</p>';
            return;
        }

        document.getElementById('hiresByAgencyBody').innerHTML = agencies.map(a => `
            <div class="mb-3">
                <div class="d-flex justify-content-between">
                    <span class="fw-semibold">${escapeHtml(a.company_name)}</span>
                    <span class="li-pill li-pill-green">${a.hire_count} hire${a.hire_count === 1 ? '' : 's'}</span>
                </div>
                <div class="ps-3">
                    ${a.hires.map(h => `
                        <div class="text-muted small border-bottom py-1">
                            ${escapeHtml(h.candidate_name)} — ${escapeHtml(h.job_title)}
                            ${h.hired_at ? `<span class="ms-2">${formatDateTime(h.hired_at)}</span>` : ''}
                        </div>
                    `).join('')}
                </div>
            </div>
        `).join('');
    } catch (e) {
        document.getElementById('hiresByAgencyBody').innerHTML = `<p class="text-danger small mb-0">${e.message}</p>`;
    }
}

async function loadCandidateReport() {
    const userId = document.getElementById('candidateUserIdInput').value;
    if (!userId) return;
    const body = document.getElementById('candidateReportBody');
    body.innerHTML = 'Loading...';

    try {
        const res = await apiFetch(`/admin/reports/candidate/${userId}/applications`);
        const { candidate, applications, total_applications, total_hires } = res.data;

        if (!candidate) { body.innerHTML = '<p class="text-danger small mb-0">No candidate profile found for this user ID.</p>'; return; }

        body.innerHTML = `
            <div class="mb-2">
                <strong>${escapeHtml(candidate.name)}</strong> (${escapeHtml(candidate.email)})
                — <span class="li-pill li-pill-blue">${total_applications} application${total_applications === 1 ? '' : 's'}</span>
                <span class="li-pill li-pill-green">${total_hires} hire${total_hires === 1 ? '' : 's'}</span>
            </div>
            ${applications.map(a => `
                <div class="border-bottom py-2 small">
                    <strong>${escapeHtml(a.job_title)}</strong> at ${escapeHtml(a.company_name)}
                    — <span class="li-pill li-pill-${a.status === 'hired' ? 'green' : (a.status === 'rejected' ? 'red' : 'blue')}">${a.status.replace(/_/g,' ')}</span>
                    <div class="text-muted">Applied ${formatDateTime(a.applied_at)} ${a.hired_at ? '· Hired ' + formatDateTime(a.hired_at) : ''}</div>
                </div>
            `).join('') || '<p class="text-muted small mb-0">No applications yet.</p>'}
        `;
    } catch (e) {
        body.innerHTML = `<p class="text-danger small mb-0">${e.message}</p>`;
    }
}

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