/* =====================================================
   DASHBOARD KEPATUHAN PEMBAYARAN – UPGRADED FINAL
   STABLE • ROLE AWARE • CSV + PDF READY
===================================================== */

/* =======================
   STATE
======================= */
let allRows = [];
let currentPeriod = '';
let currentCategory = 'ALL';

let chartMain = null;
let chartTop  = null;

const API = 'api_kepatuhan.php';

/* =======================
   ROLE (DARI PHP)
======================= */
// WAJIB ADA DI index.php
// <script>const USER_ROLE = "ADMIN";</script>

const CAN_EDIT   = USER_ROLE === 'ADMIN';
const CAN_DELETE = USER_ROLE === 'ADMIN';
const CAN_EXPORT = USER_ROLE !== 'GUEST';

/* =======================
   HELPERS
======================= */
function $(id) {
    return document.getElementById(id);
}

function rupiah(n) {
    if (n == null || isNaN(n)) return 'Rp 0';
    return 'Rp ' + Number(n).toLocaleString('id-ID');
}

function toast(msg, type = 'success') {
    console.log(`[${type.toUpperCase()}]`, msg);
}

/* =======================
   KATEGORI
======================= */
function categoryLabel(cat) {
    return cat === 'ALL' ? 'Semua Kategori' : cat;
}

/* =======================
   UPDATE JUDUL TABEL
======================= */
function updateTableTitle() {
    if ($('tableTitle')) {
        $('tableTitle').innerHTML =
            `<i class="fas fa-table"></i> Kepatuhan Pembayaran – ${categoryLabel(currentCategory)}`;
    }
    if ($('tableSubtitle')) {
        $('tableSubtitle').textContent =
            currentPeriod ? `Periode ${currentPeriod}` : 'Pilih periode';
    }
}

/* =======================
   LOAD PERIODE
======================= */
async function loadPeriods() {
    try {
        const res  = await fetch(`${API}?action=get_periods`);
        const json = await res.json();

        if (!json.success) throw json.error;

        const sel = $('periodSelect');
        if (!sel) return;

        sel.innerHTML = '<option value="">Pilih Periode</option>';

        json.data.forEach(p => {
            sel.innerHTML += `<option value="${p}">${p}</option>`;
        });

        if (json.data.length) {
            currentPeriod   = json.data[0];
            currentCategory = 'ALL';
            sel.value       = currentPeriod;
            updateTableTitle();
            loadData(currentPeriod);
        }
    } catch (e) {
        toast('Gagal memuat periode', 'error');
    }
}

/* =======================
   LOAD DATA
======================= */
async function loadData(period) {
    if (!period) return;
    currentPeriod = period;

    const url =
        currentCategory === 'ALL'
            ? `${API}?action=get_data&period=${encodeURIComponent(period)}`
            : `${API}?action=detail&period=${encodeURIComponent(period)}&category=${encodeURIComponent(currentCategory)}`;

    try {
        const res  = await fetch(url);
        const json = await res.json();

        if (!json.success) throw json.error;

        allRows = json.data.rows || [];

        renderSummary(json.data.summary);
        renderTable();
        renderCharts();
    } catch (e) {
        toast(e || 'Gagal memuat data', 'error');
    }
}

/* =======================
   SUMMARY
======================= */
function renderSummary(s) {
    if (!s) return;

    if ($('statTarget'))  $('statTarget').textContent  = rupiah(s.total_target);
    if ($('statCapaian')) $('statCapaian').textContent = rupiah(s.total_capaian);
    if ($('statPiutang')) $('statPiutang').textContent = rupiah(s.total_piutang);
    if ($('statPersen'))  $('statPersen').textContent  = s.persen + '%';
}

/* =======================
   TABLE
======================= */
function renderTable() {
    const tbody = $('tableBody');
    if (!tbody) return;

    tbody.innerHTML = '';

    if (!allRows.length) {
        tbody.innerHTML = `<tr><td colspan="8">Tidak ada data</td></tr>`;
        return;
    }

    allRows.forEach((r, i) => {
        const tr = document.createElement('tr');

        if (r.kategori === 'POOR') {
            tr.style.background = '#fee2e2';
        }

        tr.innerHTML = `
            <td>${i + 1}</td>
            <td>${r.ta}</td>
            <td align="right">${rupiah(r.target)}</td>
            <td align="right">${rupiah(r.capaian)}</td>
            <td align="right">${rupiah(r.piutang)}</td>
            <td align="center">${r.persen}%</td>
            <td align="center">${r.kategori}</td>
            ${
                CAN_EDIT || CAN_DELETE
                    ? `<td>
                        ${CAN_EDIT ? `<button onclick="editRow(${r.id})">✏️</button>` : ''}
                        ${CAN_DELETE ? `<button onclick="deleteRow(${r.id})">🗑️</button>` : ''}
                      </td>`
                    : ''
            }
        `;
        tbody.appendChild(tr);
    });
}

/* =======================
   CHARTS
======================= */
function destroyChart(c) {
    if (c) c.destroy();
}

function renderCharts() {
    destroyChart(chartMain);
    destroyChart(chartTop);

    if (!window.Chart || !allRows.length) return;

    const mainEl = $('chartMainEl');
    const topEl  = $('chartTopEl');

    if (mainEl) {
        chartMain = new Chart(mainEl, {
            type: 'bar',
            data: {
                labels: allRows.map(r => r.ta),
                datasets: [
                    { label: 'Capaian', data: allRows.map(r => r.capaian), backgroundColor: '#4D869C' },
                    { label: 'Piutang', data: allRows.map(r => r.piutang), backgroundColor: '#ef4444' }
                ]
            }
        });
    }

    if (topEl) {
        const top5 = [...allRows]
            .sort((a, b) => b.capaian - a.capaian)
            .slice(0, 5);

        chartTop = new Chart(topEl, {
            type: 'bar',
            data: {
                labels: top5.map(r => r.ta),
                datasets: [{
                    label: 'Top 5',
                    data: top5.map(r => r.capaian),
                    backgroundColor: '#10b981'
                }]
            },
            options: { indexAxis: 'y' }
        });
    }
}

/* =======================
   EXPORT
======================= */
function exportCSV() {
    if (!CAN_EXPORT || !currentPeriod) return;

    let url = `${API}?action=export&period=${encodeURIComponent(currentPeriod)}`;
    if (currentCategory !== 'ALL') {
        url += `&category=${encodeURIComponent(currentCategory)}`;
    }
    window.location.href = url;
}

function exportPDF() {
    if (!CAN_EXPORT || !currentPeriod) return;

    let url = `${API}?action=export_pdf&period=${encodeURIComponent(currentPeriod)}`;
    if (currentCategory !== 'ALL') {
        url += `&category=${encodeURIComponent(currentCategory)}`;
    }
    window.open(url, '_blank');
}

/* =======================
   INIT
======================= */
document.addEventListener('DOMContentLoaded', () => {

    if ($('periodSelect')) {
        $('periodSelect').addEventListener('change', e => {
            currentCategory = 'ALL';
            updateTableTitle();
            loadData(e.target.value);
        });
    }

    document.querySelectorAll('#categoryTabs .tab').forEach(btn => {
        btn.addEventListener('click', () => {
            document.querySelectorAll('#categoryTabs .tab')
                .forEach(t => t.classList.remove('active'));

            btn.classList.add('active');
            currentCategory = btn.dataset.cat;
            updateTableTitle();

            if (currentPeriod) {
                loadData(currentPeriod);
            }
        });
    });

    loadPeriods();
});
