// external_stations.js

// Global variables for external stations
let currentExternalStations = [];
let currentExtCementDeliveries = [];
let currentExtConcretePurchases = [];

// Initialize External Stations View
window.renderExternalStations = async function() {
    try {
        // Auto-fix missing account codes
        const allAccs = await window.DB.getAll('accounts') || [];
        let needsUpdate = false;
        for (let a of allAccs) {
            if (!a.code) {
                a.code = Date.now().toString().slice(-6) + Math.floor(Math.random()*100);
                await window.DB.update('accounts', a);
                needsUpdate = true;
            }
        }
        if (needsUpdate && window.loadData) await window.loadData(false);

        const allTransactions = await window.DB.getAll('transactions') || [];
        const allContacts = await window.DB.getAll('contacts') || [];
        const allProjects = await window.DB.getAll('projects') || [];
        
        // Fetch transactions first
        currentExtCementDeliveries = allTransactions.filter(t => t.type === 'ext_cement_delivery');
        currentExtConcretePurchases = allTransactions.filter(t => t.type === 'ext_concrete_purchase');

        // Fetch external stations (Suppliers with tag OR those who have relevant transactions)
        currentExternalStations = allContacts.filter(c => {
            if (c.type !== 'مورد') return false;
            if ((c.tag || '').includes('محطة خرسانة خارجية')) return true;
            if (currentExtConcretePurchases.some(t => String(t.contact_id) === String(c.id))) return true;
            if (currentExtCementDeliveries.some(t => String(t.contact_id) === String(c.id))) return true;
            return false;
        });
        currentExtCementDeliveries = allTransactions.filter(t => t.type === 'ext_cement_delivery');
        currentExtConcretePurchases = allTransactions.filter(t => t.type === 'ext_concrete_purchase');

        const tbody = document.getElementById('ext-stations-tbody');
        if (!tbody) return;
        
        tbody.innerHTML = '';
        
        if (currentExternalStations.length === 0) {
            tbody.innerHTML = '<tr><td colspan="6" style="text-align:center;">لا توجد محطات خارجية مسجلة</td></tr>';
            return;
        }

        currentExternalStations.forEach(station => {
            // Calculate totals for this station
            const deliveries = currentExtCementDeliveries.filter(t => String(t.contact_id) === String(station.id));
            const purchases = currentExtConcretePurchases.filter(t => String(t.contact_id) === String(station.id));

            let totalCementDeliveredQty = 0;
            let totalCementDeliveredValue = 0;
            deliveries.forEach(d => {
                if(d.items) {
                    d.items.forEach(item => {
                        totalCementDeliveredQty += parseFloat(item.qty) || 0;
                    });
                }
                totalCementDeliveredValue += parseFloat(d.total) || 0;
            });

            let totalConcreteQty = 0;
            let totalConcreteValue = 0;
            let totalConsumedCement = 0;
            purchases.forEach(p => {
                if(p.items) {
                    p.items.forEach(item => {
                        totalConcreteQty += parseFloat(item.qty) || 0;
                    });
                } else {
                    totalConcreteQty += parseFloat(p.qty) || 0;
                }
                totalConcreteValue += parseFloat(p.total) || 0;
                totalConsumedCement += parseFloat(p.cement_used) || 0;
            });
            
            let totalCementQty = totalCementDeliveredQty - totalConsumedCement;
            let averageCementPrice = totalCementDeliveredQty > 0 ? (totalCementDeliveredValue / totalCementDeliveredQty) : 0;
            let totalCementValue = totalCementQty * averageCementPrice;

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td><strong>${station.name}</strong></td>
                <td style="color:#2e7d32;">${totalCementQty.toLocaleString()} طن</td>
                <td style="color:#2e7d32;">${totalCementValue.toLocaleString()} ج.م.</td>
                <td style="color:#1565c0;">${totalConcreteQty.toLocaleString()} م³</td>
                <td style="color:#1565c0;">${totalConcreteValue.toLocaleString()} ج.م.</td>
                <td>
                    <button class="action-btn btn-view" onclick="viewExternalStationDetails('${station.id}')"><i class="fas fa-eye"></i> التفاصيل</button>
                    <button class="action-btn" style="background:#ff6f00; color:white;" onclick="openExtStationReport('${station.id}')"><i class="fas fa-chart-bar"></i> تقرير</button>
                    <button class="action-btn" style="background:#4caf50; color:white;" onclick="openExtCementModal(null, '${station.id}')"><i class="fas fa-truck"></i> توريد أسمنت</button>
                    <button class="action-btn" style="background:#2196f3; color:white;" onclick="openExtConcreteModal(null, '${station.id}')"><i class="fas fa-cubes"></i> شراء خرسانة</button>
                    <button class="action-btn" style="background:#9c27b0; color:white;" onclick="openExtAgreementsModal('${station.id}', '${station.name}')"><i class="fas fa-file-contract"></i> الاتفاقات</button>
                </td>
            `;
            tbody.appendChild(tr);
        });

    } catch (e) {
        console.error("Error rendering external stations:", e);
    }
};

window.openExtStationModal = function() {
    document.getElementById('ext-station-name').value = '';
    document.getElementById('ext-station-phone').value = '';
    document.getElementById('ext-station-modal').classList.add('active');
};

window.saveExtStation = async function() {
    const name = document.getElementById('ext-station-name').value.trim();
    const phone = document.getElementById('ext-station-phone').value.trim();
    
    if (!name) {
        alert("يرجى إدخال اسم المحطة");
        return;
    }
    
    const newStation = {
        id: Date.now(),
        name: name,
        phone: phone,
        type: 'مورد',
        tag: 'محطة خرسانة خارجية'
    };
    
    try {
        await window.DB.add('contacts', newStation);
        document.getElementById('ext-station-modal').classList.remove('active');
        window.renderExternalStations();
        if(window.renderContacts) window.renderContacts(); // Update contacts view if exists
        alert("تم حفظ المحطة بنجاح");
    } catch(e) {
        alert("خطأ أثناء الحفظ");
    }
};

// ================= CEMENT DELIVERY =================

window.openExtCementModal = async function(id = null, stationId = null) {
    document.getElementById('ext-cement-id').value = id || '';
    document.getElementById('ext-cement-date').value = new Date().toISOString().split('T')[0];
    const defaultTax = localStorage.getItem('defaultExtTax') || '';
    document.getElementById('ext-cement-tax').value = defaultTax;
    const attachmentInput = document.getElementById('ext-cement-attachment');
    if (attachmentInput) attachmentInput.value = '';
    
    // Populate stations
    const stationSelect = document.getElementById('ext-cement-station');
    stationSelect.innerHTML = '<option value="">اختر المحطة...</option>';
    currentExternalStations.forEach(s => {
        stationSelect.innerHTML += `<option value="${s.id}">${s.name}</option>`;
    });
    
    if (stationId) {
        stationSelect.value = stationId;
    }

    // Populate projects
    const projectSelect = document.getElementById('ext-cement-project');
    const projects = await window.DB.getAll('projects') || [];
    projectSelect.innerHTML = '<option value="">اختر المشروع...</option>';
    projects.forEach(p => {
        projectSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`;
    });

    // Populate suppliers
    const supplierSelect = document.getElementById('ext-cement-supplier');
    if (supplierSelect) {
        const allContacts = await window.DB.getAll('contacts') || [];
        const suppliers = allContacts.filter(c => c.type === 'مورد' || c.type === 'عميل/مورد');
        supplierSelect.innerHTML = '<option value="">-- اختر المورد (اختياري) --</option>';
        suppliers.forEach(s => {
            supplierSelect.innerHTML += `<option value="${s.id}">${s.name}</option>`;
        });
        supplierSelect.value = '';
    }
    
    document.getElementById('ext-cement-qty').value = '';
    document.getElementById('ext-cement-price').value = '';
    document.getElementById('ext-cement-total').innerText = '0 ج.م.';
    document.getElementById('ext-cement-notes').value = '';
    
    // Payment method
    document.getElementById('ext-cement-payment').value = 'cash';
    
    document.getElementById('ext-cement-modal').classList.add('active');
};

window.calcExtCementTotal = function() {
    const qty = parseFloat(document.getElementById('ext-cement-qty').value) || 0;
    const price = parseFloat(document.getElementById('ext-cement-price').value) || 0;
    const taxPercent = parseFloat(document.getElementById('ext-cement-tax').value) || 0;
    
    // Save preference
    if (taxPercent > 0) localStorage.setItem('defaultExtTax', taxPercent);
    else localStorage.removeItem('defaultExtTax');

    const subtotal = qty * price;
    const taxAmount = subtotal * (taxPercent / 100);
    const total = subtotal + taxAmount;
    
    document.getElementById('ext-cement-total').innerText = total.toLocaleString() + ' ج.م.';
    if (taxAmount > 0) {
        document.getElementById('ext-cement-total').innerText += ` (شامل ضريبة: ${taxAmount.toLocaleString()})`;
    }
};

window.saveExtCementDelivery = async function() {
    const stationId = document.getElementById('ext-cement-station').value;
    const projectId = document.getElementById('ext-cement-project').value;
    const date = document.getElementById('ext-cement-date').value;
    const qty = parseFloat(document.getElementById('ext-cement-qty').value) || 0;
    const price = parseFloat(document.getElementById('ext-cement-price').value) || 0;
    const notes = document.getElementById('ext-cement-notes').value;
    const paymentType = document.getElementById('ext-cement-payment').value;
    const taxPercent = parseFloat(document.getElementById('ext-cement-tax') ? document.getElementById('ext-cement-tax').value : 0) || 0;
    const supplierSelect = document.getElementById('ext-cement-supplier');
    const supplier_id = supplierSelect ? supplierSelect.value : '';
    const attachmentInput = document.getElementById('ext-cement-attachment');
    let attachmentBase64 = null;
    
    if (!stationId || !projectId || qty <= 0 || price <= 0) {
        alert("يرجى إكمال جميع الحقول المطلوبة (المحطة، المشروع، الكمية، السعر).");
        return;
    }
    
    // Read file if provided
    if (attachmentInput && attachmentInput.files && attachmentInput.files[0]) {
        try {
            attachmentBase64 = await new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(attachmentInput.files[0]);
            });
        } catch (err) {
            console.error("Error reading attachment:", err);
            alert("فشل قراءة المرفق");
            return;
        }
    }
    
    const subtotal = qty * price;
    const tax_amount = subtotal * (taxPercent / 100);
    const total = subtotal + tax_amount;
    
    const transaction = {
        id: Date.now(),
        type: 'ext_cement_delivery',
        date: date,
        contact_id: stationId,
        supplier_id: supplier_id,
        project_id: projectId,
        payment_type: paymentType,
        items: [
            { item_name: 'أسمنت', qty: qty, price: price }
        ],
        tax_rate: taxPercent,
        tax_amount: tax_amount,
        subtotal: subtotal,
        tax_rate: taxPercent,
        tax_amount: tax_amount,
        subtotal: subtotal,
        total: total,
        notes: notes,
        attachment: attachmentBase64,
        status: 'posted',
        created_at: new Date().toISOString()
    };
    
    try {
        await window.DB.add('transactions', transaction);
        
        // Generate Accounting Journal Entry
        await generateExtCementJournal(transaction);
        
        document.getElementById('ext-cement-modal').classList.remove('active');
        window.renderExternalStations();
        if(window.viewExternalStationDetails && document.getElementById('ext-station-details-modal').classList.contains('active')) {
            window.viewExternalStationDetails(stationId);
        }
    } catch(e) {
        console.error(e);
        alert("خطأ أثناء الحفظ");
    }
};

async function generateExtCementJournal(t) {
    if(!window.DB) return;
    const accounts = await window.DB.getAll('accounts') || [];
    const allContacts = await window.DB.getAll('contacts') || [];
    const station = allContacts.find(c => String(c.id) === String(t.contact_id));
    const stationName = station ? station.name : 'خارجية';
    let supplierName = '';
    if (t.supplier_id && String(t.supplier_id) !== String(t.contact_id)) {
        const supplier = allContacts.find(c => String(c.id) === String(t.supplier_id));
        if (supplier) supplierName = ` (مورد: ${supplier.name})`;
    }
    
    // Find or create "عهدة أسمنت محطات خارجية" (Debit - Assets)
    let costAcc = accounts.find(a => a.name === 'عهدة أسمنت محطات خارجية' || a.name === 'عهدة أسمنت محطات');
    if(!costAcc && typeof window.resolveSystemAccount === 'function') {
        costAcc = await window.resolveSystemAccount('عهدة أسمنت محطات خارجية', ['أصول متداولة', 'أصول'], 'assets');
    }
    // Fallback if not found
    if(!costAcc) costAcc = { id: Date.now() + 1, name: 'عهدة أسمنت محطات خارجية', type: 'أصول' };
    
    // Find Credit Account based on payment type
    let creditAcc;
    let supplierIdForContact = null;
    
    if (t.payment_type === 'cash') {
        creditAcc = accounts.find(a => a.name === 'الخزينة' || a.name === 'خزينة' || a.name === 'الصندوق الرئيسية');
        if(!creditAcc && typeof window.resolveSystemAccount === 'function') {
            creditAcc = await window.resolveSystemAccount('الخزينة', ['أصول', 'نقدية'], 'assets');
        }
        if(!creditAcc) creditAcc = { id: Date.now() + 2, name: 'الخزينة', type: 'أصول' };
    } else {
        // Supplier Account (Ajel) -> General Suppliers Account
        const realSupplierId = t.supplier_id ? t.supplier_id : t.contact_id;
        supplierIdForContact = realSupplierId;
        
        creditAcc = accounts.find(a => a.name.includes('الموردين') || a.name.includes('موردين'));
        if(!creditAcc && typeof window.resolveSystemAccount === 'function') {
            creditAcc = await window.resolveSystemAccount('الموردين', ['التزامات', 'خصوم', 'متداولة'], 'liabilities');
        }
        if(!creditAcc) creditAcc = { id: Date.now() + 3, name: 'الموردين', type: 'خصوم' };
    }

    let taxAcc = null;
    const taxAmount = t.tax_amount || 0;
    if (taxAmount > 0) {
        if (typeof window.resolveSystemAccount === 'function') {
            taxAcc = await window.resolveSystemAccount('ضريبة القيمة المضافة', ['ضريبة', 'ضرائب'], 'assets');
        } else {
            taxAcc = accounts.find(a => a.name.includes('ضريبة القيمة المضافة')) || { id: Date.now() + 5, name: 'ضريبة القيمة المضافة' };
        }
    }

    const costAmount = t.total - taxAmount; // Because t.total now includes tax
    const journalRows = [];
    journalRows.push({ account_id: costAcc.id, debit: costAmount, credit: 0, project_id: t.project_id, contact_id: t.contact_id, desc: `عهدة أسمنت لمحطة ${stationName}` });
    
    if (taxAmount > 0 && taxAcc) {
        journalRows.push({ account_id: taxAcc.id, debit: taxAmount, credit: 0, contact_id: supplierIdForContact, desc: `ضريبة مشتريات أسمنت لمحطة ${stationName}` });
    }
    
    journalRows.push({ account_id: creditAcc.id, debit: 0, credit: t.total, contact_id: supplierIdForContact, desc: 'دفع قيمة الأسمنت' + (taxAmount > 0 ? ' (شامل الضريبة)' : '') });

    const journal = {
        id: Date.now() + 4,
        date: t.date,
        reference: `توريد أسمنت #${t.id}`,
        desc: `شراء وتوريد أسمنت لمحطة ${stationName}${supplierName} - فاتورة #${t.id} ${t.notes ? ' - ' + t.notes : ''}`,
        source: `ext_cement_${t.id}`,
        status: 'posted',
        total: t.total,
        rows: journalRows
    };
    
    await window.DB.add('journal_entries', journal);
}

// ================= CONCRETE PURCHASE =================



window.openExtConcreteModal = async function(id = null, stationId = null) {
    document.getElementById('ext-concrete-id').value = id || '';
    document.getElementById('ext-concrete-date').value = new Date().toISOString().split('T')[0];
    const defaultTax = localStorage.getItem('defaultExtTax') || '';
    document.getElementById('ext-concrete-tax').value = defaultTax;
    
    // Populate stations
    const stationSelect = document.getElementById('ext-concrete-station');
    stationSelect.innerHTML = '<option value="">اختر المحطة...</option>';
    currentExternalStations.forEach(s => {
        stationSelect.innerHTML += `<option value="${s.id}">${s.name}</option>`;
    });
    
    if (stationId) {
        stationSelect.value = stationId;
        if (window.populateExtConcreteTypes) await window.populateExtConcreteTypes();
    } else {
        document.getElementById('ext-concrete-type').innerHTML = '<option value="">اختر الرتبة...</option>';
    }

    // Populate projects
    const projectSelect = document.getElementById('ext-concrete-project');
    const projects = await window.DB.getAll('projects') || [];
    projectSelect.innerHTML = '<option value="">اختر المشروع...</option>';
    projects.forEach(p => {
        projectSelect.innerHTML += `<option value="${p.id}">${p.name}</option>`;
    });

    document.getElementById('ext-concrete-type').value = '';
    document.getElementById('ext-concrete-qty').value = '';
    document.getElementById('ext-concrete-price').value = '';
    document.getElementById('ext-concrete-total').innerText = '0 ج.م.';
    document.getElementById('ext-concrete-notes').value = '';
    const attachmentInput = document.getElementById('ext-concrete-attachment');
    if (attachmentInput) attachmentInput.value = '';
    
    // Payment method
    document.getElementById('ext-concrete-payment').value = 'cash';
    
    document.getElementById('ext-concrete-modal').classList.add('active');
};

window.calcExtConcreteTotal = function() {
    const qty = parseFloat(document.getElementById('ext-concrete-qty').value) || 0;
    const price = parseFloat(document.getElementById('ext-concrete-price').value) || 0;
    document.getElementById('ext-concrete-total').innerText = (qty * price).toLocaleString() + ' ج.م.';
    
    // Auto-calculate cement used based on selected grade
    const typeSelect = document.getElementById('ext-concrete-type');
    const selectedOption = typeSelect.options[typeSelect.selectedIndex];
    if (selectedOption && selectedOption.dataset.cement) {
        const cementContentKg = parseFloat(selectedOption.dataset.cement) || 0;
        const totalCementKg = cementContentKg * qty;
        const totalCementTon = totalCementKg / 1000;
        document.getElementById('ext-concrete-cement-used').value = totalCementTon.toFixed(2);
    }
};

window.saveExtConcretePurchase = async function() {
    const stationId = document.getElementById('ext-concrete-station').value;
    const projectId = document.getElementById('ext-concrete-project').value;
    const date = document.getElementById('ext-concrete-date').value;
    const type = document.getElementById('ext-concrete-type').value.trim();
    const qty = parseFloat(document.getElementById('ext-concrete-qty').value) || 0;
    const price = parseFloat(document.getElementById('ext-concrete-price').value) || 0;
    const cementUsed = parseFloat(document.getElementById('ext-concrete-cement-used').value) || 0;
    const notes = document.getElementById('ext-concrete-notes').value;
    const paymentType = document.getElementById('ext-concrete-payment').value;
    const taxPercent = parseFloat(document.getElementById('ext-concrete-tax') ? document.getElementById('ext-concrete-tax').value : 0) || 0;
    const attachmentInput = document.getElementById('ext-concrete-attachment');
    let attachmentBase64 = null;
    
    if (!stationId || !projectId || !type || qty <= 0 || price <= 0) {
        alert("يرجى إكمال جميع الحقول المطلوبة (المحطة، المشروع، الرتبة، الكمية، السعر).");
        return;
    }
    
    if (attachmentInput && attachmentInput.files && attachmentInput.files[0]) {
        try {
            attachmentBase64 = await new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(attachmentInput.files[0]);
            });
        } catch (err) {
            console.error("Error reading attachment:", err);
            alert("فشل قراءة المرفق");
            return;
        }
    }
    
    const subtotal = qty * price;
    const tax_amount = subtotal * (taxPercent / 100);
    const total = subtotal + tax_amount;
    
    const transaction = {
        id: Date.now(),
        type: 'ext_concrete_purchase',
        date: date,
        contact_id: stationId,
        project_id: projectId,
        payment_type: paymentType,
        concrete_type: type,
        qty: qty,
        price: price,
        cement_used: cementUsed,
        tax_rate: taxPercent,
        tax_amount: tax_amount,
        subtotal: subtotal,
        total: total,
        notes: notes,
        attachment: attachmentBase64,
        status: 'posted',
        created_at: new Date().toISOString()
    };
    
    try {
        await window.DB.add('transactions', transaction);
        
        // Generate Accounting Journal Entry
        await generateExtConcreteJournal(transaction);
        
        document.getElementById('ext-concrete-modal').classList.remove('active');
        window.renderExternalStations();
        if(window.viewExternalStationDetails && document.getElementById('ext-station-details-modal').classList.contains('active')) {
            window.viewExternalStationDetails(stationId);
        }
    } catch(e) {
        console.error(e);
        alert("خطأ أثناء الحفظ");
    }
};

async function generateExtConcreteJournal(t) {
    if(!window.DB) return;
    const accounts = await window.DB.getAll('accounts') || [];
    const allContacts = await window.DB.getAll('contacts') || [];
    const station = allContacts.find(c => String(c.id) === String(t.contact_id));
    const stationName = station ? station.name : 'خارجية';
    
    // Find or create "تكلفة خرسانة جاهزة - مشاريع" (Debit)
    let costAcc = accounts.find(a => a.name === 'تكلفة خرسانة جاهزة - مشاريع');
    if(!costAcc && typeof window.resolveSystemAccount === 'function') {
        costAcc = await window.resolveSystemAccount('تكلفة خرسانة جاهزة - مشاريع', ['مصروفات', 'تكاليف'], 'expenses');
    }
    if(!costAcc) costAcc = { id: Date.now() + 1, name: 'تكلفة خرسانة جاهزة - مشاريع', type: 'مصروفات' };
    
    // Find Credit Account based on payment type
    let creditAcc;
    if (t.payment_type === 'cash') {
        creditAcc = accounts.find(a => a.name === 'الخزينة' || a.name === 'خزينة' || a.name === 'الصندوق الرئيسية');
        if(!creditAcc && typeof window.resolveSystemAccount === 'function') {
            creditAcc = await window.resolveSystemAccount('الخزينة', ['أصول', 'نقدية'], 'assets');
        }
        if(!creditAcc) creditAcc = { id: Date.now() + 2, name: 'الخزينة', type: 'أصول' };
    } else {
        // Supplier Account (Ajel) -> General Suppliers Account
        creditAcc = accounts.find(a => a.name.includes('الموردين') || a.name.includes('موردين'));
        if(!creditAcc && typeof window.resolveSystemAccount === 'function') {
            creditAcc = await window.resolveSystemAccount('الموردين', ['التزامات', 'خصوم', 'متداولة'], 'liabilities');
        }
        if(!creditAcc) creditAcc = { id: Date.now() + 3, name: 'الموردين', type: 'خصوم' };
    }

    // Now for Cement Consumption (if any)
    let cementConsumedValue = 0;
    if (t.cement_used > 0) {
        const transactions = await window.DB.getAll('transactions') || [];
        const deliveries = transactions.filter(tr => tr.type === 'ext_cement_delivery' && String(tr.contact_id) === String(t.contact_id));
        let totalCementDeliveredQty = 0;
        let totalCementDeliveredValue = 0;
        deliveries.forEach(d => {
            if(d.items) {
                d.items.forEach(item => totalCementDeliveredQty += parseFloat(item.qty) || 0);
            }
            totalCementDeliveredValue += parseFloat(d.total) || 0;
        });
        const avgPrice = totalCementDeliveredQty > 0 ? (totalCementDeliveredValue / totalCementDeliveredQty) : 0;
        cementConsumedValue = parseFloat((t.cement_used * avgPrice).toFixed(2));
    }

    let cementCostAcc, cementAssetAcc;
    if (cementConsumedValue > 0) {
        cementCostAcc = accounts.find(a => a.name === 'تكلفة مواد - مشاريع');
        if(!cementCostAcc && typeof window.resolveSystemAccount === 'function') {
            cementCostAcc = await window.resolveSystemAccount('تكلفة مواد - مشاريع', ['مصروفات', 'تكاليف'], 'expenses');
        }
        if(!cementCostAcc) cementCostAcc = { id: Date.now() + 4, name: 'تكلفة مواد - مشاريع', type: 'مصروفات' };

        cementAssetAcc = accounts.find(a => a.name === 'عهدة أسمنت محطات خارجية' || a.name === 'عهدة أسمنت محطات');
        if(!cementAssetAcc && typeof window.resolveSystemAccount === 'function') {
            cementAssetAcc = await window.resolveSystemAccount('عهدة أسمنت محطات خارجية', ['أصول متداولة', 'أصول'], 'assets');
        }
        if(!cementAssetAcc) cementAssetAcc = { id: Date.now() + 5, name: 'عهدة أسمنت محطات خارجية', type: 'أصول' };
    }

    let taxAcc = null;
    const taxAmount = t.tax_amount || 0;
    if (taxAmount > 0) {
        if (typeof window.resolveSystemAccount === 'function') {
            taxAcc = await window.resolveSystemAccount('ضريبة القيمة المضافة', ['ضريبة', 'ضرائب'], 'assets');
        } else {
            taxAcc = accounts.find(a => a.name.includes('ضريبة القيمة المضافة')) || { id: Date.now() + 50, name: 'ضريبة القيمة المضافة' };
        }
    }

    const costAmount = t.total - taxAmount; // Because t.total includes tax

    const rows = [
        { account_id: costAcc.id, debit: costAmount, credit: 0, project_id: t.project_id, contact_id: t.contact_id, desc: 'شراء خرسانة' }
    ];

    if (taxAmount > 0 && taxAcc) {
        rows.push({ account_id: taxAcc.id, debit: taxAmount, credit: 0, contact_id: t.contact_id, desc: 'ضريبة قيمة مضافة - خرسانة' });
    }

    rows.push({ account_id: creditAcc.id, debit: 0, credit: t.total, contact_id: t.contact_id, desc: 'شراء خرسانة' + (taxAmount > 0 ? ' (شامل الضريبة)' : '') });

    if (cementConsumedValue > 0) {
        rows.push({ account_id: cementCostAcc.id, debit: cementConsumedValue, credit: 0, project_id: t.project_id, contact_id: t.contact_id, desc: 'إهلاك أسمنت للخرسانة' });
        rows.push({ account_id: cementAssetAcc.id, debit: 0, credit: cementConsumedValue, contact_id: t.contact_id, desc: 'خصم من العهدة' });
    }

    const journal = {
        id: Date.now() + 6,
        date: t.date,
        reference: `شراء خرسانة #${t.id}`,
        desc: `شراء خرسانة (${t.concrete_type}) من محطة ${stationName} - فاتورة #${t.id} ${t.notes ? ' - ' + t.notes : ''}`,
        source: `ext_concrete_${t.id}`,
        status: 'posted',
        total: t.total + cementConsumedValue,
        rows: rows
    };
    
    await window.DB.add('journal_entries', journal);
}

// ================= STATION DETAILS MODAL =================



window.viewExternalStationDetails = async function(stationId) {
    const station = currentExternalStations.find(s => String(s.id) === String(stationId));
    if (!station) return;
    
    document.getElementById('ext-station-details-title').innerText = `تفاصيل المحطة: ${station.name}`;
    
    const deliveries = currentExtCementDeliveries.filter(t => String(t.contact_id) === String(stationId));
    const purchases = currentExtConcretePurchases.filter(t => String(t.contact_id) === String(stationId));
    
    const allProjects = await window.DB.getAll('projects') || [];
    const getProjectName = (pid) => {
        const p = allProjects.find(x => String(x.id) === String(pid));
        return p ? p.name : 'غير محدد';
    };

    const cementTbody = document.getElementById('ext-station-cement-tbody');
    cementTbody.innerHTML = '';
    deliveries.forEach(d => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${d.date || ''}</td>
            <td>${getProjectName(d.project_id)}</td>
            <td>${(d.items[0]?.qty || 0).toLocaleString()} طن</td>
            <td>${(d.items[0]?.price || 0).toLocaleString()}</td>
            <td>${(d.tax_amount || 0).toLocaleString()}</td>
            <td>${(d.total || 0).toLocaleString()}</td>
            <td>${d.payment_type === 'cash' ? 'كاش' : 'آجل'}</td>
            <td>
                ${d.attachment ? `<button onclick="window.openAttachmentModal(this.dataset.src)" data-src="${d.attachment}" class="action-btn" style="background:#2196f3; color:white; padding:4px 8px; border:none; cursor:pointer;"><i class="fas fa-paperclip"></i></button>` : `<button onclick="window.addAttachmentToTransaction('${d.id}')" class="action-btn" style="background:#ff9800; color:white; padding:4px 8px; border:none; cursor:pointer;" title="إضافة بوليصة/فاتورة"><i class="fas fa-plus"></i></button>`}
            </td>
            <td>
                <button class="action-btn btn-delete" onclick="deleteExtTransaction('${d.id}')"><i class="fas fa-trash"></i></button>
            </td>
        `;
        cementTbody.appendChild(tr);
    });

    const concreteTbody = document.getElementById('ext-station-concrete-tbody');
    concreteTbody.innerHTML = '';
    purchases.forEach(p => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${p.date || ''}</td>
            <td>${getProjectName(p.project_id)}</td>
            <td>${p.concrete_type || ''}</td>
            <td>${(p.qty || 0).toLocaleString()} م³</td>
            <td>${(p.price || 0).toLocaleString()}</td>
            <td>${(p.tax_amount || 0).toLocaleString()}</td>
            <td>${(p.cement_used || 0).toLocaleString()} طن</td>
            <td>${(p.total || 0).toLocaleString()}</td>
            <td>${p.payment_type === 'cash' ? 'نقدي' : 'آجل'}</td>
            <td>
                ${p.attachment ? `<button onclick="window.openAttachmentModal(this.dataset.src)" data-src="${p.attachment}" class="action-btn" style="background:#2196f3; color:white; padding:4px 8px; border:none; cursor:pointer;"><i class="fas fa-paperclip"></i></button>` : `<button onclick="window.addAttachmentToTransaction('${p.id}')" class="action-btn" style="background:#ff9800; color:white; padding:4px 8px; border:none; cursor:pointer;" title="إضافة بوليصة/فاتورة"><i class="fas fa-plus"></i></button>`}
            </td>
            <td>
                <button class="action-btn btn-delete" onclick="deleteExtTransaction('${p.id}')"><i class="fas fa-trash"></i></button>
            </td>
        `;
        concreteTbody.appendChild(tr);
    });

    document.getElementById('ext-station-details-modal').classList.add('active');
};

window.deleteExtTransaction = async function(id) {
    if(!confirm("هل أنت متأكد من حذف هذه العملية؟ سيتم حذف القيد المحاسبي المرتبط بها أيضاً.")) return;
    
    try {
        await window.DB.remove('transactions', Number(id));
        
        // Find and delete the journal entry
        const journals = await window.DB.getAll('journal_entries') || [];
        const j = journals.find(x => x.source === `ext_cement_${id}` || x.source === `ext_concrete_${id}`);
        if (j) {
            await window.DB.remove('journal_entries', Number(j.id));
        }
        
        // Refresh view
        window.renderExternalStations();
        const detailsModal = document.getElementById('ext-station-details-modal');
        if (detailsModal.classList.contains('active')) {
            // Find which station is open currently. 
            // We can infer from the select boxes or just close it.
            // Let's just close it for simplicity.
            detailsModal.classList.remove('active');
        }
        alert("تم الحذف بنجاح");
    } catch(e) {
        alert("خطأ أثناء الحذف");
    }
};

// ================= AGREEMENTS =================

window.openExtAgreementsModal = async function(stationId, stationName) {
    document.getElementById('ext-agreements-station-id').value = stationId;
    document.getElementById('ext-agreements-title').innerText = "اتفاقات المحطة: " + stationName;
    await window.renderExtAgreementsTable(stationId);
    document.getElementById('ext-agreements-modal').classList.add('active');
};

window.renderExtAgreementsTable = async function(stationId) {
    const contacts = await window.DB.getAll('contacts');
    const station = contacts.find(c => c.id == stationId);
    const tbody = document.getElementById('ext-agreements-tbody');
    tbody.innerHTML = '';
    
    if (station && station.agreements) {
        station.agreements.forEach((agr, index) => {
            let attachmentsHTML = '';
            if (agr.attachments && agr.attachments.length > 0) {
                agr.attachments.forEach((att, attIdx) => {
                    let icon = 'fa-file-alt';
                    if (att.name.match(/\.(jpg|jpeg|png|gif)$/i)) icon = 'fa-image';
                    else if (att.name.match(/\.pdf$/i)) icon = 'fa-file-pdf';
                    else if (att.name.match(/\.(xls|xlsx|csv)$/i)) icon = 'fa-file-excel';
                    
                    attachmentsHTML += `
                        <div style="display:inline-block; margin:2px; border:1px solid #ccc; padding:2px 5px; border-radius:4px; background:#f9f9f9;">
                            <a href="${att.path}" target="_blank" title="${att.name}" style="color:#2196f3;"><i class="fas ${icon}"></i></a>
                            <button onclick="deleteExtAgreementAttachment('${stationId}', ${index}, ${attIdx})" style="background:none;border:none;color:red;cursor:pointer;margin-left:3px;"><i class="fas fa-times"></i></button>
                        </div>
                    `;
                });
            }
            attachmentsHTML += `
                <button class="btn-secondary" style="padding: 2px 5px; font-size:12px; margin-right:5px;" onclick="document.getElementById('upload-agr-att-${index}').click()" title="إضافة مرفق"><i class="fas fa-paperclip"></i></button>
                <input type="file" id="upload-agr-att-${index}" style="display:none;" onchange="uploadExtAgreementAttachment('${stationId}', ${index}, this)">
            `;

            const tr = document.createElement('tr');
            tr.innerHTML = `
                <td>${agr.type}</td>
                <td>${agr.price}</td>
                <td>${agr.cementContent || 0}</td>
                <td>${attachmentsHTML}</td>
                <td><button class="btn-danger action-btn" onclick="deleteExtAgreement('${stationId}', ${index})"><i class="fas fa-trash"></i></button></td>
            `;
            tbody.appendChild(tr);
        });
    }
};

window.uploadExtAgreementAttachment = async function(stationId, agrIndex, inputEl) {
    if(!inputEl.files || inputEl.files.length === 0) return;
    const file = inputEl.files[0];
    const formData = new FormData();
    formData.append('file', file);
    formData.append('type', 'agreements');
    
    try {
        const res = await fetch('upload_attachment.php', { method: 'POST', body: formData });
        const result = await res.json();
        
        if(result.success) {
            const contacts = await window.DB.getAll('contacts');
            const station = contacts.find(c => c.id == stationId);
            if(station && station.agreements && station.agreements[agrIndex]) {
                if(!station.agreements[agrIndex].attachments) station.agreements[agrIndex].attachments = [];
                station.agreements[agrIndex].attachments.push({
                    name: result.name,
                    path: result.path
                });
                await window.DB.update('contacts', station);
                await window.renderExtAgreementsTable(stationId);
            }
        } else {
            alert('فشل رفع الملف: ' + (result.error || ''));
        }
    } catch(e) {
        alert('حدث خطأ بالشبكة أثناء الرفع');
    }
};

window.deleteExtAgreementAttachment = async function(stationId, agrIndex, attIndex) {
    if(!confirm('هل أنت متأكد من حذف هذا المرفق؟')) return;
    const contacts = await window.DB.getAll('contacts');
    const station = contacts.find(c => c.id == stationId);
    if(station && station.agreements && station.agreements[agrIndex] && station.agreements[agrIndex].attachments) {
        station.agreements[agrIndex].attachments.splice(attIndex, 1);
        await window.DB.update('contacts', station);
        await window.renderExtAgreementsTable(stationId);
    }
};

window.addExtAgreement = async function() {
    const stationId = document.getElementById('ext-agreements-station-id').value;
    const type = document.getElementById('new-agreement-type').value.trim();
    const price = parseFloat(document.getElementById('new-agreement-price').value);
    const cement = parseFloat(document.getElementById('new-agreement-cement').value) || 0;
    
    if (!stationId || !type || !price) {
        alert("يرجى إدخال الرتبة والسعر");
        return;
    }
    
    const contacts = await window.DB.getAll('contacts');
    const station = contacts.find(c => c.id == stationId);
    
    if (station) {
        if (!station.agreements) station.agreements = [];
        station.agreements.push({ type, price, cementContent: cement });
        await window.DB.update('contacts', station);
        
        document.getElementById('new-agreement-type').value = '';
        document.getElementById('new-agreement-price').value = '';
        document.getElementById('new-agreement-cement').value = '';
        await window.renderExtAgreementsTable(stationId);
        
        // Refresh dropdowns if modal is open
        if(window.populateExtConcreteTypes) await window.populateExtConcreteTypes();
    }
};

window.deleteExtAgreement = async function(stationId, index) {
    if(!confirm('هل أنت متأكد من الحذف؟')) return;
    
    try {
        const contacts = await window.DB.getAll('contacts');
        const station = contacts.find(c => c.id == stationId);
        
        if (station && station.agreements) {
            station.agreements.splice(index, 1);
            await window.DB.update('contacts', station);
            
            // تحديث جدول الاتفاقيات
            await window.renderExtAgreementsTable(stationId);
            
            // تحديث القائمة المنسدلة في الفاتورة
            if(window.populateExtConcreteTypes) await window.populateExtConcreteTypes();
            
            alert('تم الحذف بنجاح');
        }
    } catch (e) {
        console.error(e);
        alert('حدث خطأ أثناء الحذف: ' + e.message);
    }
};

window.populateExtConcreteTypes = async function() {
    const stationSelect = document.getElementById('ext-concrete-station');
    const typeSelect = document.getElementById('ext-concrete-type');
    const stationId = stationSelect.value;
    
    typeSelect.innerHTML = '<option value="">اختر الرتبة...</option>';
    
    if (!stationId) return;
    
    const contacts = await window.DB.getAll('contacts');
    const station = contacts.find(c => c.id == stationId);
    
    if (station && station.agreements) {
        station.agreements.forEach(agr => {
            typeSelect.innerHTML += `<option value="${agr.type}" data-price="${agr.price}" data-cement="${agr.cementContent || 0}">${agr.type} (السعر: ${agr.price})</option>`;
        });
    }
};

window.onExtConcreteTypeChange = function() {
    const typeSelect = document.getElementById('ext-concrete-type');
    const selectedOption = typeSelect.options[typeSelect.selectedIndex];
    const priceInput = document.getElementById('ext-concrete-price');
    
    if (selectedOption && selectedOption.dataset.price) {
        priceInput.value = selectedOption.dataset.price;
    } else {
        priceInput.value = '';
    }
    if (window.calcExtConcreteTotal) window.calcExtConcreteTotal();
};

window.calcExtConcreteTotal = function() {
    const qty = parseFloat(document.getElementById('ext-concrete-qty').value) || 0;
    const price = parseFloat(document.getElementById('ext-concrete-price').value) || 0;
    const total = qty * price;
    
    // Auto calc cement
    const typeSelect = document.getElementById('ext-concrete-type');
    const selectedOption = typeSelect.options[typeSelect.selectedIndex];
    if (selectedOption && selectedOption.dataset.cement) {
        const cementPerM3 = parseFloat(selectedOption.dataset.cement) || 0;
        document.getElementById('ext-concrete-cement-used').value = ((qty * cementPerM3) / 1000).toFixed(3);
    }

    if (document.getElementById('ext-concrete-total')) {
        document.getElementById('ext-concrete-total').innerText = total.toLocaleString();
    }
};

// ================= STATION REPORT =================

window._extReportData = null;

window.openExtStationReport = async function(stationId) {
    const allTransactions = await window.DB.getAll('transactions') || [];
    const allContacts     = await window.DB.getAll('contacts')     || [];
    const allProjects     = await window.DB.getAll('projects')     || [];

    const station = allContacts.find(c => String(c.id) === String(stationId));
    if (!station) return;

    const deliveries = allTransactions.filter(t => t.type === 'ext_cement_delivery'   && String(t.contact_id) === String(stationId));
    const purchases  = allTransactions.filter(t => t.type === 'ext_concrete_purchase' && String(t.contact_id) === String(stationId));
    const payments   = allTransactions.filter(t => t.type === 'payment'               && String(t.contact_id) === String(stationId));

    const getProj = pid => { const p = allProjects.find(x => String(x.id) === String(pid)); return p ? p.name : ''; };

    // ---- Section 1: Concrete by grade ----
    const gradeMap = {};
    purchases.forEach(p => {
        const grade = p.concrete_type || 'غير محدد';
        const qty   = parseFloat(p.qty)   || 0;
        const val   = parseFloat(p.total) || 0;
        if (!gradeMap[grade]) gradeMap[grade] = { qty: 0, totalValue: 0, cash: 0, ajel: 0 };
        gradeMap[grade].qty        += qty;
        gradeMap[grade].totalValue += val;
        if (p.payment_type === 'cash') gradeMap[grade].cash += val;
        else gradeMap[grade].ajel += val;
    });

    const concreteTbody = document.getElementById('ext-report-concrete-tbody');
    const concreteTfoot = document.getElementById('ext-report-concrete-tfoot');
    concreteTbody.innerHTML = '';
    let totalConcreteQty = 0, totalConcreteVal = 0, totalConcreteAjel = 0;

    Object.entries(gradeMap).forEach(([grade, d]) => {
        const avgPrice = d.qty > 0 ? (d.totalValue / d.qty) : 0;
        totalConcreteQty  += d.qty;
        totalConcreteVal  += d.totalValue;
        totalConcreteAjel += d.ajel;
        const payTag = d.cash > 0 && d.ajel > 0 ? 'مختلط' : d.cash > 0 ? 'كاش' : 'آجل';
        const payColor = d.ajel > 0 ? '#e65100' : '#2e7d32';
        const payBg    = d.ajel > 0 ? '#ffecb3' : '#e8f5e9';
        concreteTbody.innerHTML += `
        <tr style="border-bottom:1px solid #eee;">
            <td style="padding:9px 10px;border:1px solid #ddd;font-weight:bold;">${grade}</td>
            <td style="padding:9px;text-align:center;border:1px solid #ddd;color:#1565c0;font-weight:bold;">${d.qty.toLocaleString()} م³</td>
            <td style="padding:9px;text-align:center;border:1px solid #ddd;">${avgPrice.toLocaleString(undefined,{maximumFractionDigits:0})} ج.م.</td>
            <td style="padding:9px;text-align:center;border:1px solid #ddd;font-weight:bold;color:#1b5e20;">${d.totalValue.toLocaleString()} ج.م.</td>
            <td style="padding:9px;text-align:center;border:1px solid #ddd;">
                <span style="background:${payBg};color:${payColor};padding:2px 8px;border-radius:10px;font-size:15px; font-weight:bold;">${payTag}</span>
            </td>
        </tr>`;
    });

    concreteTfoot.innerHTML = `
    <tr style="background:#e3f2fd;font-weight:bold;">
        <td style="padding:10px;border:1px solid #90caf9;">الإجمالي</td>
        <td style="padding:10px;text-align:center;border:1px solid #90caf9;">${totalConcreteQty.toLocaleString()} م³</td>
        <td style="padding:10px;text-align:center;border:1px solid #90caf9;">-</td>
        <td style="padding:10px;text-align:center;border:1px solid #90caf9;">${totalConcreteVal.toLocaleString()} ج.م.</td>
        <td style="padding:10px;text-align:center;border:1px solid #90caf9;">آجل: ${totalConcreteAjel.toLocaleString()}</td>
    </tr>`;

    // ---- Section 2: Cement summary ----
    let cementDeliveredQty = 0, cementDeliveredValue = 0;
    deliveries.forEach(d => {
        if (d.items) d.items.forEach(it => cementDeliveredQty += parseFloat(it.qty) || 0);
        cementDeliveredValue += parseFloat(d.total) || 0;
    });
    let cementUsedQty = 0;
    purchases.forEach(p => cementUsedQty += parseFloat(p.cement_used) || 0);
    const cementRemainingQty   = cementDeliveredQty - cementUsedQty;
    const avgCementPrice       = cementDeliveredQty > 0 ? (cementDeliveredValue / cementDeliveredQty) : 0;
    const cementRemainingValue = cementRemainingQty * avgCementPrice;

    const cCard = (title, val, sub, color, bg) => `
    <div style="background:${bg};border-right:4px solid ${color};border-radius:8px;padding:14px;">
        <div style="font-size:15px; font-weight:bold;color:#222;margin-bottom:6px;">${title}</div>
        <div style="font-size:24px; font-weight:bold;font-weight:bold;color:${color};">${val}</div>
        <div style="font-size:14px; font-weight:bold;color:#555;margin-top:4px;">${sub}</div>
    </div>`;

    document.getElementById('ext-report-cement-cards').innerHTML =
        cCard('إجمالي المُوَرَّد',
              cementDeliveredQty.toLocaleString() + ' طن',
              'قيمة: ' + cementDeliveredValue.toLocaleString() + ' ج.م. (أمانة) | متوسط السعر: ' + avgCementPrice.toLocaleString(undefined,{maximumFractionDigits:0}) + ' ج.م.',
              '#1565c0', '#e3f2fd') +
        cCard('إجمالي المُستهلك',
              cementUsedQty.toLocaleString() + ' طن',
              'قيمة: ' + (cementUsedQty * avgCementPrice).toLocaleString(undefined,{maximumFractionDigits:0}) + ' ج.م.',
              '#e65100', '#fff3e0') +
        cCard('المتبقي في العهدة',
              cementRemainingQty.toLocaleString() + ' طن',
              'قيمة تقريبية: ' + cementRemainingValue.toLocaleString(undefined,{maximumFractionDigits:0}) + ' ج.م. ★ غير محسوبة في الرصيد',
              '#2e7d32', '#e8f5e9');

    // ---- Section 3: Payments ledger ----
    const payTbody = document.getElementById('ext-report-payments-tbody');
    payTbody.innerHTML = '';
    let allLedger = [];

    purchases.forEach(p => {
        const val = parseFloat(p.total) || 0;
        if (p.payment_type !== 'cash') {
            allLedger.push({ date: p.date, desc: 'شراء خرسانة (' + (p.concrete_type||'') + ') - ' + getProj(p.project_id), debit: 0, credit: val, payType: 'آجل' });
        } else {
            allLedger.push({ date: p.date, desc: 'شراء خرسانة كاش (' + (p.concrete_type||'') + ') - ' + getProj(p.project_id), debit: val, credit: val, payType: 'كاش' });
        }
    });

    payments.forEach(pv => {
        const val = parseFloat(pv.amount) || 0;
        allLedger.push({ date: pv.date, desc: 'سند دفع #' + pv.id + (pv.notes ? ' - ' + pv.notes : ''), debit: val, credit: 0, payType: 'سند دفع' });
    });

    allLedger.sort((a, b) => new Date(a.date) - new Date(b.date));

    allLedger.forEach(row => {
        const ptColor = row.payType === 'كاش' ? '#2e7d32' : row.payType === 'سند دفع' ? '#1565c0' : '#e65100';
        const ptBg    = row.payType === 'كاش' ? '#e8f5e9' : row.payType === 'سند دفع' ? '#e3f2fd' : '#fff3e0';
        payTbody.innerHTML += `
        <tr style="border-bottom:1px solid #eee;">
            <td style="padding:8px 10px;border:1px solid #eee;white-space:nowrap;">${row.date || ''}</td>
            <td style="padding:8px 10px;border:1px solid #eee;">${row.desc}</td>
            <td style="padding:8px;text-align:center;border:1px solid #eee;color:#c62828;">${row.debit > 0 ? row.debit.toLocaleString() : '-'}</td>
            <td style="padding:8px;text-align:center;border:1px solid #eee;color:#1b5e20;">${row.credit > 0 ? row.credit.toLocaleString() : '-'}</td>
            <td style="padding:8px;text-align:center;border:1px solid #eee;">
                <span style="font-size:15px; font-weight:bold;background:${ptBg};color:${ptColor};padding:2px 8px;border-radius:10px;">${row.payType}</span>
            </td>
        </tr>`;
    });

    const totalPaid = payments.reduce((s, p) => s + (parseFloat(p.amount) || 0), 0);
    const remaining = totalConcreteAjel - totalPaid;

    document.getElementById('ext-report-balance-summary').innerHTML = `
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px;">
        <div style="text-align:center;padding:12px;background:#fff3e0;border-radius:8px;">
            <div style="font-size:15px; font-weight:bold;color:#555;margin-bottom:4px;">إجمالي الخرسانة (آجل)</div>
            <div style="font-size:24px; font-weight:bold;font-weight:bold;color:#e65100;">${totalConcreteAjel.toLocaleString()} ج.م.</div>
        </div>
        <div style="text-align:center;padding:12px;background:#e3f2fd;border-radius:8px;">
            <div style="font-size:15px; font-weight:bold;color:#555;margin-bottom:4px;">إجمالي المدفوع</div>
            <div style="font-size:24px; font-weight:bold;font-weight:bold;color:#1565c0;">${totalPaid.toLocaleString()} ج.م.</div>
        </div>
        <div style="text-align:center;padding:12px;background:${remaining > 0 ? '#ffebee' : '#e8f5e9'};border-radius:8px;border:2px solid ${remaining > 0 ? '#c62828' : '#2e7d32'};">
            <div style="font-size:15px; font-weight:bold;color:#555;margin-bottom:4px;">المتبقي غير المسدد</div>
            <div style="font-size:26px; font-weight:bold;font-weight:bold;color:${remaining > 0 ? '#c62828' : '#2e7d32'};">${remaining.toLocaleString()} ج.م.</div>
        </div>
    </div>`;

    document.getElementById('ext-report-title').textContent    = 'تقرير محطة: ' + station.name;
    document.getElementById('ext-report-subtitle').textContent =
        'إجمالي خرسانة: ' + totalConcreteVal.toLocaleString() + ' ج.م.  |  أسمنت موردة: ' + cementDeliveredQty.toLocaleString() + ' طن  |  متبقي: ' + remaining.toLocaleString() + ' ج.م.';

    window._extReportData = { stationName: station.name, totalConcreteVal, totalConcreteAjel, cementDeliveredQty, cementDeliveredValue, cementAvgPrice: avgCementPrice, cementUsedQty, cementRemainingQty, cementRemainingValue, remaining, gradeMap, payments, allLedger };

    document.getElementById('ext-station-report-modal').classList.add('active');
};

window.printExtStationReport = function() {
    const body  = document.getElementById('ext-report-body');
    const title = document.getElementById('ext-report-title').textContent;
    const sub   = document.getElementById('ext-report-subtitle').textContent;
    const w = window.open('', '_blank');
    w.document.write('<!DOCTYPE html><html dir="rtl"><head><meta charset="UTF-8"><title>' + title + '</title><style>');
    w.document.write('body{font-family:Arial,sans-serif;direction:rtl;padding:20px;font-size:16px;color:#000;}');
    w.document.write('h1{color:#000;border-bottom:3px solid #000;padding-bottom:10px;font-size:28px;}');
    w.document.write('h3{font-size:26px; font-weight:bold;font-weight:bold;color:#000 !important;margin-top:25px;border-bottom:2px solid #000 !important;padding-bottom:8px;}');
    w.document.write('table{width:100%;border-collapse:collapse;margin-top:15px;}');
    w.document.write('th,td{border:2px solid #000 !important;padding:12px 15px !important;text-align:center;font-size:16px !important;font-weight:bold !important;color:#000 !important;}');
    w.document.write('th{background:#f0f0f0 !important;font-size:18px !important;}');
    w.document.write('.grid{display:grid;grid-template-columns:repeat(3,1fr);gap:15px;margin-top:15px;}');
    w.document.write('.card{background:#fff !important;border:2px solid #000 !important;border-radius:8px;padding:15px;text-align:center;}');
    w.document.write('.val{font-size:24px !important;font-weight:bold !important;color:#000 !important;}');
    w.document.write('* { -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }');
    w.document.write('span, div { color: #000 !important; font-size: 16px; font-weight: bold; }');
    w.document.write('</style></head><body><h1>' + title + '</h1><p style="color:#000;margin-bottom:25px;font-size:18px;font-weight:bold;">' + sub + '</p>' + body.innerHTML + '<p style="text-align:center;color:#000;margin-top:40px;font-size:14px;font-weight:bold;">تم إنشاء هذا التقرير بتاريخ: ' + new Date().toLocaleDateString('ar-EG') + '</p><script>window.onload=function(){window.print();}</script></body></html>');
    w.document.close();
};

window.shareExtStationReportWhatsApp = function() {
    const d = window._extReportData;
    if (!d) return;
    const nl = '\n';
    let msg = '\uD83D\uDCCA *\u062a\u0642\u0631\u064a\u0631 \u0645\u062d\u0637\u0629: ' + d.stationName + '*' + nl;
    msg += '\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501' + nl;
    msg += '\uD83C\uDFD7\uFE0F *\u0627\u0644\u062e\u0631\u0633\u0627\u0646\u0629 \u0627\u0644\u0645\u0634\u062a\u0631\u0627\u0629:*' + nl;
    Object.entries(d.gradeMap).forEach(([grade, gd]) => {
        const avg = gd.qty > 0 ? Math.round(gd.totalValue / gd.qty) : 0;
        msg += '  \u2022 ' + grade + ': ' + gd.qty.toLocaleString() + ' \u0645\xb3 \xd7 ' + avg.toLocaleString() + ' = ' + gd.totalValue.toLocaleString() + ' \u062c.\u0645.' + nl;
    });
    msg += '  \uD83D\uDCCC \u0627\u0644\u0625\u062c\u0645\u0627\u0644\u064a: ' + d.totalConcreteVal.toLocaleString() + ' \u062c.\u0645.' + nl + nl;
    msg += '\uD83C\uDFDB\uFE0F *\u0627\u0644\u0623\u0633\u0645\u0646\u062a (\u0623\u0645\u0627\u0646\u0629 - \u063a\u064a\u0631 \u0645\u062d\u0633\u0648\u0628\u0629):*' + nl;
    msg += '  \u2022 \u0645\u0648\u0631\u062f\u0629: ' + d.cementDeliveredQty.toLocaleString() + ' \u0637\u0646 (\u0645\u062a\u0648\u0633\u0637: ' + Math.round(d.cementAvgPrice).toLocaleString() + ' \u062c.\u0645.)' + nl;
    msg += '  \u2022 \u0645\u0633\u062a\u0647\u0644\u0643: ' + d.cementUsedQty.toLocaleString() + ' \u0637\u0646' + nl;
    msg += '  \u2022 \u0645\u062a\u0628\u0642\u064a \u0641\u064a \u0627\u0644\u0639\u0647\u062f\u0629: ' + d.cementRemainingQty.toLocaleString() + ' \u0637\u0646' + nl + nl;

    if (d.allLedger && d.allLedger.length > 0) {
        msg += '\uD83D\uDCD2 *\u062a\u0641\u0635\u064a\u0644 \u0627\u0644\u062d\u0631\u0643\u0627\u062a:*' + nl;
        d.allLedger.forEach(r => {
            let amount = r.debit > 0 ? ('(-\u0639\u0644\u064a\u0647) ' + r.debit.toLocaleString()) : ('(+\u0644\u0647) ' + r.credit.toLocaleString());
            msg += '  \u25AA\uFE0F ' + (r.date||'') + ': ' + amount + ' ' + (r.payType === '\u0643\u0627\u0634' ? '[\u0643\u0627\u0634]' : '') + nl;
            msg += '      \u2BA1\uFE0F ' + r.desc + nl;
        });
        msg += nl;
    }

    msg += '\uD83D\uDCB0 *\u0627\u0644\u0631\u0635\u064a\u062f:*' + nl;
    const paid = d.payments.reduce((s, p) => s + (parseFloat(p.amount) || 0), 0);
    msg += '  \u2022 \u0645\u0633\u062a\u062d\u0642 \u0644\u0644\u0645\u062d\u0637\u0629 (\u0622\u062c\u0644): ' + d.totalConcreteAjel.toLocaleString() + ' \u062c.\u0645.' + nl;
    msg += '  \u2022 \u062a\u0645 \u0627\u0644\u062f\u0641\u0639: ' + paid.toLocaleString() + ' \u062c.\u0645.' + nl;
    msg += '  \u2705 \u0627\u0644\u0645\u062a\u0628\u0642\u064a: *' + d.remaining.toLocaleString() + ' \u062c.\u0645.*' + nl;
    msg += '\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501' + nl;
    msg += '\uD83D\uDCC5 ' + new Date().toLocaleDateString('ar-EG');
    window.open('https://wa.me/?text=' + encodeURIComponent(msg), '_blank');
};

window.openAttachmentModal = function(base64Str) {
    if (!base64Str) return;
    document.getElementById('attachment-view-img').style.display = 'none';
    document.getElementById('attachment-view-pdf').style.display = 'none';
    
    // Set up download button
    const downloadBtn = document.getElementById('attachment-download-btn');
    if (downloadBtn) {
        downloadBtn.onclick = function() {
            const a = document.createElement('a');
            a.href = base64Str;
            a.download = base64Str.startsWith('data:application/pdf') ? 'attachment.pdf' : 'attachment.jpg';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
        };
    }

    if (base64Str.startsWith('data:application/pdf')) {
        document.getElementById('attachment-view-pdf').src = base64Str;
        document.getElementById('attachment-view-pdf').style.display = 'block';
    } else {
        document.getElementById('attachment-view-img').src = base64Str;
        document.getElementById('attachment-view-img').style.display = 'inline-block';
    }
    document.getElementById('attachment-view-modal').style.display = 'flex';
};

window.addAttachmentToTransaction = function(txId) {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/*,application/pdf';
    input.onchange = async (e) => {
        if (!e.target.files || !e.target.files[0]) return;
        try {
            const base64 = await new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = () => resolve(reader.result);
                reader.onerror = reject;
                reader.readAsDataURL(e.target.files[0]);
            });
            const txs = await window.DB.getAll('transactions');
            const idx = txs.findIndex(t => String(t.id) === String(txId));
            if (idx > -1) {
                txs[idx].attachment = base64;
                await window.DB.update('transactions', txs[idx]);
                alert('تم إضافة المرفق بنجاح');
                window.renderExternalStations();
                const detailsModal = document.getElementById('ext-station-details-modal');
                if (detailsModal.classList.contains('active')) {
                    window.viewExternalStationDetails(txs[idx].contact_id);
                }
            }
        } catch (err) {
            console.error(err);
            alert('حدث خطأ أثناء إضافة المرفق');
        }
    };
    input.click();
};
