$(function () {
    loadReport();
    $('#filterSearch').on('input', debounce(loadReport, 300));
    $('#filterStatus').on('change', loadReport);
    $('#btnRefresh').on('click', loadReport);
    $('#btnExport').on('click', exportCsv);
});

let _allWorkshops = [];

function loadReport() {
    const search = $('#filterSearch').val();
    const status = $('#filterStatus').val();
    const tbody = $('#workshopReportBody');
    tbody.html('<tr><td colspan="10" class="text-center text-muted py-4">Loading report data...</td></tr>');

    $.get('api/workshop.php', { action: 'list', search: search, status: status }, function (res) {
        if (res.status !== 'success') {
            tbody.html('<tr><td colspan="10" class="text-center text-danger py-4">' + esc(res.message || 'Load failed') + '</td></tr>');
            return;
        }
        _allWorkshops = res.data || [];
        renderKpis(_allWorkshops);
        renderTable(_allWorkshops);
    });
}

function renderKpis(data) {
    const total = data.length;
    const active = data.filter(function (w) { return w.status === 'active'; }).length;
    let totalRfqs = 0;
    let totalValue = 0;
    data.forEach(function (w) {
        const s = w.quote_summary || {};
        totalRfqs += Number(s.rfqs_total || 0);
        totalValue += Number(s.total_quote_amount || 0);
    });
    $('#kpiTotalWorkshops').text(total);
    $('#kpiActiveWorkshops').text(active);
    $('#kpiTotalRfqs').text(totalRfqs);
    $('#kpiTotalQuoteValue').text(fmtCurr(totalValue));
}

function renderTable(data) {
    const tbody = $('#workshopReportBody');
    if (!data.length) {
        tbody.html('<tr><td colspan="10" class="text-center text-muted py-4">No workshops found</td></tr>');
        return;
    }
    tbody.html(data.map(function (w) {
        const s = w.quote_summary || {};
        const latest = Number(s.latest_quote_amount || 0);
        return '<tr>' +
            '<td><div class="fw-semibold">' + esc(w.name || '-') + '</div></td>' +
            '<td>' + esc(w.contact_person || '-') + '</td>' +
            '<td>' + esc(w.phone || '-') + '</td>' +
            '<td>' + esc(w.email || '-') + '</td>' +
            '<td>' + statusBadge(w.status) + '</td>' +
            '<td class="text-center">' + Number(s.rfqs_total || 0) + '</td>' +
            '<td class="text-center">' + Number(s.submitted_quotes || 0) + '</td>' +
            '<td class="text-center">' + Number(s.selected_quotes || 0) + '</td>' +
            '<td class="text-end fw-semibold">' + fmtCurr(Number(s.total_quote_amount || 0)) + '</td>' +
            '<td>' + (latest > 0 ? fmtCurr(latest) : '-') + '</td>' +
            '</tr>';
    }).join(''));
}

function statusBadge(status) {
    return status === 'active'
        ? '<span class="badge bg-success">Active</span>'
        : '<span class="badge bg-secondary">Inactive</span>';
}

function exportCsv() {
    if (!_allWorkshops.length) return;
    const rows = [['Workshop', 'Contact', 'Phone', 'Email', 'Status', 'RFQs', 'Submitted', 'Selected', 'Total Quote Value', 'Latest Quote']];
    _allWorkshops.forEach(function (w) {
        const s = w.quote_summary || {};
        rows.push([
            w.name || '',
            w.contact_person || '',
            w.phone || '',
            w.email || '',
            w.status || '',
            String(Number(s.rfqs_total || 0)),
            String(Number(s.submitted_quotes || 0)),
            String(Number(s.selected_quotes || 0)),
            fmtCsvCurr(Number(s.total_quote_amount || 0)),
            fmtCsvCurr(Number(s.latest_quote_amount || 0))
        ]);
    });
    const csv = rows.map(function (r) { return r.map(csvEsc).join(','); }).join('\n');
    const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
    const a = document.createElement('a');
    a.href = URL.createObjectURL(blob);
    a.download = 'workshop_report_' + new Date().toISOString().split('T')[0] + '.csv';
    a.click();
    URL.revokeObjectURL(a.href);
}

function csvEsc(v) {
    const s = String(v == null ? '' : v);
    return /[,"\n]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s;
}

function fmtCurr(v) {
    const n = Number(v || 0);
    const locale = n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
    return Number.isFinite(n) && n > 0 ? '\u20A6' + locale : '\u20A60.00';
}

function fmtCsvCurr(v) {
    const n = Number(v || 0);
    return Number.isFinite(n) ? n.toFixed(2) : '0.00';
}

function esc(text) {
    const d = document.createElement('div');
    d.textContent = text == null ? '' : String(text);
    return d.innerHTML;
}

function debounce(fn, wait) {
    let t;
    return function () { clearTimeout(t); t = setTimeout(fn, wait); };
}
