// Frontend Logic for Current Shift Calibration & Audit Matching Page

let shiftData = null;

const dom = {
    // Section 1: Revenue Totals
    valBalaSum: document.getElementById('val-bala-sum'),
    valSalesSum: document.getElementById('val-sales-sum'),
    valCommissionSum: document.getElementById('val-commission-sum'),
    valBagsSum: document.getElementById('val-bags-sum'),
    formsCountBadge: document.getElementById('forms-count-badge'),
    valFormsSum: document.getElementById('val-forms-sum'),
    valGrandSum: document.getElementById('val-grand-sum'),
    shiftPeriodText: document.getElementById('shift-period-text'),

    // Section 2: Cash & Debts Totals
    valCashSum: document.getElementById('val-cash-sum'),
    valDebtsSum: document.getElementById('val-debts-sum'),
    valCashDebtsSum: document.getElementById('val-cash-debts-sum'),

    // Section 3: Audit Matching Verification
    auditMatchBanner: document.getElementById('audit-match-banner'),
    auditMatchIcon: document.getElementById('audit-match-icon'),
    auditMatchText: document.getElementById('audit-match-text'),
    auditMatchDiff: document.getElementById('audit-match-diff'),

    // Print elements
    printShiftPeriod: document.getElementById('print-shift-period'),
    printBalaSum: document.getElementById('print-bala-sum'),
    printSalesSum: document.getElementById('print-sales-sum'),
    printCommSum: document.getElementById('print-comm-sum'),
    printBagsSum: document.getElementById('print-bags-sum'),
    printFormsSum: document.getElementById('print-forms-sum'),
    printGrandSum: document.getElementById('print-grand-sum'),
    printCashSum: document.getElementById('print-cash-sum'),
    printDebtsSum: document.getElementById('print-debts-sum'),
    printCashDebtsSum: document.getElementById('print-cash-debts-sum'),
    printAuditStatus: document.getElementById('print-audit-status'),

    // Detail Tables
    salesTbody: document.getElementById('sales-tbody'),
    balaTbody: document.getElementById('bala-tbody'),
    commTbody: document.getElementById('comm-tbody'),
    bagsTbody: document.getElementById('bags-tbody'),

    // Toast Container
    toastContainer: document.getElementById('toast-container')
};

let lastStates = {};
function checkSystemStateAndRefresh(targetTables, refreshCallback) {
    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                let hasChanges = false;
                targetTables.forEach(t => {
                    const newTs = res.states[t] || 0;
                    if (lastStates[t] !== undefined && lastStates[t] !== newTs) {
                        hasChanges = true;
                    }
                    lastStates[t] = newTs;
                });
                if (hasChanges) {
                    refreshCallback();
                }
            }
        })
        .catch(err => console.error("Error checking states:", err));
}

document.addEventListener('DOMContentLoaded', () => {
    fetchShiftCalibration();

    fetch('api/check_state.php?_t=' + Date.now())
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success' && res.states) {
                lastStates = res.states;
            }
        }).catch(() => {});

    setInterval(() => {
        checkSystemStateAndRefresh(['forms', 'safe_transactions', 'calibrations'], fetchShiftCalibration);
    }, 3000);
});

function fetchShiftCalibration() {
    fetch('api/calibration.php?action=shift_calibration')
        .then(res => res.json())
        .then(res => {
            if (res.status === 'success') {
                shiftData = res;
                renderShiftCalibration();
            } else {
                showToast(res.message || 'حدث خطأ في تحميل بيانات الوردية', 'error');
            }
        })
        .catch(err => {
            console.error(err);
            showToast('فشل الاتصال بالخادم لجلب كشف معايرة الوردية الحالية', 'error');
        });
}

function renderShiftCalibration() {
    if (!shiftData) return;

    const calib = shiftData.calibration || {};
    const info = shiftData.shift_info || {};
    const details = shiftData.details || {};

    // Format Shift Time Text
    const sStart = formatDateDisplay(info.shift_start);
    const sEnd = formatDateDisplay(info.shift_end);
    const shiftText = `الوردية الحالية: من ${sStart} إلى ${sEnd}`;

    if (dom.shiftPeriodText) dom.shiftPeriodText.textContent = shiftText;
    if (dom.printShiftPeriod) dom.printShiftPeriod.textContent = shiftText;

    // 1. Populate Section 1: Revenue Totals
    if (dom.valBalaSum) dom.valBalaSum.textContent = formatCurrency(calib.bala_total);
    if (dom.valSalesSum) dom.valSalesSum.textContent = formatCurrency(calib.sales_total);
    if (dom.valCommissionSum) dom.valCommissionSum.textContent = formatCurrency(calib.percentage_commission_total);
    if (dom.valBagsSum) dom.valBagsSum.textContent = formatCurrency(calib.bags_commission_total);
    if (dom.formsCountBadge) dom.formsCountBadge.textContent = calib.forms_count || 0;
    if (dom.valFormsSum) dom.valFormsSum.textContent = formatCurrency(calib.forms_fee_total);
    if (dom.valGrandSum) dom.valGrandSum.textContent = formatCurrency(calib.grand_total);

    // 2. Populate Section 2: Cash & Debts Totals
    if (dom.valCashSum) dom.valCashSum.textContent = formatCurrency(calib.shift_cash_total);
    if (dom.valDebtsSum) dom.valDebtsSum.textContent = formatCurrency(calib.shift_debts_total);
    if (dom.valCashDebtsSum) dom.valCashDebtsSum.textContent = formatCurrency(calib.cash_debts_sum);

    // 3. Populate Section 3: Audit Matching Verification Status
    const isMatching = calib.is_matching;
    const diff = calib.difference || 0;

    if (dom.auditMatchBanner) {
        if (isMatching) {
            dom.auditMatchBanner.className = 'audit-match-banner matching';
            if (dom.auditMatchIcon) dom.auditMatchIcon.className = 'fa-solid fa-circle-check';
            if (dom.auditMatchText) dom.auditMatchText.textContent = 'المعايرة مطابقة صحيحة 100% (مجموع النقدي والديون مساوٍ لمجموع مستحقات الوردية)';
            if (dom.auditMatchDiff) dom.auditMatchDiff.textContent = 'الفرق: 0.00 د.ع';
        } else {
            dom.auditMatchBanner.className = 'audit-match-banner mismatch';
            if (dom.auditMatchIcon) dom.auditMatchIcon.className = 'fa-solid fa-circle-xmark';
            if (dom.auditMatchText) dom.auditMatchText.textContent = 'يوجد تباين/فرق في المعايرة بين مجموع النقدي والديون ومجموع مستحقات الوردية';
            if (dom.auditMatchDiff) dom.auditMatchDiff.textContent = `الفرق: ${formatCurrency(Math.abs(diff))}`;
        }
    }

    // Print template
    if (dom.printBalaSum) dom.printBalaSum.textContent = formatCurrency(calib.bala_total);
    if (dom.printSalesSum) dom.printSalesSum.textContent = formatCurrency(calib.sales_total);
    if (dom.printCommSum) dom.printCommSum.textContent = formatCurrency(calib.percentage_commission_total);
    if (dom.printBagsSum) dom.printBagsSum.textContent = formatCurrency(calib.bags_commission_total);
    if (dom.printFormsSum) dom.printFormsSum.textContent = `${formatCurrency(calib.forms_fee_total)} (${calib.forms_count} استمارة × 1000)`;
    if (dom.printGrandSum) dom.printGrandSum.textContent = formatCurrency(calib.grand_total);
    
    if (dom.printCashSum) dom.printCashSum.textContent = formatCurrency(calib.shift_cash_total);
    if (dom.printDebtsSum) dom.printDebtsSum.textContent = formatCurrency(calib.shift_debts_total);
    if (dom.printCashDebtsSum) dom.printCashDebtsSum.textContent = formatCurrency(calib.cash_debts_sum);

    if (dom.printAuditStatus) {
        if (isMatching) {
            dom.printAuditStatus.style.background = '#dcfce7';
            dom.printAuditStatus.style.borderColor = '#16a34a';
            dom.printAuditStatus.style.color = '#15803d';
            dom.printAuditStatus.textContent = '✅ المعايرة مطابقة صحيحة 100% (مجموع النقدي والديون مساوٍ لمجموع مستحقات الوردية)';
        } else {
            dom.printAuditStatus.style.background = '#fee2e2';
            dom.printAuditStatus.style.borderColor = '#dc2626';
            dom.printAuditStatus.style.color = '#b91c1c';
            dom.printAuditStatus.textContent = `⚠️ يوجد فرق في المعايرة (الفرق = ${formatCurrency(Math.abs(diff))})`;
        }
    }

    // Populate Detail Tables
    renderSalesTable(details.sales_items || []);
    renderBalaTable(details.bala_items || []);
    renderCommTable(details.commission_items || []);
    renderBagsTable(details.bags_items || []);
}

function renderSalesTable(items) {
    if (!dom.salesTbody) return;
    if (items.length === 0) {
        dom.salesTbody.innerHTML = '<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:20px;">لا تتوفر أصناف مبياع في الوردية الحالية</td></tr>';
        return;
    }

    let html = '';
    items.forEach((item, idx) => {
        html += `
            <tr>
                <td>${idx + 1}</td>
                <td><strong style="color:var(--primary);">#${item.form_id}</strong></td>
                <td><strong>${escapeHtml(item.item_name)}</strong></td>
                <td>${escapeHtml(item.customer_name || '-')}</td>
                <td>${item.quantity}</td>
                <td>${item.weight} كجم</td>
                <td>${formatCurrency(item.price)}</td>
                <td><strong style="color:#10b981;">${formatCurrency(item.item_value)}</strong></td>
            </tr>
        `;
    });
    dom.salesTbody.innerHTML = html;
}

function renderBalaTable(items) {
    if (!dom.balaTbody) return;
    if (items.length === 0) {
        dom.balaTbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:var(--text-muted); padding:20px;">لا تتوفر أصناف بلا في الوردية الحالية</td></tr>';
        return;
    }

    let html = '';
    items.forEach((item, idx) => {
        html += `
            <tr>
                <td>${idx + 1}</td>
                <td><strong style="color:var(--primary);">#${item.form_id}</strong></td>
                <td><strong>${escapeHtml(item.item_name)}</strong></td>
                <td>${escapeHtml(item.customer_name || '-')}</td>
                <td>${item.quantity}</td>
                <td>${formatCurrency(item.price)}</td>
                <td><strong style="color:#8b5cf6;">${formatCurrency(item.item_value)}</strong></td>
            </tr>
        `;
    });
    dom.balaTbody.innerHTML = html;
}

function renderCommTable(items) {
    if (!dom.commTbody) return;
    if (items.length === 0) {
        dom.commTbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:20px;">لا تتوفر عمولات مئوية في الوردية الحالية</td></tr>';
        return;
    }

    let html = '';
    items.forEach((item, idx) => {
        html += `
            <tr>
                <td>${idx + 1}</td>
                <td><strong style="color:var(--primary);">#${item.form_id}</strong></td>
                <td><strong>${escapeHtml(item.item_name)}</strong></td>
                <td>${escapeHtml(item.customer_name || '-')}</td>
                <td>${formatCurrency(item.item_value)}</td>
                <td><strong style="color:#f59e0b;">${formatCurrency(item.commission_10)}</strong></td>
            </tr>
        `;
    });
    dom.commTbody.innerHTML = html;
}

function renderBagsTable(items) {
    if (!dom.bagsTbody) return;
    if (items.length === 0) {
        dom.bagsTbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--text-muted); padding:20px;">لا تتوفر عمولات أكياس في الوردية الحالية</td></tr>';
        return;
    }

    let html = '';
    items.forEach((item, idx) => {
        html += `
            <tr>
                <td>${idx + 1}</td>
                <td><strong style="color:var(--primary);">#${item.form_id}</strong></td>
                <td><strong>${escapeHtml(item.item_name)}</strong></td>
                <td>${escapeHtml(item.customer_name || '-')}</td>
                <td>${item.quantity}</td>
                <td><strong style="color:#ec4899;">${formatCurrency(item.commission)}</strong></td>
            </tr>
        `;
    });
    dom.bagsTbody.innerHTML = html;
}

function switchTab(tabId) {
    document.querySelectorAll('.tab-btn').forEach(btn => {
        if (btn.getAttribute('data-tab') === tabId) {
            btn.classList.add('active', 'btn-primary');
            btn.classList.remove('btn-secondary-outline');
        } else {
            btn.classList.remove('active', 'btn-primary');
            btn.classList.add('btn-secondary-outline');
        }
    });

    document.querySelectorAll('.tab-content').forEach(content => {
        content.style.display = content.id === tabId ? 'block' : 'none';
    });
}

function printCalibration() {
    const printContent = document.getElementById('print-area').innerHTML;
    const printWindow = window.open('', '', 'height=750,width=900');
    printWindow.document.write('<html><head><title>كشف معايرة ومطابقة الوردية الحالية</title>');
    printWindow.document.write('<link href="css/cairo.css" rel="stylesheet">');
    printWindow.document.write('</head><body>');
    printWindow.document.write(printContent);
    printWindow.document.write('</body></html>');
    printWindow.document.close();
    printWindow.focus();
    setTimeout(() => {
        printWindow.print();
        printWindow.close();
    }, 500);
}

function exportExcel() {
    if (!shiftData) return;
    const calib = shiftData.calibration || {};
    
    let csv = '\uFEFF';
    csv += 'بند الكشف والمعايرة للوردية الحالية,المبلغ (د.ع)\n';
    csv += `"أولاً: إيرادات ومستحقات الوردية",""\n`;
    csv += `"بلا (مجموع)","${calib.bala_total}"\n`;
    csv += `"مبياع (مجموع)","${calib.sales_total}"\n`;
    csv += `"عمولة مئوية (10% / 20% أو أكثر/أقل - مجموع)","${calib.percentage_commission_total}"\n`;
    csv += `"أكياس (مجموع العمولات الثابتة)","${calib.bags_commission_total}"\n`;
    csv += `"عدد الاستمارات مضروب في 1000 (${calib.forms_count} استمارة)","${calib.forms_fee_total}"\n`;
    csv += `-----------------------------------,-------------------\n`;
    csv += `"مجموع ما سبق (إجمالي مستحقات الوردية)","${calib.grand_total}"\n`;
    csv += `"\n",""\n`;
    csv += `"ثانياً: التحصيل والمطابقة",""\n`;
    csv += `"مجموع النقدي","${calib.shift_cash_total}"\n`;
    csv += `"مجموع الديون","${calib.shift_debts_total}"\n`;
    csv += `-----------------------------------,-------------------\n`;
    csv += `"المجموع (النقدي + الديون)","${calib.cash_debts_sum}"\n`;
    csv += `"\n",""\n`;
    const statusStr = calib.is_matching ? 'مطابقة صحيحة 100%' : `غير مطابقة (الفرق: ${calib.difference})`;
    csv += `"حالة مطابقة المعايرة","${statusStr}"\n`;

    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `كشف_معايرة_ومطابقة_الوردية_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
}

function formatCurrency(amount) {
    if (isNaN(amount) || amount === null) return '0.00 د.ع';
    return Number(amount).toLocaleString('ar-IQ', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + ' د.ع';
}

function formatDateDisplay(dateStr) {
    if (!dateStr) return '';
    try {
        const d = new Date(dateStr);
        return d.toLocaleString('ar-IQ', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
    } catch(e) {
        return dateStr;
    }
}

function showToast(message, type = 'success') {
    if (!dom.toastContainer) return;
    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.style.cssText = `
        padding: 12px 20px;
        border-radius: 8px;
        color: white;
        font-weight: 600;
        font-size: 14px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
        display: flex;
        align-items: center;
        gap: 8px;
        background: ${type === 'success' ? '#10b981' : '#ef4444'};
    `;
    toast.innerHTML = `<i class="fa-solid ${type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle'}"></i> ${escapeHtml(message)}`;
    dom.toastContainer.appendChild(toast);
    setTimeout(() => {
        toast.remove();
    }, 3500);
}

function escapeHtml(str) {
    if (!str) return '';
    return String(str)
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#039;');
}

