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

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

<div class="li-card mb-3 overflow-hidden">
    <div style="height:80px; background: linear-gradient(120deg, var(--li-blue), #38b6ff);"></div>
    <div class="li-card-body pt-0">
        <div class="d-flex align-items-end" style="margin-top:-36px;">
            <span class="avatar-circle lg border border-4 border-white"><?= esc(strtoupper(substr($userName, 0, 1))) ?></span>
        </div>
        <h4 class="mt-3 mb-0">Welcome back, <?= esc($userName) ?> 👋</h4>
        <p class="text-muted mb-0"><?= esc(ucwords(str_replace('_', ' ', $role))) ?></p>
    </div>
</div>

<?php if (in_array($role, ['agency_owner', 'recruiter'])): ?>

    <?php if ($role === 'agency_owner'): ?>
        <div class="li-card mb-3">
            <div class="li-card-header d-flex justify-content-between align-items-center">
                <span>Subscription Plans</span>
                <span class="text-muted small">Submit a request — a Super Admin will review and approve it</span>
            </div>
            <div class="li-card-body">
                <div class="row g-2" id="dashPlansList">Loading plans...</div>
            </div>
        </div>
    <?php endif; ?>

    <div class="row g-3 mb-3">
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['open_jobs'] ?></div>
                <div class="li-stat-label">Open Jobs</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['applications'] ?></div>
                <div class="li-stat-label">Applications</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['hires'] ?></div>
                <div class="li-stat-label">Hires</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['team_size'] ?></div>
                <div class="li-stat-label">Team Members</div>
            </div>
        </div>
    </div>

    <div class="row g-3">
        <div class="col-md-8">
            <div class="li-card">
                <div class="li-card-header d-flex justify-content-between align-items-center">
                    Quick Actions
                </div>
                <div class="li-card-body d-flex flex-wrap gap-2">
                    <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>
                    <a href="<?= base_url('admin/candidates') ?>" class="btn btn-li-outline"><i class="bi bi-search me-1"></i>Search Candidates</a>
                    <a href="<?= base_url('admin/ats') ?>" class="btn btn-li-outline"><i class="bi bi-kanban me-1"></i>View ATS Pipeline</a>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <?php if (isset($subscription) && $subscription): ?>
                <div class="li-card">
                    <div class="li-card-header">Your Plan</div>
                    <div class="li-card-body">
                        <span class="li-pill li-pill-blue mb-2 d-inline-block"><?= esc($subscription['plan']['name']) ?></span>
                        <p class="mb-1 text-muted small">Status: <?= esc($subscription['subscription']['status']) ?></p>
                        <p class="mb-3 text-muted small">Renews: <?= esc($subscription['subscription']['current_period_end']) ?></p>
                        <a href="<?= base_url('admin/billing') ?>" class="btn btn-li-outline btn-sm w-100">Manage Billing</a>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </div>

<?php elseif ($role === 'candidate'): ?>
    <div class="row g-3 mb-3">
        <div class="col-6 col-md-4">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) ($stats['applications'] ?? 0) ?></div>
                <div class="li-stat-label">Applications Sent</div>
            </div>
        </div>
        <div class="col-6 col-md-4">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) ($stats['profile_pct'] ?? 0) ?>%</div>
                <div class="li-stat-label">Profile Complete</div>
            </div>
        </div>
    </div>

    <?php if (($stats['profile_pct'] ?? 0) < 100): ?>
        <div class="li-card mb-3">
            <div class="li-card-body d-flex justify-content-between align-items-center">
                <div>
                    <strong>Your profile is <?= (int) ($stats['profile_pct'] ?? 0) ?>% complete.</strong>
                    <div class="text-muted small">Complete your profile to get discovered by more recruiters.</div>
                </div>
                <a href="<?= base_url('admin/profile') ?>" class="btn btn-li-primary">Complete Profile</a>
            </div>
        </div>
    <?php endif; ?>

    <div class="li-card">
        <div class="li-card-header">Quick Actions</div>
        <div class="li-card-body d-flex flex-wrap gap-2">
            <a href="<?= base_url('admin/jobs') ?>" class="btn btn-li-primary"><i class="bi bi-search me-1"></i>Browse Jobs</a>
            <a href="<?= base_url('admin/applications') ?>" class="btn btn-li-outline"><i class="bi bi-file-earmark-text me-1"></i>My Applications</a>
            <a href="<?= base_url('admin/profile') ?>" class="btn btn-li-outline"><i class="bi bi-person me-1"></i>Edit Profile</a>
        </div>
    </div>

<?php elseif ($role === 'super_admin'): ?>
    <div class="row g-3 mb-3">
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['total_users'] ?></div>
                <div class="li-stat-label">Total Users</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['agencies'] ?></div>
                <div class="li-stat-label">Agencies (<?= (int) $stats['agencies_active'] ?> active)</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['candidates'] ?></div>
                <div class="li-stat-label">Candidates</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num text-success"><?= (int) $stats['open_to_work'] ?></div>
                <div class="li-stat-label">Open to Work</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['jobs_published'] ?></div>
                <div class="li-stat-label">Published Jobs (<?= (int) $stats['jobs_total'] ?> total)</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num"><?= (int) $stats['applications'] ?></div>
                <div class="li-stat-label">Applications</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num text-success"><?= (int) $stats['hires'] ?></div>
                <div class="li-stat-label">Total Hires</div>
            </div>
        </div>
        <div class="col-6 col-md-3">
            <div class="li-card li-card-body text-center">
                <div class="li-stat-num text-warning"><?= (int) $stats['pending_verifications'] ?></div>
                <div class="li-stat-label">Pending Verifications</div>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-3">
        <div class="col-md-6">
            <div class="li-card li-card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="text-muted small">Last 7 Days</div>
                    <div class="fw-bold"><?= (int) $stats['new_users_7d'] ?> new users</div>
                </div>
                <i class="bi bi-person-plus fs-3 text-muted"></i>
            </div>
        </div>
        <div class="col-md-6">
            <div class="li-card li-card-body d-flex justify-content-between align-items-center">
                <div>
                    <div class="text-muted small">Last 7 Days</div>
                    <div class="fw-bold"><?= (int) $stats['new_jobs_7d'] ?> new jobs posted</div>
                </div>
                <i class="bi bi-briefcase fs-3 text-muted"></i>
            </div>
        </div>
    </div>

    <div class="row g-3 mb-3">
        <div class="col-md-6">
            <div class="li-card">
                <div class="li-card-header">Recently Registered</div>
                <div class="li-card-body p-0">
                    <?php foreach ($recentUsers as $u): ?>
                        <div class="d-flex justify-content-between px-3 py-2 border-bottom">
                            <div>
                                <div class="small fw-semibold"><?= esc($u['name']) ?></div>
                                <div class="text-muted small"><?= esc($u['email']) ?></div>
                            </div>
                            <div class="text-end">
                                <span class="li-pill li-pill-blue"><?= esc(str_replace('_', ' ', $u['role_slug'])) ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($recentUsers)): ?><p class="text-muted small text-center py-3 mb-0">No users yet.</p><?php endif; ?>
                </div>
            </div>
        </div>
        <div class="col-md-6">
            <div class="li-card">
                <div class="li-card-header">Recently Posted Jobs</div>
                <div class="li-card-body p-0">
                    <?php foreach ($recentJobs as $j): ?>
                        <div class="d-flex justify-content-between px-3 py-2 border-bottom">
                            <div>
                                <div class="small fw-semibold"><?= esc($j['title']) ?></div>
                                <div class="text-muted small"><?= esc($j['company_name']) ?></div>
                            </div>
                            <span class="li-pill li-pill-<?= $j['status'] === 'published' ? 'green' : 'gray' ?>"><?= esc($j['status']) ?></span>
                        </div>
                    <?php endforeach; ?>
                    <?php if (empty($recentJobs)): ?><p class="text-muted small text-center py-3 mb-0">No jobs yet.</p><?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="li-card">
        <div class="li-card-header">Quick Actions</div>
        <div class="li-card-body d-flex flex-wrap gap-2">
            <a href="<?= base_url('admin/agencies') ?>" class="btn btn-li-primary"><i class="bi bi-building me-1"></i>Manage Agencies</a>
            <a href="<?= base_url('admin/payments') ?>" class="btn btn-li-outline"><i class="bi bi-credit-card me-1"></i>Payments & Invoices</a>
            <a href="<?= base_url('admin/reports') ?>" class="btn btn-li-outline"><i class="bi bi-bar-chart me-1"></i>Platform Reports</a>
            <a href="<?= base_url('admin/settings') ?>" class="btn btn-li-outline"><i class="bi bi-gear me-1"></i>Settings</a>
        </div>
    </div>
<?php endif; ?>

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

<?php if ($role === 'agency_owner'): ?>
<?= $this->section('scripts') ?>
<script>
async function loadDashPlans() {
    try {
        const [plansRes, currentRes, pendingRes] = await Promise.all([
            apiFetch('/billing/plans'),
            apiFetch('/billing/subscription').catch(() => null),
            apiFetch('/billing/subscription/pending-request').catch(() => null),
        ]);
        const plans = plansRes.data.plans || [];
        const currentSlug = currentRes?.data?.plan?.slug;
        const pending = pendingRes?.data?.pending_request;

        let pendingBanner = '';
        if (pending) {
            pendingBanner = `
                <div class="alert alert-warning py-2 px-3 mb-3 small">
                    <i class="bi bi-hourglass-split me-1"></i>
                    Your request to switch to <strong>${escapeHtml(pending.requested_plan_name)}</strong> is awaiting Super Admin approval.
                </div>`;
        }

        document.getElementById('dashPlansList').innerHTML = pendingBanner + plans.map(p => `
            <div class="col-md-3">
                <div class="li-card li-card-body h-100 d-flex flex-column ${p.slug === currentSlug ? 'border-primary' : ''}">
                    <div class="fw-bold">${escapeHtml(p.name)} ${p.slug === currentSlug ? '<span class="li-pill li-pill-blue">Current</span>' : ''}</div>
                    <div class="text-muted small mb-2">PKR ${Number(p.price_monthly).toLocaleString()}/mo</div>
                    <div class="text-muted small mb-3 flex-grow-1">
                        ${p.job_posting_limit == -1 ? 'Unlimited jobs' : p.job_posting_limit + ' jobs'} ·
                        ${p.candidate_view_limit == -1 ? 'Unlimited views' : p.candidate_view_limit + ' views'}
                    </div>
                    ${p.slug === currentSlug
                        ? `<button class="btn btn-li-outline btn-sm" disabled>Active Plan</button>`
                        : pending
                            ? `<button class="btn btn-li-outline btn-sm" disabled>Request Pending</button>`
                            : `<button class="btn btn-li-primary btn-sm" onclick="assignDashPlan('${p.slug}')">Request This Plan</button>`}
                </div>
            </div>
        `).join('');
    } catch (e) { document.getElementById('dashPlansList').innerHTML = '<p class="text-muted small">Could not load plans.</p>'; }
}

async function assignDashPlan(slug) {
    try {
        await apiFetch('/billing/subscribe', {
            method: 'POST',
            body: JSON.stringify({ plan_slug: slug, billing_cycle: 'monthly' }),
        });
        showToast('Plan change requested — a Super Admin will review it shortly.');
        loadDashPlans();
    } catch (e) { showToast(e.message, true); }
}

loadDashPlans();
</script>
<?= $this->endSection() ?>
<?php endif; ?>
