<?php
require_once __DIR__ . '/../config/bootstrap.php';
$user = Auth::requireLogin();
$pageTitle = 'Dashboard';
$activeNav = 'dashboard';
require __DIR__ . '/../includes/partials/dashboard-head.php';
?>

<!-- Page Header -->
<div class="page-header">
    <div class="page-header-left">
        <h4>Dashboard</h4>
        <p>Plan, prioritize and accomplish your campaigns</p>
    </div>
    <div class="page-header-actions">
        <a href="/dashboard/campaigns/add" class="btn-primary-custom">
            <i class="bi bi-plus"></i> Add Campaign
        </a>
        <a href="mailto:support@droidtester.com" class="btn-dark-custom" style="padding:10px 20px">
            <i class="bi bi-question-circle"></i> Help Support
        </a>
    </div>
</div>

<div class="content-wrapper">

    <!-- Stat Cards (live filled) -->
    <div class="row g-3 mb-4" id="statCards">
        <?php for ($i = 0; $i < 3; $i++): ?>
        <div class="col-lg-4 col-md-6">
            <div class="stat-card fade-in-up" style="opacity:0.4">
                <div class="stat-arrow"><i class="bi bi-arrow-up-right"></i></div>
                <div class="stat-value">—</div>
                <div class="stat-title">Loading…</div>
                <div class="stat-desc">Fetching live data.</div>
            </div>
        </div>
        <?php endfor; ?>
    </div>

    <!-- Campaign List + Chart -->
    <div class="row g-3">
        <div class="col-lg-7">
            <div class="campaign-list-card">
                <div class="d-flex align-items-center justify-content-between mb-3">
                    <div class="card-header-title">All Campaign List</div>
                    <a href="/dashboard/campaigns" class="show-more-link">
                        Show More <i class="bi bi-arrow-right"></i>
                    </a>
                </div>
                <div id="recentCampaignsList">
                    <div class="text-center py-4 text-muted" style="font-size:14px">
                        <div class="spinner-border spinner-border-sm me-2"></div> Loading campaigns…
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-5">
            <div class="chart-card h-100">
                <div class="chart-title">Campaign Reports</div>
                <div style="position:relative;height:200px;width:100%">
                    <canvas id="campaignChart"></canvas>
                </div>
                <div style="text-align:center;margin-top:12px">
                    <div class="fw-800" id="completionPct" style="font-size:28px;color:var(--primary)">0%</div>
                    <div style="font-size:13px;color:var(--text-secondary)">Project Completed</div>
                </div>
                <div class="chart-legend" id="chartLegend"></div>
            </div>
        </div>
    </div>

</div>

<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
(async function () {
    function escapeHtml(s) {
        return String(s ?? '').replace(/[&<>"']/g, c =>
            ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[c]));
    }

    function statCard(value, title, desc) {
        return `
            <div class="col-lg-4 col-md-6">
                <div class="stat-card fade-in-up" style="opacity:1">
                    <div class="stat-arrow"><i class="bi bi-arrow-up-right"></i></div>
                    <div class="stat-value">${value}</div>
                    <div class="stat-title">${title}</div>
                    <div class="stat-desc">${desc}</div>
                </div>
            </div>`;
    }

    function campaignRow(c) {
        const initial = c.app_title ? c.app_title.charAt(0).toUpperCase() : '?';
        const iconHtml = c.app_logo
            ? `<img src="${escapeHtml(c.app_logo)}" class="campaign-app-icon-placeholder" style="object-fit:cover" alt="">`
            : `<div class="campaign-app-icon-placeholder" style="background:linear-gradient(135deg,#1B7A43,#2D9B5A);color:white;font-weight:700">${initial}</div>`;
        return `
            <div class="campaign-row">
                ${iconHtml}
                <div class="flex-grow-1">
                    <div class="campaign-app-name">${escapeHtml(c.app_title)}</div>
                    <div class="campaign-app-dev">${escapeHtml(c.app_developer || '—')}</div>
                </div>
                <span class="${escapeHtml(c.status_badge)}">Status: ${escapeHtml(c.status_label)}</span>
                <a href="${escapeHtml(c.detail_url)}" class="go-btn"><i class="bi bi-arrow-right"></i></a>
            </div>`;
    }

    try {
        const resp = await window.api('/api/dashboard/stats');
        if (resp.status !== 'success') throw new Error(resp.message);
        const d = resp.data;

        // Stat cards
        document.getElementById('statCards').innerHTML =
            statCard(d.stats.total,     'Total Campaign',     'All campaigns ever created.') +
            statCard(d.stats.active,    'Active Campaign',    'Currently running campaigns.') +
            statCard(d.stats.completed, 'Completed Campaign', 'Finished testing campaigns.');

        // Recent list
        const listEl = document.getElementById('recentCampaignsList');
        if (!d.recent_campaigns.length) {
            listEl.innerHTML = `
                <div class="text-center py-5">
                    <div style="font-size:48px">📭</div>
                    <p class="text-muted mt-2">No campaigns yet. Create your first one!</p>
                    <a href="/dashboard/campaigns/add" class="btn-primary-custom" style="display:inline-flex">
                        <i class="bi bi-plus"></i> Add Campaign
                    </a>
                </div>`;
        } else {
            listEl.innerHTML = d.recent_campaigns.map(campaignRow).join('');
        }

        // Donut chart
        document.getElementById('completionPct').textContent = d.stats.completion_pct + '%';
        const ctx = document.getElementById('campaignChart').getContext('2d');
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: d.chart.labels,
                datasets: [{
                    data: d.chart.data,
                    backgroundColor: d.chart.colors,
                    borderWidth: 0,
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                cutout: '70%',
                plugins: { legend: { display: false } }
            }
        });

        // Legend
        document.getElementById('chartLegend').innerHTML = d.chart.labels.map((l, i) => `
            <div class="legend-item">
                <div class="legend-dot" style="background:${d.chart.colors[i]}"></div>
                ${escapeHtml(l)} (${d.chart.data[i]})
            </div>`).join('');

    } catch (err) {
        window.Toast && window.Toast.fire({ icon: 'error', title: 'Could not load dashboard.' });
        console.error(err);
    }
})();
</script>

<?php require __DIR__ . '/../includes/partials/dashboard-foot.php'; ?>
