<?= $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 flex-wrap gap-2">
    <h5 class="mb-0">Manage Agencies</h5>
    <div class="d-flex gap-2 flex-wrap">
        <input type="text" id="searchFilter" class="form-control form-control-sm" style="width:200px;" placeholder="Search company or email">
        <select id="verificationFilter" class="form-select form-select-sm" style="width:160px;">
            <option value="">All verification</option>
            <option value="pending">Pending</option>
            <option value="verified">Verified</option>
            <option value="rejected">Rejected</option>
        </select>
        <select id="statusFilter" class="form-select form-select-sm" style="width:140px;">
            <option value="">All statuses</option>
            <option value="active">Active</option>
            <option value="suspended">Suspended</option>
        </select>
    </div>
</div>

<div id="agenciesList"></div>
<div id="agenciesEmpty" class="li-card li-card-body text-center text-muted py-5 d-none">
    <i class="bi bi-building display-4 d-block mb-2"></i>No agencies match your filters.
</div>

<div class="d-flex justify-content-between align-items-center mt-3" id="paginationBar" style="display:none;">
    <span class="text-muted small" id="pageInfo"></span>
    <div>
        <button class="btn btn-li-ghost btn-sm" id="prevPageBtn" onclick="changePage(-1)">← Previous</button>
        <button class="btn btn-li-ghost btn-sm" id="nextPageBtn" onclick="changePage(1)">Next →</button>
    </div>
</div>

<!-- Unified Agency Detail panel — tabs instead of a scattered dropdown +
     several separate modals, so every action for one agency lives in one
     place. -->
<div class="modal fade" id="agencyDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h6 class="modal-title mb-0" id="adCompanyName">Agency</h6>
                    <div class="text-muted small" id="adOwnerEmail"></div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>

            <ul class="nav nav-tabs px-3 pt-2" id="agencyDetailTabs">
                <li class="nav-item"><button class="nav-link active" data-bs-toggle="tab" data-bs-target="#tabOverview" type="button">Overview</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSubscription" type="button">Subscription</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabCredits" type="button">Credits</button></li>
                <li class="nav-item"><button class="nav-link" data-bs-toggle="tab" data-bs-target="#tabSecurity" type="button">Security</button></li>
            </ul>

            <div class="modal-body tab-content">
                <input type="hidden" id="adAgencyId">

                <div class="tab-pane fade show active" id="tabOverview">
                    <div id="adOverviewBody">Loading...</div>
                </div>

                <div class="tab-pane fade" id="tabSubscription">
                    <div id="smCurrentInfo" class="mb-3">Loading...</div>
                    <hr>
                    <h6 class="mb-2">Change Plan</h6>
                    <div class="d-flex gap-2 mb-2 flex-wrap">
                        <select id="smPlanSelect" class="form-select form-select-sm" style="min-width:180px; flex:1;"></select>
                        <select id="smBillingCycle" class="form-select form-select-sm" style="width:120px;">
                            <option value="monthly">Monthly</option>
                            <option value="yearly">Yearly</option>
                        </select>
                        <button class="btn btn-li-primary btn-sm" onclick="changeSubscriptionPlan()">Apply</button>
                    </div>
                    <p class="text-muted small">Grants the plan directly (no payment) — for admin overrides, promotions, or approved plan-change requests.</p>
                    <hr>
                    <h6 class="mb-2">Reset Usage This Period</h6>
                    <p class="text-muted small">Resets jobs posted / candidate views / contact reveals / resume downloads to 0 without changing the plan.</p>
                    <button class="btn btn-li-outline btn-sm" onclick="resetSubscriptionUsage()">Reset Usage to 0</button>
                </div>

                <div class="tab-pane fade" id="tabCredits">
                    <div class="mb-3">
                        <span class="text-muted small">Current balance</span>
                        <div class="li-stat-num" id="adCreditBalance" style="font-size:28px;">—</div>
                    </div>
                    <label class="form-label">Amount (positive to add, negative to deduct)</label>
                    <input type="number" id="caAmount" class="form-control mb-2" placeholder="e.g. 50 or -10">
                    <label class="form-label">Note <span class="text-danger">*</span> (required — why this adjustment?)</label>
                    <textarea id="caNote" class="form-control mb-2" rows="3" placeholder="e.g. Compensation for a service outage on Aug 5"></textarea>
                    <button class="btn btn-li-primary btn-sm" onclick="submitCreditAdjust()">Apply Adjustment</button>
                </div>

                <div class="tab-pane fade" id="tabSecurity">
                    <h6 class="mb-2">Reset Owner Password</h6>
                    <p class="text-muted small">Generates a new temporary password for the agency owner's account. There's no email delivery configured yet, so you'll need to share this password with them directly.</p>
                    <button class="btn btn-li-outline btn-sm" onclick="resetAgencyPassword()"><i class="bi bi-key me-1"></i>Generate New Password</button>
                    <div id="resetPasswordResult" class="mt-3 d-none">
                        <div class="alert alert-success">
                            <div class="small text-muted mb-1">New temporary password (copy and share securely — this won't be shown again):</div>
                            <div class="d-flex align-items-center gap-2">
                                <code id="newPasswordText" style="font-size:16px;"></code>
                                <button class="btn btn-li-ghost btn-sm" onclick="copyNewPassword()"><i class="bi bi-clipboard"></i></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

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

<?= $this->section('scripts') ?>
<script>
let currentPage = 1;
let totalAgencies = 0;
const PER_PAGE = 15;
let agencyCache = {}; // id -> agency row, so the detail modal doesn't need a re-fetch for basics

function verPill(v) {
    const map = { pending: 'yellow', verified: 'green', rejected: 'red', under_review: 'blue' };
    return `<span class="li-pill li-pill-${map[v] || 'gray'}">${v}</span>`;
}
function statPill(s) {
    return `<span class="li-pill li-pill-${s === 'active' ? 'green' : 'red'}">${s}</span>`;
}

let searchTimer = null;
document.getElementById('searchFilter').addEventListener('input', () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(() => loadAgencies(1), 400);
});
document.getElementById('verificationFilter').addEventListener('change', () => loadAgencies(1));
document.getElementById('statusFilter').addEventListener('change', () => loadAgencies(1));

async function loadAgencies(page) {
    currentPage = page || currentPage;
    const params = new URLSearchParams();
    const q = document.getElementById('searchFilter').value;
    const v = document.getElementById('verificationFilter').value;
    const s = document.getElementById('statusFilter').value;
    if (q) params.set('q', q);
    if (v) params.set('verification_status', v);
    if (s) params.set('status', s);
    params.set('page', currentPage);
    params.set('per_page', PER_PAGE);

    try {
        const res = await apiFetch(`/admin/agencies?${params.toString()}`);
        const agencies = res.data || [];
        totalAgencies = res.meta.total || agencies.length;
        agencies.forEach(a => agencyCache[a.id] = a);
        renderAgencies(agencies);

        const totalPages = Math.max(1, Math.ceil(totalAgencies / PER_PAGE));
        const bar = document.getElementById('paginationBar');
        if (totalPages <= 1) { bar.style.display = 'none'; }
        else {
            bar.style.display = 'flex';
            document.getElementById('pageInfo').textContent = `Page ${currentPage} of ${totalPages} (${totalAgencies} total)`;
            document.getElementById('prevPageBtn').disabled = currentPage <= 1;
            document.getElementById('nextPageBtn').disabled = currentPage >= totalPages;
        }
    } catch (e) {
        showToast(e.message, true);
    }
}
function changePage(delta) { loadAgencies(currentPage + delta); }

function renderAgencies(agencies) {
    const list = document.getElementById('agenciesList');
    const empty = document.getElementById('agenciesEmpty');

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

    list.innerHTML = agencies.map(a => `
        <div class="li-card mb-2">
            <div class="li-card-body">
                <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                    <div class="d-flex gap-3 align-items-center">
                        <span class="avatar-circle" style="border-radius:8px;">${escapeHtml((a.company_name || 'A')[0].toUpperCase())}</span>
                        <div>
                            <div class="fw-bold">${escapeHtml(a.company_name)}</div>
                            <div class="text-muted small">${escapeHtml(a.owner_name || '—')} · ${escapeHtml(a.owner_email || '')}</div>
                            <div class="mt-1 d-flex gap-2 flex-wrap">
                                ${verPill(a.verification_status)}
                                ${statPill(a.status)}
                                <span class="li-pill li-pill-blue">${a.credit_balance} credits</span>
                                <span class="text-muted small">${a.recruiter_count} recruiter${a.recruiter_count == 1 ? '' : 's'} · joined ${dateOnly(a.created_at)}</span>
                            </div>
                        </div>
                    </div>
                    <button class="btn btn-li-primary btn-sm" onclick="openAgencyDetail(${a.id})"><i class="bi bi-gear me-1"></i>Manage</button>
                </div>
            </div>
        </div>
    `).join('');
}

async function openAgencyDetail(agencyId) {
    const a = agencyCache[agencyId];
    document.getElementById('adAgencyId').value = agencyId;
    document.getElementById('adCompanyName').textContent = a ? a.company_name : 'Agency';
    document.getElementById('adOwnerEmail').textContent = a ? a.owner_email : '';
    document.getElementById('resetPasswordResult').classList.add('d-none');

    // Reset to the Overview tab every time it's opened.
    const firstTabBtn = document.querySelector('#agencyDetailTabs .nav-link');
    if (window.bootstrap) new bootstrap.Tab(firstTabBtn).show();

    renderOverviewTab(a);
    new bootstrap.Modal(document.getElementById('agencyDetailModal')).show();
    loadSubscriptionTab(agencyId);
    document.getElementById('adCreditBalance').textContent = a ? a.credit_balance : '—';
    document.getElementById('caAmount').value = '';
    document.getElementById('caNote').value = '';
}

function renderOverviewTab(a) {
    if (!a) { document.getElementById('adOverviewBody').innerHTML = '<p class="text-muted">Details unavailable.</p>'; return; }
    document.getElementById('adOverviewBody').innerHTML = `
        <div class="mb-3">
            <div class="d-flex justify-content-between border-bottom py-2"><span class="text-muted small">Owner</span><span class="small">${escapeHtml(a.owner_name || '—')}</span></div>
            <div class="d-flex justify-content-between border-bottom py-2"><span class="text-muted small">Email</span><span class="small">${escapeHtml(a.owner_email || '—')}</span></div>
            <div class="d-flex justify-content-between border-bottom py-2"><span class="text-muted small">Recruiters</span><span class="small">${a.recruiter_count}</span></div>
            <div class="d-flex justify-content-between border-bottom py-2"><span class="text-muted small">Joined</span><span class="small">${dateOnly(a.created_at)}</span></div>
            <div class="d-flex justify-content-between border-bottom py-2"><span class="text-muted small">Verification</span>${verPill(a.verification_status)}</div>
            <div class="d-flex justify-content-between py-2"><span class="text-muted small">Account Status</span>${statPill(a.status)}</div>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            ${a.verification_status !== 'verified' ? `<button class="btn btn-li-primary btn-sm" onclick="decide(${a.id}, 'verified')">Approve Verification</button>` : ''}
            ${a.verification_status !== 'rejected' ? `<button class="btn btn-li-outline btn-sm" onclick="decide(${a.id}, 'rejected')">Reject Verification</button>` : ''}
            ${a.status === 'active'
                ? `<button class="btn btn-outline-danger btn-sm" onclick="suspendAgency(${a.id})">Suspend Agency</button>`
                : `<button class="btn btn-outline-success btn-sm" onclick="activateAgency(${a.id})">Reactivate Agency</button>`}
        </div>
    `;
}

async function loadSubscriptionTab(agencyId) {
    document.getElementById('smCurrentInfo').innerHTML = 'Loading...';
    try {
        const res = await apiFetch(`/admin/agencies/${agencyId}/subscription`);
        const { subscription, plan, usage, all_plans } = res.data;

        if (!subscription) {
            document.getElementById('smCurrentInfo').innerHTML = '<p class="text-muted">No active subscription.</p>';
        } else {
            const limitRow = (label, used, limit) => `
                <div class="d-flex justify-content-between border-bottom py-1">
                    <span class="text-muted small">${label}</span>
                    <span class="small fw-semibold">${used || 0} / ${limit == -1 ? '∞' : limit}</span>
                </div>`;
            document.getElementById('smCurrentInfo').innerHTML = `
                <div class="li-card li-card-body">
                    <div class="d-flex justify-content-between mb-2">
                        <span class="fw-bold">${escapeHtml(plan.name)}</span>
                        <span class="li-pill li-pill-blue">${subscription.status}</span>
                    </div>
                    ${limitRow('Jobs Posted', usage?.jobs_posted_used, plan.job_posting_limit)}
                    ${limitRow('Candidate Views', usage?.candidate_views_used, plan.candidate_view_limit)}
                    ${limitRow('Contact Reveals', usage?.contact_reveals_used, plan.contact_reveal_limit)}
                    ${limitRow('Resume Downloads', usage?.resume_downloads_used, plan.resume_download_limit)}
                    <div class="text-muted small mt-2">Renews: ${dateOnly(subscription.current_period_end)}</div>
                </div>
            `;
        }

        const select = document.getElementById('smPlanSelect');
        select.innerHTML = all_plans.map(p => `<option value="${p.slug}" ${plan && plan.slug === p.slug ? 'selected' : ''}>${escapeHtml(p.name)} — PKR ${Number(p.price_monthly).toLocaleString()}/mo</option>`).join('');
    } catch (e) { showToast(e.message, true); }
}

async function changeSubscriptionPlan() {
    const agencyId = document.getElementById('adAgencyId').value;
    const planSlug = document.getElementById('smPlanSelect').value;
    const billingCycle = document.getElementById('smBillingCycle').value;
    try {
        await apiFetch(`/admin/agencies/${agencyId}/subscription/change-plan`, {
            method: 'POST',
            body: JSON.stringify({ plan_slug: planSlug, billing_cycle: billingCycle }),
        });
        showToast('Plan updated.');
        loadSubscriptionTab(agencyId);
    } catch (e) { showToast(e.message, true); }
}

async function resetSubscriptionUsage() {
    const agencyId = document.getElementById('adAgencyId').value;
    if (!confirm('Reset this agency\'s usage counters to 0 for the current period?')) return;
    try {
        await apiFetch(`/admin/agencies/${agencyId}/subscription/reset-usage`, { method: 'POST' });
        showToast('Usage reset.');
        loadSubscriptionTab(agencyId);
    } catch (e) { showToast(e.message, true); }
}

async function submitCreditAdjust() {
    const agencyId = document.getElementById('adAgencyId').value;
    const amount = parseInt(document.getElementById('caAmount').value);
    const note = document.getElementById('caNote').value.trim();

    if (!amount) { showToast('Enter a non-zero amount.', true); return; }
    if (!note) { showToast('A note is required.', true); return; }

    try {
        const res = await apiFetch(`/admin/agencies/${agencyId}/credits`, { method: 'POST', body: JSON.stringify({ amount, note }) });
        showToast(`Credits adjusted. New balance: ${res.data.new_balance}`);
        document.getElementById('adCreditBalance').textContent = res.data.new_balance;
        document.getElementById('caAmount').value = '';
        document.getElementById('caNote').value = '';
        loadAgencies(currentPage);
    } catch (e) { showToast(e.message, true); }
}

async function resetAgencyPassword() {
    const agencyId = document.getElementById('adAgencyId').value;
    if (!confirm('Generate a new temporary password for this agency\'s owner? Their current password will stop working immediately.')) return;
    try {
        const res = await apiFetch(`/admin/agencies/${agencyId}/reset-password`, { method: 'POST' });
        document.getElementById('newPasswordText').textContent = res.data.temp_password;
        document.getElementById('resetPasswordResult').classList.remove('d-none');
        showToast('New password generated.');
    } catch (e) { showToast(e.message, true); }
}

function copyNewPassword() {
    const text = document.getElementById('newPasswordText').textContent;
    navigator.clipboard.writeText(text).then(() => showToast('Password copied to clipboard.'));
}

async function decide(id, decision) {
    try {
        await apiFetch(`/admin/agencies/${id}/verify`, { method: 'POST', body: JSON.stringify({ decision }) });
        showToast(`Agency ${decision}.`);
        loadAgencies(currentPage);
        bootstrap.Modal.getInstance(document.getElementById('agencyDetailModal'))?.hide();
    } catch (e) { showToast(e.message, true); }
}
async function suspendAgency(id) {
    if (!confirm('Suspend this agency? They will lose access immediately.')) return;
    try {
        await apiFetch(`/admin/agencies/${id}/suspend`, { method: 'POST' });
        showToast('Agency suspended.');
        loadAgencies(currentPage);
        bootstrap.Modal.getInstance(document.getElementById('agencyDetailModal'))?.hide();
    } catch (e) { showToast(e.message, true); }
}
async function activateAgency(id) {
    try {
        await apiFetch(`/admin/agencies/${id}/activate`, { method: 'POST' });
        showToast('Agency reactivated.');
        loadAgencies(currentPage);
        bootstrap.Modal.getInstance(document.getElementById('agencyDetailModal'))?.hide();
    } catch (e) { showToast(e.message, true); }
}

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