// ============================================================
// Easy ERP - Ready-Mix Concrete Module (ready_mix.js)
// ============================================================

window.RMApp = (function () {
    'use strict';

    // --- State ---
    let currentUser = null;
    let mixers = [];
    let isSavingMixer = false;
    let isSavingPump = false;
    
    let isSavingEquipment = false;
    let employees = [];
    let warehouses = [];
    let equipments = [];
    let projects = [];
    let contacts = [];
    let mixItems = [];
    let batchTrips = []; // Array of trip objects
    let batchExtraItems = []; // Array of extra manual items
    let allItems = []; // All inventory items
    let allTransactions = []; // Sales invoices / receipt & payment vouchers (transactions store)
    let allJournalEntries = []; // Posted journal entries (for manual entries + auto-generated voucher journals)
    let allConcreteInvoicesRM = []; // Concrete invoices archive (the authoritative record of what was billed to the client)


    // ======================
    // INIT & AUTH
    // ======================

    async function waitForDB() {
        let tries = 0;
        while ((!window.DB || typeof window.DB.getAll !== 'function') && tries < 20) {
            await new Promise(r => setTimeout(r, 100));
            tries++;
        }
        if (!window.DB) {
            alert('تعذر تحميل قاعدة البيانات (db.js). يرجى التحديث.');
            throw new Error('DB not loaded');
        }
    }

    async function init() {
        try {
            await waitForDB();
            checkAuth();
        } catch (e) {
            console.error('Init Error:', e);
        }
    }

    function checkAuth() {
        const storedUser = sessionStorage.getItem('currentUser');
        if (storedUser) {
            try {
                currentUser = JSON.parse(storedUser);
                if (currentUser && currentUser.username) {
                    window.rmDataLoadPromise = loadData();
                    showApp();
                    return;
                }
            } catch (e) { }
        }
        showLogin();
    }

    function showLogin() {
        document.getElementById('view-login').style.display = 'flex';
        document.getElementById('app-layout').style.display = 'none';
    }

    function showApp() {
        document.getElementById('view-login').style.display = 'none';
        document.getElementById('app-layout').style.display = 'flex';
        if(currentUser && currentUser.username) {
            document.getElementById('current-user-name').innerText = currentUser.name || currentUser.username;
        }
        
        // Restore active view
        const savedView = localStorage.getItem('currentRmView');
        if (savedView) {
            const el = document.querySelector(`.nav-link[onclick*="'${savedView}'"]`);
            switchTab(savedView, el);
        }
    }

    async function login() {
        const userStr = document.getElementById('login-user').value.trim();
        const passStr = document.getElementById('login-pass').value.trim();
        const errEl = document.getElementById('login-error');

        if (!userStr || !passStr) {
            errEl.innerText = 'يرجى إدخال اسم المستخدم وكلمة المرور';
            errEl.style.display = 'block';
            return;
        }

        try {
            const users = await window.DB.getAll('users');
            const user = users.find(u => u.username === userStr && String(u.password) === String(passStr));

            if (user) {
                try { sessionStorage.setItem('currentUser', JSON.stringify(user)); } catch(e) { console.warn(e); }
                currentUser = user;
                errEl.style.display = 'none';
                window.rmDataLoadPromise = loadData();
                showApp();
            } else {
                errEl.innerText = 'بيانات الدخول غير صحيحة';
                errEl.style.display = 'block';
            }
        } catch (e) {
            errEl.innerText = 'خطأ في الاتصال بقاعدة البيانات';
            errEl.style.display = 'block';
            console.error(e);
        }
    }

    function logout() {
        sessionStorage.removeItem('currentUser');
        currentUser = null;
        showLogin();
    }

    // ======================
    // DATA LOADING
    // ======================

    async function loadData() {
        try {
            const allData = await window.DB.getMultiStores(['mixers', 'employees', 'warehouses', 'projects', 'contacts', 'items', 'users', 'transactions', 'journal_entries', 'concrete_invoices']);
            const mx = allData['mixers'] || [];
            
            const emps = allData['employees'] || [];
            const whs = allData['warehouses'] || [];
            const projs = allData['projects'] || [];
            const conts = allData['contacts'] || [];
            const itms = allData['items'] || [];
            const eqs = allData['equipments'] || [];
            const allUsers = allData['users'] || [];

            mixers = Array.isArray(mx) ? mx : [];
            
            employees = Array.isArray(emps) ? emps : [];
            warehouses = Array.isArray(whs) ? whs : [];
            projects = Array.isArray(projs) ? projs : [];
            contacts = Array.isArray(conts) ? conts : [];
            equipments = Array.isArray(eqs) ? eqs : [];
            allItems = Array.isArray(itms) ? itms : [];
            allTransactions = Array.isArray(allData['transactions']) ? allData['transactions'] : [];
            allJournalEntries = Array.isArray(allData['journal_entries']) ? allData['journal_entries'] : [];
            allConcreteInvoicesRM = Array.isArray(allData['concrete_invoices']) ? allData['concrete_invoices'] : [];

            // Refresh current user to get latest permissions
            if (currentUser && Array.isArray(allUsers)) {
                const updatedUser = allUsers.find(u => String(u.id) === String(currentUser.id));
                if (updatedUser) {
                    currentUser = updatedUser;
                    try { sessionStorage.setItem('currentUser', JSON.stringify(currentUser)); } catch(e) { console.warn(e); }
                }
            }

            // Filter only items that have BOM (components) to represent mix designs
            mixItems = allItems.filter(item => (item.bom && item.bom.length > 0) || (item.category === '\u062e\u0631\u0633\u0627\u0646\u0629 \u062c\u0627\u0647\u0632\u0629') || (item.category === '\u062e\u062f\u0645\u0629') || (item.name && item.name.includes('\u0646\u0642\u0644')));
            
            renderMixers();
            
            populateBatchForm();
            
            try {
                const cached = localStorage.getItem('shared_balances_cache');
                if (cached) {
                    window.balancesCache = JSON.parse(cached);
                }
            } catch(e) {}
        } catch (e) {
            console.error('Failed to load data:', e);
            alert("حدث خطأ أثناء تحميل البيانات:\n" + e.stack);
        }
    }

    // ======================
    // UI HELPERS
    // ======================

    function fileToBase64(file) {
        return new Promise((resolve, reject) => {
            if (!file) return resolve('');
            
            if (!file.type.startsWith('image/')) {
                const reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = () => resolve(reader.result);
                reader.onerror = error => reject(error);
                return;
            }

            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = (event) => {
                const img = new Image();
                img.onload = () => {
                    const canvas = document.createElement('canvas');
                    let width = img.width;
                    let height = img.height;
                    
                    const MAX_SIZE = 800;
                    if (width > height) {
                        if (width > MAX_SIZE) {
                            height = Math.round(height * (MAX_SIZE / width));
                            width = MAX_SIZE;
                        }
                    } else {
                        if (height > MAX_SIZE) {
                            width = Math.round(width * (MAX_SIZE / height));
                            height = MAX_SIZE;
                        }
                    }
                    
                    canvas.width = width;
                    canvas.height = height;
                    const ctx = canvas.getContext('2d');
                    ctx.drawImage(img, 0, 0, width, height);
                    
                    const dataUrl = canvas.toDataURL('image/jpeg', 0.7);
                    resolve(dataUrl);
                };
                img.onerror = () => {
                    resolve(event.target.result); // Fallback to original if image loading fails
                };
                img.src = event.target.result;
            };
            reader.onerror = error => reject(error);
        });
    }

    function previewImage(dataUrl) {
        if (!dataUrl) return;
        const win = window.open('', '_blank');
        if (win) {
            win.document.write('<html><head><title>معاينة الصورة</title></head><body style="margin:0; display:flex; justify-content:center; align-items:center; background:#333;">');
            win.document.write(`<img src="${dataUrl}" style="max-width:100%; max-height:100vh;">`);
            win.document.write('</body></html>');
            win.document.close();
        } else {
            alert('يرجى السماح بالنوافذ المنبثقة (Pop-ups) لعرض الصورة');
        }
    }

    function formatExpiryDate(dateStr) {
        if (!dateStr) return '-';
        const today = new Date();
        const expDate = new Date(dateStr);
        const diffTime = expDate - today;
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        let color = '';
        let fontWeight = 'normal';
        if (diffDays < 0) {
            color = '#e74c3c'; // Red
            fontWeight = 'bold';
        } else if (diffDays <= 30) {
            color = '#e67e22'; // Orange
            fontWeight = 'bold';
        }
        
        return `<span style="color:${color}; font-weight:${fontWeight}">${dateStr}</span>`;
    }

    function switchTab(tabName, el) {
        document.querySelectorAll('.nav-link').forEach(n => n.classList.remove('active'));
        if (el) el.classList.add('active');

        document.querySelectorAll('.view-section').forEach(v => {
            v.classList.remove('active');
            v.style.display = 'none';
        });

        localStorage.setItem('currentRmView', tabName);

        const target = document.getElementById('view-' + tabName);
        if (target) {
            target.classList.add('active');
            target.style.display = 'block';
        }
        
        if (tabName === 'archive') {
            renderArchiveTable();
        } else if (tabName === 'dashboard') {
            renderRMDashboard();
        } else if (tabName === 'production-report') {
            populateProductionReportStation();
        } else if (tabName === 'client-statement') {
            populateClientStatementDropdown();
        }
    }

    // ======================
    // CLIENT STATEMENT (كشف حساب - خرسانة)
    // ======================

    function populateClientStatementDropdown() {
        const sel = document.getElementById('cs-client-select');
        if (!sel) return;
        const prevVal = sel.value;
        let opts = '<option value="">-- اختر عميل --</option>';
        contacts.forEach(c => {
            opts += `<option value="${c.id}">${c.name}</option>`;
        });
        sel.innerHTML = opts;
        if (prevVal) sel.value = prevVal;
    }

    function refreshClientStatement() {
        const contactId = document.getElementById('cs-client-select').value;
        const tbody = document.getElementById('cs-tbody');
        if (!contactId) {
            tbody.innerHTML = '<tr><td colspan="9" style="text-align:center; padding:20px;">اختر عميل واضغط "عرض الكشف"</td></tr>';
            return;
        }
        const c = contacts.find(x => String(x.id) === String(contactId));
        const filterFrom = document.getElementById('cs-date-from').value;
        const filterTo = document.getElementById('cs-date-to').value;

        let records = [];

        // 1) Concrete invoices for this client, sourced from the concrete archive itself
        //    (not the generic sales-invoice record) - this correctly captures billed_qty
        //    vs total_qty, and any extra charges (lumpsum) added on top of the concrete value.
        allConcreteInvoicesRM.forEach(inv => {
            if (inv.client_type !== 'contact') return; // only external clients have a financial statement
            if (String(inv.target_id) !== String(contactId)) return;

            const mixItem = allItems.find(i => String(i.id) === String(inv.mix_item_id));
            const mixName = 'خرسانة جاهزة ' + (mixItem ? mixItem.name : '');
            const billedQty = parseFloat(inv.billed_qty !== undefined ? inv.billed_qty : inv.total_qty) || 0;
            const lumpsum = parseFloat(inv.extra_lumpsum) || 0;
            const totalRevenue = parseFloat(inv.total_revenue) || 0;
            // Concrete value = total billed to client minus any extra (non-concrete) charge
            const concreteValue = Math.max(totalRevenue - lumpsum, 0);
            const price = billedQty > 0 ? (concreteValue / billedQty) : 0;

            if (concreteValue > 0 || billedQty > 0) {
                records.push({
                    date: inv.date,
                    type: 'فاتورة مبيعات',
                    ref: '#' + inv.id,
                    notes: mixName,
                    price: price,
                    qty: billedQty,
                    concreteValue: concreteValue,
                    debit: concreteValue,
                    credit: 0
                });
            }

            // Any extra charge on the same invoice (e.g. مبلغ إضافي) shown as its own line,
            // since it's not part of the concrete quantity/price itself.
            if (lumpsum > 0) {
                records.push({
                    date: inv.date,
                    type: 'فاتورة مبيعات',
                    ref: '#' + inv.id,
                    notes: inv.extra_lumpsum_desc || 'مبلغ إضافي',
                    price: 0,
                    qty: 0,
                    concreteValue: lumpsum,
                    debit: lumpsum,
                    credit: 0
                });
            }
        });

        // 2) Payments (دفعات) - two sources combined, without double-counting:
        //    a) Receipt vouchers (سند قبض) themselves - reliable because the voucher record
        //       always carries contact_id, even though its auto-generated journal rows don't.
        //    b) Posted journal entries with contact_id set directly on a credit row -
        //       this covers manual journal entries made without creating a voucher.
        allTransactions.forEach(t => {
            if (t.type !== 'receipt') return;
            if (String(t.contact_id) !== String(contactId)) return;
            const amount = parseFloat(t.amount) || 0;
            if (amount <= 0) return;

            records.push({
                date: t.date,
                type: 'سند قبض',
                ref: '#' + t.id,
                notes: t.notes || '',
                price: 0,
                qty: 0,
                concreteValue: 0,
                debit: 0,
                credit: amount
            });
        });

        allJournalEntries.forEach(j => {
            if (j.status !== 'posted') return;
            if (!j.rows) return;
            if (j.reference && j.reference.startsWith('voucher_')) return; // already counted above via the voucher itself
            j.rows.forEach(r => {
                if (String(r.contact_id) !== String(contactId)) return;
                const credit = parseFloat(r.credit) || 0;
                if (credit <= 0) return; // only the payment/credit side, to avoid double-counting the sale

                records.push({
                    date: j.date,
                    type: 'قيد يدوي',
                    ref: '#' + j.id,
                    notes: r.notes || j.desc || '',
                    price: 0,
                    qty: 0,
                    concreteValue: 0,
                    debit: 0,
                    credit: credit
                });
            });
        });

        // Date filter
        if (filterFrom) {
            const fromDate = new Date(filterFrom); fromDate.setHours(0, 0, 0, 0);
            records = records.filter(r => new Date(r.date) >= fromDate);
        }
        if (filterTo) {
            const toDate = new Date(filterTo); toDate.setHours(23, 59, 59, 999);
            records = records.filter(r => new Date(r.date) <= toDate);
        }

        // Sort chronologically to compute running balance correctly
        records.sort((a, b) => new Date(a.date) - new Date(b.date));

        let runningBalance = 0;
        let totalDebit = 0;
        let totalCredit = 0;

        records.forEach(r => {
            totalDebit += r.debit;
            totalCredit += r.credit;
            runningBalance += (r.debit - r.credit);
            r.balStr = Math.abs(runningBalance).toLocaleString('en-US') +
                (runningBalance > 0 ? ' (مدين)' : runningBalance < 0 ? ' (دائن)' : '');
        });

        // Show newest first, like the rest of the app's statements
        records = records.slice().reverse();

        tbody.innerHTML = '';
        if (records.length === 0) {
            tbody.innerHTML = '<tr><td colspan="9" style="text-align:center; padding:20px;">لا توجد حركات في الفترة المحددة</td></tr>';
        } else {
            records.forEach(r => {
                tbody.innerHTML += `<tr>
                    <td>${new Date(r.date).toLocaleDateString('ar-EG')}</td>
                    <td>${r.type}</td>
                    <td>${r.ref}</td>
                    <td>${r.notes}</td>
                    <td>${r.price ? r.price.toLocaleString('en-US') : '-'}</td>
                    <td>${r.qty ? r.qty.toLocaleString('en-US') : '-'}</td>
                    <td>${r.concreteValue ? r.concreteValue.toLocaleString('en-US') : '-'}</td>
                    <td>${r.credit ? r.credit.toLocaleString('en-US') : '-'}</td>
                    <td style="font-weight:bold;">${r.balStr}</td>
                </tr>`;
            });
        }

        document.getElementById('cs-total-debit').innerText = totalDebit.toLocaleString('en-US');
        document.getElementById('cs-total-credit').innerText = totalCredit.toLocaleString('en-US');
        const finalBalStr = Math.abs(runningBalance).toLocaleString('en-US') +
            (runningBalance > 0 ? ' (مدين)' : runningBalance < 0 ? ' (دائن)' : '');
        document.getElementById('cs-final-balance').innerText = finalBalStr;

        const printHeader = document.getElementById('cs-print-header');
        if (c) {
            const fromStr = document.getElementById('cs-date-from').value;
            const toStr = document.getElementById('cs-date-to').value;
            let periodStr = '';
            if (fromStr || toStr) {
                periodStr = `<div style="font-size:14px; font-weight:normal; margin-top:5px;">الفترة: ${fromStr || '...'} إلى ${toStr || '...'}</div>`;
            }
            printHeader.innerHTML = `<div style="font-size:20px;">كشف حساب: ${c.name} (عميل)</div>${periodStr}<div style="font-size:12px; font-weight:normal; margin-top:5px;">تاريخ الطباعة: ${new Date().toLocaleDateString('ar-EG')}</div>`;
        }
    }

    function printClientStatement() {
        const contactId = document.getElementById('cs-client-select').value;
        if (!contactId) { alert('اختر عميل الأول واعرض الكشف قبل الطباعة'); return; }
        document.body.classList.add('printing-cs');
        const cleanup = () => document.body.classList.remove('printing-cs');
        window.onafterprint = cleanup;
        window.print();
        setTimeout(cleanup, 3000); // fallback in case onafterprint doesn't fire
    }

    async function renderRMDashboard() {
        const container = document.getElementById('rm-dashboard-content');
        if (!container) return;
        
        container.innerHTML = '<div style="text-align:center; padding:20px;">جاري تحميل لوحة المؤشرات...</div>';

        try {
            if (window.rmDataLoadPromise) await window.rmDataLoadPromise;
            // Ensure data is loaded
            let invoices = await window.DB.getAll('concrete_invoices') || [];
            let pettyCashTxs = [];
            if (window.allInvoices) {
                pettyCashTxs = window.allInvoices.filter(t => t.type === 'expense' && t.items && t.items.some(i => i.item_type === 'expense'));
            } else {
                pettyCashTxs = await window.DB.getAll('transactions') || [];
                pettyCashTxs = pettyCashTxs.filter(t => t.type === 'expense');
            }

            // 1. Determine Allowed Stations
            const allowedIds = getUserAllowedStationIds();
            let displayStations = warehouses || [];
            
            // Filter to only stations (exclude regular warehouses)
            
            
            if (allowedIds !== null) {
                displayStations = displayStations.filter(w => allowedIds.includes(String(w.id)));
            }

            // 2. Count Mixers, Pumps, Equipments
            
            // Populate Dropdown
            const filterSelect = document.getElementById('dashboard-station-filter');
            let selectedStation = '';
            
            if (filterSelect) {
                console.log('Warehouses array length:', warehouses ? warehouses.length : 'undefined');
                console.log('displayStations length:', displayStations ? displayStations.length : 'undefined');
                console.log('allowedIds:', allowedIds);
                // Also log the actual contents
                console.log('Warehouses:', warehouses);

                selectedStation = filterSelect.value;
                if (filterSelect.options.length <= 1) {
                    displayStations.forEach(s => {
                        const opt = document.createElement('option');
                        opt.value = s.id;
                        opt.textContent = s.name || "محطة " + s.id;
                        filterSelect.appendChild(opt);
                    });
                    if (selectedStation) filterSelect.value = selectedStation;
                }
            }

            let allowedMixers = mixers || [];
            if (allowedIds !== null) {
                allowedMixers = allowedMixers.filter(m => !m.station_id || allowedIds.includes(String(m.station_id)));
            }
            if (selectedStation) {
                allowedMixers = allowedMixers.filter(m => String(m.station_id || m.warehouse_id) === String(selectedStation));
            }
            
            if (selectedStation) {
                invoices = invoices.filter(inv => String(inv.warehouse_id) === String(selectedStation));
            }


            // Group by Unique Types dynamically
            let typeCounts = {};
            allowedMixers.forEach(m => {
                let t = m.type || 'خلاطة';
                t = t.trim();
                if (!typeCounts[t]) typeCounts[t] = 0;
                typeCounts[t]++;
            });
            
            let typesHtml = '';
            const typeColors = ['#f59e0b', '#10b981', '#6366f1', '#06b6d4', '#14b8a6', '#d946ef'];
            let colorIdx = 0;
            for (let t in typeCounts) {
                let c = typeColors[colorIdx % typeColors.length];
                typesHtml += `
                    <div style="background:#fff; padding:15px; border-radius:8px; border-right:4px solid ${c}; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                        <div style="color:#64748b; font-size:0.95rem; font-weight:bold;">${t}</div>
                        <div style="font-size:2rem; font-weight:bold; color:#1e293b; margin-top:5px;">${typeCounts[t]}</div>
                    </div>
                `;
                colorIdx++;
            }
            
            let inMaintenance = allowedMixers.filter(m => m.status === 'maintenance' || m.status === 'inactive' || m.status === 'معطل' || m.status === 'صيانة');
            let noDriver = allowedMixers.filter(m => !m.driver_id || String(m.driver_id).trim() === '');
            
            const today = new Date();
            let licenseWarnings = allowedMixers.filter(m => {
                let licExp = m.vehicle_license_expiry ? new Date(m.vehicle_license_expiry) : null;
                let insExp = m.vehicle_insurance_expiry ? new Date(m.vehicle_insurance_expiry) : null;
                return (licExp && licExp < today) || (insExp && insExp < today);
            });

            // 3. Raw Materials (tag === 'خامات خرسانة')
            const rawMaterials = (allItems || []).filter(i => i.tag && i.tag.trim().includes('خامات خرسانة'));

            // 4. Invoices Calculation for Revenue and Costs
            const rmInvoices = invoices.filter(inv => displayStations.find(s => String(s.id) === String(inv.warehouse_id)));

            // HTML Building
            let html = `
                <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap:15px; margin-bottom:20px;">
                    
                    ${typesHtml}
                    <div style="background:#fff; padding:15px; border-radius:8px; border-right:4px solid #ef4444; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                        <div style="color:#64748b; font-size:0.95rem; font-weight:bold;">في الصيانة / معطل</div>
                        <div style="font-size:2rem; font-weight:bold; color:#1e293b; margin-top:5px;">${inMaintenance.length}</div>
                    </div>
                    <div style="background:#fff; padding:15px; border-radius:8px; border-right:4px solid #8b5cf6; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                        <div style="color:#64748b; font-size:0.95rem; font-weight:bold;">بدون سائق</div>
                        <div style="font-size:2rem; font-weight:bold; color:#1e293b; margin-top:5px;">${noDriver.length}</div>
                    </div>
                    <div style="background:#fff; padding:15px; border-radius:8px; border-right:4px solid #ec4899; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                        <div style="color:#64748b; font-size:0.95rem; font-weight:bold;">تراخيص منتهية</div>
                        <div style="font-size:2rem; font-weight:bold; color:#1e293b; margin-top:5px;">${licenseWarnings.length}</div>
                    </div>
                </div>
            `;

            // Loop over allowed stations to build detailed cards
            const detailedStations = displayStations.filter(w => w.name && (w.name.includes('محطة') || w.name.includes('خرسان')));
            detailedStations.forEach(st => {
                // Find invoices for this specific station
                const stInvoices = rmInvoices.filter(inv => String(inv.warehouse_id) === String(st.id));
                let stRev = 0; let stCost = 0; let stCashExpenses = 0;
                
                stInvoices.forEach(inv => {
                    stRev += parseFloat(inv.total_revenue || 0);
                    
                    // Use historical fixed cost from the archive (total_cost) instead of recalculating dynamically
                    stCost += parseFloat(inv.total_cost || 0);

                    // Cash Expenses
                    pettyCashTxs.forEach(tx => {
                        (tx.items || []).forEach(txItem => {
                            if (String(txItem.concrete_order_id) === String(inv.id) || String(txItem.batch_id) === String(inv.id)) {
                                stCashExpenses += parseFloat(txItem.total || 0);
                            }
                        });
                    });
                });
                
                stCost += stCashExpenses; // add cash expenses to total cost
                
                // Calculate Sales by Mix Product
                let mixStats = {};
                stInvoices.forEach(inv => {
                    const mixId = inv.mix_item_id;
                    if (!mixId) return;
                    if (!mixStats[mixId]) {
                        mixStats[mixId] = { qty: 0, revenue: 0 };
                    }
                    mixStats[mixId].qty += parseFloat(inv.total_qty || 0);
                    mixStats[mixId].revenue += parseFloat(inv.total_revenue || 0);
                });

                const allowedFinancialRoles = ['مدير عام', 'محاسب', 'مدير مالي', 'مدير'];
                const canViewFinancials = currentUser && allowedFinancialRoles.includes(currentUser.role);
                
                let mixRows = '';
                for (let mixId in mixStats) {
                    const mixObj = mixItems.find(m => m.id == mixId);
                    const mixName = mixObj ? mixObj.name : 'منتج غير معروف';
                    const stats = mixStats[mixId];
                    
                    let revenueHtml = '';
                    if (canViewFinancials) {
                        revenueHtml = `<br><small style="color:#16a34a; font-weight:bold;">${stats.revenue.toLocaleString(undefined, {maximumFractionDigits:0})} ج.م</small>`;
                    }

                    mixRows += `
                        <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:12px; border-bottom:1px dashed #e2e8f0; padding-bottom:8px;">
                            <span style="color:#1e293b; font-weight:500; font-size:0.95rem;">${mixName}</span>
                            <div style="text-align:left;">
                                <strong style="color:#0f172a; font-size:1.05rem;">${stats.qty.toLocaleString(undefined, {maximumFractionDigits:2})} م³</strong>
                                ${revenueHtml}
                            </div>
                        </div>
                    `;
                }

                // Raw materials table rows
                let rawRows = '';
                rawMaterials.forEach(rm => {
                    const balInfo = window.balancesCache ? window.balancesCache[rm.id] : null;
                    const qty = balInfo && balInfo.warehouses ? (balInfo.warehouses[st.id] || 0) : 0;
                    
                    let altDisplay = '';
                    const convF = parseFloat(rm.conv_factor) || 1;
                    const altU = rm.alt_unit || '';
                    if (altU && convF !== 1) {
                        altDisplay = `<br><span style="font-size:1.1em; color:#64748b; font-weight:600;">(${(qty / convF).toLocaleString(undefined, {maximumFractionDigits:2})} ${altU})</span>`;
                    }

                    rawRows += `
                        <tr>
                            <td style="padding:10px 5px; border-bottom:1px solid #f1f5f9; color:#1e293b; font-weight:500;">${rm.name}</td>
                            <td style="padding:10px 5px; border-bottom:1px solid #f1f5f9; text-align:left; font-weight:bold; color:${qty <= 1000 ? '#ef4444' : '#15803d'};">${qty.toLocaleString(undefined, {maximumFractionDigits:2})} <small style="color:#64748b;">${rm.unit}</small>${altDisplay}</td>
                        </tr>
                    `;
                });

                let financialsHtml = '';
                if (canViewFinancials) {
                    financialsHtml = `
                                <div style="display:flex; justify-content:space-between; margin-bottom:12px; border-bottom:1px dashed #e2e8f0; padding-bottom:8px;">
                                    <span style="color:#475569;">إجمالي الإيرادات:</span> <strong style="color:#2563eb; font-size:1.1rem;">${stRev.toLocaleString(undefined, {maximumFractionDigits:0})}</strong>
                                </div>
                                <div style="display:flex; justify-content:space-between; margin-bottom:12px; border-bottom:1px dashed #e2e8f0; padding-bottom:8px;">
                                    <span style="color:#475569;">إجمالي التكاليف (المسجلة):</span> <strong style="color:#dc2626; font-size:1.1rem;">${stCost.toLocaleString(undefined, {maximumFractionDigits:0})}</strong>
                                </div>
                                <div style="display:flex; justify-content:space-between; margin-top:15px; background:#f1f5f9; padding:10px; border-radius:5px;">
                                    <span style="font-weight:bold; color:#1e293b;">الصافي التقديري:</span> <strong style="font-size:1.2rem; color:${(stRev - stCost) >= 0 ? '#16a34a' : '#ef4444'};">${(stRev - stCost).toLocaleString(undefined, {maximumFractionDigits:0})}</strong>
                                </div>
                    `;
                }

                html += `
                    <div style="background:#f8fafc; border:1px solid #e2e8f0; border-radius:8px; padding:20px; margin-bottom:20px;">
                        <h3 style="margin-top:0; color:#1e293b; border-bottom:2px solid #cbd5e1; padding-bottom:10px; font-size:1.4rem;">📍 محطة: ${st.name}</h3>
                        
                        <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap:20px; margin-top:15px;">
                            
                            <!-- Financial & Operations -->
                            <div style="background:#fff; padding:20px; border-radius:8px; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                                <h4 style="margin-top:0; color:#0f172a; font-size:1.1rem; margin-bottom:15px;">📊 الأداء المالي والتشغيلي</h4>
                                <div style="display:flex; justify-content:space-between; margin-bottom:12px; border-bottom:1px dashed #e2e8f0; padding-bottom:8px;">
                                    <span style="color:#475569;">إجمالي أوامر الصب:</span> <strong style="font-size:1.1rem; color:#1e293b;">${stInvoices.length}</strong>
                                </div>
                                ${financialsHtml}
                            </div>
                            
                            <!-- Sales by Mix Product -->
                            <div style="background:#fff; padding:20px; border-radius:8px; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                                <h4 style="margin-top:0; color:#0f172a; font-size:1.1rem; margin-bottom:15px;">📈 المبيعات حسب المنتج</h4>
                                ${mixRows || '<div style="color:#64748b; text-align:center; padding:10px;">لا توجد مبيعات مسجلة</div>'}
                            </div>

                            <!-- Raw Materials Inventory -->
                            <div style="background:#fff; padding:20px; border-radius:8px; box-shadow:0 1px 3px rgba(0,0,0,0.1); color:#1e293b;">
                                <h4 style="margin-top:0; color:#0f172a; font-size:1.1rem; margin-bottom:15px;">📦 أرصدة الخامات المباشرة</h4>
                                <table style="width:100%; border-collapse:collapse; font-size:1rem; color:#1e293b;">
                                    ${rawRows || '<tr><td style="padding:8px; color:#1e293b;">لا توجد خامات مسجلة</td></tr>'}
                                </table>
                            </div>

                        </div>
                    </div>
                `;
            });

            if (displayStations.length === 0) {
                html += `<div style="text-align:center; padding:30px; background:#fff; border-radius:8px; color:#64748b;">لا توجد محطات متاحة لك لعرض بياناتها.</div>`;
            }

            container.innerHTML = html;
        } catch (e) {
            console.error('Error rendering RM Dashboard:', e);
            container.innerHTML = '<div style="color:red; padding:20px;">حدث خطأ أثناء تحميل البيانات.</div>';
        }
    }

    
    
    
    
    
    async function populateProductionReportStation() {
        const select = document.getElementById('production-report-station');
        if (!select) return;
        
        // Use module-scoped warehouses first (same as dashboard), fallback to DB
        let allWarehouses = (warehouses && warehouses.length > 0) ? warehouses : [];
        if (allWarehouses.length === 0) {
            try {
                allWarehouses = await window.DB.getAll('warehouses') || [];
            } catch(e) { console.error('Failed to load warehouses for report:', e); }
        }
        
        console.log('Report stations: total warehouses =', allWarehouses.length);

        const allowedIds = getUserAllowedStationIds();
        let displayStations = allWarehouses;
        if (allowedIds) {
            displayStations = displayStations.filter(w => allowedIds.includes(String(w.id)));
        }
        
        console.log('Report stations: filtered =', displayStations.length, displayStations.map(s => s.name));
        
        let opts = '<option value="">-- جميع المحطات --</option>';
        displayStations.forEach(s => {
            opts += `<option value="${s.id}">${s.name || "محطة " + s.id}</option>`;
        });
        select.innerHTML = opts;
    }

    async function renderProductionReport() {
        const dateFromInput = document.getElementById('production-report-date-from');
        const dateToInput = document.getElementById('production-report-date-to');
        
        let fromDate = dateFromInput ? dateFromInput.value : '';
        let toDate = dateToInput ? dateToInput.value : '';
        
        if (!fromDate) {
            fromDate = new Date().toISOString().split('T')[0];
            if (dateFromInput) dateFromInput.value = fromDate;
        }
        if (!toDate) {
            toDate = new Date().toISOString().split('T')[0];
            if (dateToInput) dateToInput.value = toDate;
        }

        const container = document.getElementById('production-report-content');
        if (!container) return;
        container.innerHTML = '<div style="text-align:center; padding:30px;"><i class="fas fa-spinner fa-spin fa-2x"></i></div>';

        try {
            const invoices = await window.DB.getAll('concrete_invoices') || [];
            const allTrips = await window.DB.getAll('invoice_mixer_trips') || [];
            
            // Use module-scoped arrays if available
            const myUsers = await window.DB.getAll('users') || [];
            const myEmployees = await window.DB.getAll('employees') || [];
            let dbMixers = await window.DB.getAll('mixers') || [];
            let dbEquipments = await window.DB.getAll('equipments') || [];
            const myMixers = dbMixers.length > 0 ? dbMixers : dbEquipments;

            const getUserName = (id) => {
                if(!id) return 'غير محدد';
                const u = myUsers.find(u => String(u.id) === String(id));
                if (u && u.name) return u.name;
                const e = myEmployees.find(e => String(e.id) === String(id));
                if (e && e.name) return e.name;
                return 'غير محدد';
            };
            const getMixerName = (id) => {
                if(!id) return 'غير محدد';
                const m = myMixers.find(m => String(m.id) === String(id));
                return m ? (m.name || m.plate_number || m.plate || id) : id;
            };

            const stationInput = document.getElementById('production-report-station');
            const selectedStationId = stationInput ? stationInput.value : '';
            
            const targetInvoices = invoices.filter(inv => {
                if (!inv.date || inv.status === 'ملغي') return false;
                
                if (selectedStationId && String(inv.warehouse_id) !== String(selectedStationId)) return false;
                
                const allowedIds = typeof getUserAllowedStationIds === 'function' ? getUserAllowedStationIds() : null;
                if (allowedIds && !allowedIds.includes(String(inv.warehouse_id))) return false;

                const invDate = inv.date.split('T')[0].split(' ')[0];
                return invDate >= fromDate && invDate <= toDate;
            });

            let totalQty = 0;
            const stationOps = {};
            const pumpsData = {};
            const mixersData = {};
            const driversData = {};

            targetInvoices.forEach(inv => {
                const invQty = parseFloat(inv.total_qty) || 0;
                totalQty += invQty;

                const statOp = getUserName(inv.station_operator_id);
                stationOps[statOp] = (stationOps[statOp] || 0) + invQty;

                if (inv.pump_id) {
                    const pName = getMixerName(inv.pump_id);
                    if (!pumpsData[pName]) pumpsData[pName] = { total: 0, ops: {} };
                    pumpsData[pName].total += invQty;
                    
                    const pOp = getUserName(inv.pump_operator_id);
                    pumpsData[pName].ops[pOp] = (pumpsData[pName].ops[pOp] || 0) + invQty;
                }

                // Apportion trips for this invoice
                const invTrips = allTrips.filter(t => String(t.concrete_invoice_id) === String(inv.id));
                let totalTripsCount = 0;
                let explicitTripsQty = 0;

                invTrips.forEach(t => {
                    const count = parseInt(t.trips_count) || 1;
                    const cap = parseFloat(t.capacity) || 0;
                    totalTripsCount += count;
                    explicitTripsQty += (cap * count);
                });

                let avgQtyPerTrip = 0;
                if (explicitTripsQty === 0 && totalTripsCount > 0) {
                    avgQtyPerTrip = invQty / totalTripsCount;
                }

                invTrips.forEach(trip => {
                    const count = parseInt(trip.trips_count) || 1;
                    const cap = parseFloat(trip.capacity) || 0;
                    let tripQty = cap * count;
                    if (tripQty === 0) {
                        tripQty = avgQtyPerTrip * count;
                    }

                    if (trip.mixer_id) {
                        const mName = getMixerName(trip.mixer_id);
                        if (!mixersData[mName]) mixersData[mName] = { total: 0, trips: 0 };
                        mixersData[mName].total += tripQty;
                        mixersData[mName].trips += count;
                    }
                    if (trip.driver_id) {
                        const dName = getUserName(trip.driver_id);
                        if (!driversData[dName]) driversData[dName] = { total: 0, trips: 0 };
                        driversData[dName].total += tripQty;
                        driversData[dName].trips += count;
                    }
                });
            });

            const renderBadge = (val, color) => `<span style="background:${color}; color:#fff; padding:4px 10px; border-radius:20px; font-size:12px; font-weight:bold; white-space:nowrap; flex-shrink:0;">${val.toFixed(1)} م٣</span>`;
            
            let html = `
                <div style="background:var(--panel-bg, #2c3e50); border:1px solid rgba(255,255,255,0.1); border-radius:8px; padding:15px; margin-bottom:20px;">
                    <h3 style="margin:0; color:#fff; text-align:center; font-size:20px; font-weight:800;">
                        <i class="fas fa-industry" style="color:#9b59b6;"></i> [ إجمالي إنتاج المحطة: ${totalQty.toFixed(1)} متر مكعب ]
                    </h3>
                </div>
                <div style="display:flex; flex-wrap:wrap; gap:15px;">
            `;

            const cardStyle = `flex:1; min-width:250px; background:var(--panel-bg, #2c3e50); border:1px solid rgba(255,255,255,0.1); border-radius:8px; box-shadow:0 2px 8px rgba(0,0,0,0.2); border-top:4px solid`;

            // Card 1
            html += `<div style="${cardStyle} #3498db;">
                <div style="padding:15px; border-bottom:1px solid rgba(255,255,255,0.1); font-weight:bold; color:#3498db;">
                    <i class="fas fa-users-cog"></i> مشغلي المحطة
                </div>
                <div style="padding:15px;">`;
            for (let op in stationOps) {
                html += `<div style="display:flex; justify-content:space-between; margin-bottom:10px; color:var(--text-primary, #fff);">
                    <span>${op}</span> ${renderBadge(stationOps[op], '#3498db')}
                </div>`;
            }
            if (Object.keys(stationOps).length === 0) html += `<div style="color:#aaa; text-align:center;">لا يوجد</div>`;
            html += `</div></div>`;

            // Card 2
            html += `<div style="${cardStyle} #2ecc71;">
                <div style="padding:15px; border-bottom:1px solid rgba(255,255,255,0.1); font-weight:bold; color:#2ecc71;">
                    <i class="fas fa-pump-medical"></i> المضخات
                </div>
                <div style="padding:15px;">`;
            for (let pump in pumpsData) {
                html += `<div style="margin-bottom:15px; border-bottom:1px dashed rgba(255,255,255,0.1); padding-bottom:10px;">
                    <div style="display:flex; justify-content:space-between; margin-bottom:10px; font-weight:bold; color:var(--text-primary, #fff);">
                        <span>${pump}</span> ${renderBadge(pumpsData[pump].total, '#2ecc71')}
                    </div>`;
                for(let pop in pumpsData[pump].ops) {
                    html += `<div style="display:flex; justify-content:space-between; padding-right:15px; margin-bottom:5px; color:#ddd; font-size:13px; border-right:2px solid #2ecc71;">
                        <span><i class="fas fa-user ms-1"></i>${pop}</span> <span style="background:rgba(255,255,255,0.1); padding:2px 6px; border-radius:10px; white-space:nowrap; flex-shrink:0;">${pumpsData[pump].ops[pop].toFixed(1)} م٣</span>
                    </div>`;
                }
                html += `</div>`;
            }
            if (Object.keys(pumpsData).length === 0) html += `<div style="color:#aaa; text-align:center;">لا يوجد</div>`;
            html += `</div></div>`;

            // Card 3
            html += `<div style="${cardStyle} #f1c40f;">
                <div style="padding:15px; border-bottom:1px solid rgba(255,255,255,0.1); font-weight:bold; color:#f39c12;">
                    <i class="fas fa-truck-monster"></i> الخلاطات
                </div>
                <div style="padding:15px;">`;
            for (let mix in mixersData) {
                html += `<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; border-bottom:1px dashed rgba(255,255,255,0.1); padding-bottom:5px;">
                    <div style="color:var(--text-primary, #fff);">
                        <div style="font-weight:bold;">${mix}</div>
                        <div style="font-size:11px; color:#aaa;"><i class="fas fa-route"></i> ${mixersData[mix].trips} نقلة</div>
                    </div>
                    ${renderBadge(mixersData[mix].total, '#f39c12')}
                </div>`;
            }
            if (Object.keys(mixersData).length === 0) html += `<div style="color:#aaa; text-align:center;">لا يوجد</div>`;
            html += `</div></div>`;

            // Card 4
            html += `<div style="${cardStyle} #9b59b6;">
                <div style="padding:15px; border-bottom:1px solid rgba(255,255,255,0.1); font-weight:bold; color:#9b59b6;">
                    <i class="fas fa-id-card"></i> السائقين
                </div>
                <div style="padding:15px;">`;
            for (let drv in driversData) {
                html += `<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:10px; border-bottom:1px dashed rgba(255,255,255,0.1); padding-bottom:5px;">
                    <div style="color:var(--text-primary, #fff);">
                        <div style="font-weight:bold;">${drv}</div>
                        <div style="font-size:11px; color:#aaa;"><i class="fas fa-route"></i> ${driversData[drv].trips} نقلة</div>
                    </div>
                    ${renderBadge(driversData[drv].total, '#9b59b6')}
                </div>`;
            }
            if (Object.keys(driversData).length === 0) html += `<div style="color:#aaa; text-align:center;">لا يوجد</div>`;
            html += `</div></div>`;

            html += `</div>`;
            container.innerHTML = html;

        } catch (e) {
            console.error(e);
            container.innerHTML = '<div style="color:red; padding:20px;">Error loading data</div>';
        }
    }

    async function renderArchiveTable() {
        const tbody = document.getElementById('archive-tbody');
        if (!tbody) return;
        tbody.innerHTML = '<tr><td colspan="12" style="text-align:center;">جاري التحميل...</td></tr>';
        
        try {
            let invoices = await window.DB.getAll('concrete_invoices') || [];
            const allTrips = await window.DB.getAll('invoice_mixer_trips') || [];
            const pumps = mixers.filter(m => m.type && m.type.trim().startsWith('مضخ'));
            
            // Filter by station for employees
            const allowedStations = getUserAllowedStationIds();
            if (allowedStations) {
                invoices = invoices.filter(inv => allowedStations.includes(String(inv.warehouse_id)));
            }

            if (invoices.length === 0) {
                tbody.innerHTML = '<tr><td colspan="12" style="text-align:center; color:#7f8c8d;">لا توجد فواتير خرسانة في الأرشيف.</td></tr>';
                return;
            }
            
            invoices.reverse(); // newest first
            tbody.innerHTML = '';
            
            invoices.forEach(inv => {
                const targetName = inv.client_type === 'project' 
                    ? (projects.find(p => String(p.id) === String(inv.target_id))?.name || 'مشروع مجهول')
                    : (contacts.find(c => String(c.id) === String(inv.target_id))?.name || 'عميل مجهول');
                const statusHtml = `<span class="status-badge ${inv.status === 'مسجل' ? 'status-active' : (inv.status === 'غير مسددة' ? 'status-inactive' : 'status-maintenance')}">${inv.status || 'غير محدد'}</span>`;
                const rev = inv.total_revenue ? Number(inv.total_revenue).toLocaleString('ar-EG') : '0';
                const cost = inv.total_cost ? Number(inv.total_cost).toLocaleString('ar-EG') : '0';
                const lumpsumVal = parseFloat(inv.extra_lumpsum || 0);
                const lumpsumText = lumpsumVal > 0 ? Number(lumpsumVal).toLocaleString('ar-EG') : '-';
                
                let extraItemsText = '-';
                if (inv.extra_items && inv.extra_items.length > 0) {
                    extraItemsText = inv.extra_items.map(ex => {
                        const itm = allItems.find(i => String(i.id) === String(ex.item_id));
                        return (itm ? itm.name : 'صنف مجهول') + ': ' + ex.qty;
                    }).join('<br>');
                }
                let pumpName = '-';
                if (inv.pump_id) {
                    const pump = mixers.find(p => String(p.id) === String(inv.pump_id));
                    pumpName = pump ? pump.code : `مضخة #${inv.pump_id}`;
                }
                
                let pumpOpName = '-';
                if (inv.pump_operator_id) {
                    const op = employees.find(e => String(e.id) === String(inv.pump_operator_id));
                    pumpOpName = op ? op.name : `مشغل #${inv.pump_operator_id}`;
                }

                let stationOpName = '-';
                if (inv.station_operator_id) {
                    const op = employees.find(e => String(e.id) === String(inv.station_operator_id));
                    stationOpName = op ? op.name : `مشغل #${inv.station_operator_id}`;
                }

                const invoiceTrips = allTrips.filter(t => String(t.concrete_invoice_id) === String(inv.id));
                const totalTrips = invoiceTrips.reduce((sum, t) => sum + (parseInt(t.trips_count) || 1), 0);

                const isSettlementClosed = inv.settlement_closed === true || inv.settlement_closed === 'true' || String(inv.settlement_closed) === '1';
                const toggleBtnStyle = isSettlementClosed ? 'background:#64748b; color:#fff; margin-top:4px;' : 'background:#10b981; color:#fff; margin-top:4px;';
                const toggleBtnText = isSettlementClosed ? '🚫 مخفي بالتسويات' : '🟢 ظاهر بالتسويات';

                tbody.innerHTML += `
                    <tr>
                        <td><strong>#${inv.id}</strong><br><small style="color:var(--text-muted)">${inv.type}</small></td>
                        <td>${inv.date}</td>
                        <td>${targetName} <br><small>مُعرف: ${inv.target_id}</small></td>
                        <td style="font-weight:bold; color:var(--rm-accent)">${inv.billed_qty !== undefined && inv.billed_qty !== inv.total_qty ? `${inv.billed_qty} م³ <br><small style="color:var(--danger)">مُحمل: ${inv.total_qty}</small>` : `${inv.total_qty} م³`}</td>
                        <td>${extraItemsText}</td>
                        <td>${pumpName}</td>
                        <td>${pumpOpName}</td>
                        <td>${stationOpName}</td>
                        <td>${totalTrips}</td>
                        <td style="color:var(--success)">${rev}</td>
                        <td style="color:#d97706; font-weight:bold;">${lumpsumText}</td>
                        <td style="color:var(--danger)">${cost}</td>
                        <td>
                            <button class="action-btn" onclick="window.RMApp.viewInvoiceDetails(${inv.id})">🔍 التفاصيل</button>
                            <button class="action-btn" style="background:#f59e0b; color:#fff;" onclick="window.RMApp.editOperators(${inv.id})">✏️ تعديل المشغلين</button>
                            <button class="action-btn" style="background:var(--danger);" onclick="window.RMApp.deleteInvoice(${inv.id})">🗑️ حذف</button>
                            <button class="action-btn" style="${toggleBtnStyle}" onclick="window.RMApp.toggleSettlementVisibility(${inv.id})">${toggleBtnText}</button>
                        </td>
                    </tr>
                `;
            });
        } catch (e) {
            console.error(e);
            tbody.innerHTML = '<tr><td colspan="12" style="text-align:center; color:red;">خطأ أثناء جلب البيانات</td></tr>';
        }
    }

    async function viewInvoiceDetails(id) {
        try {
            document.getElementById('invoice-details-content').innerHTML = '<div style="text-align:center; padding:20px;">جاري تحميل البيانات... ⏳</div>';
            showModal('invoice-details-modal');

            const res = await fetch(`api.php?store=concrete_invoice_details&id=${id}`);
            const data = await res.json();

            if (data.error) {
                document.getElementById('invoice-details-content').innerHTML = `<div style="color:red; text-align:center; font-weight:bold;">${data.error}</div>`;
                return;
            }

            const info = data.orderInfo;
            const trips = data.trips || [];

            let mixName = allItems ? (allItems.find(i => String(i.id) === String(info.mix_item_id))?.name || "غير محدد") : "غير محدد";
            
            // Build Extra Items Section (Operational Costs)
            let extraItemsHtml = '';
            let totalDiesel = 0;
            if (info.extra_items && info.extra_items.length > 0) {
                let itemsList = info.extra_items.map(ex => {
                    let itmName = allItems ? (allItems.find(i => String(i.id) === String(ex.item_id))?.name || 'صنف مجهول') : 'صنف';
                    if (itmName.includes('سولار')) totalDiesel += parseFloat(ex.qty || 0);
                    return `<li>${itmName} - الكمية: ${ex.qty}</li>`;
                }).join('');
                
                extraItemsHtml = `
                    <div style="margin-top:20px;">
                        <h4 style="border-bottom:1px solid #ddd; padding-bottom:5px; margin-bottom:10px;">التكاليف التشغيلية (الإضافات والمحروقات)</h4>
                        <ul style="margin:0; padding-right:20px;">
                            ${itemsList}
                        </ul>
                        <div style="margin-top:10px; font-weight:bold; color:#d9534f;">إجمالي استهلاك السولار: ${totalDiesel} لتر</div>
                    </div>
                `;
            }

            // Build Trips Table
            let tripsRows = '';
            if (trips.length > 0) {
                tripsRows = trips.map((t, idx) => `
                    <tr>
                        <td style="border:1px solid #ccc; padding:8px; text-align:center;">${idx + 1}</td>
                        <td style="border:1px solid #ccc; padding:8px; text-align:center;">${t.mixer_code || '-'}</td>
                        <td style="border:1px solid #ccc; padding:8px; text-align:center;">${t.driver_name || '-'}</td>
                        <td style="border:1px solid #ccc; padding:8px; text-align:center;">${t.trips_count}</td>
                    </tr>
                `).join('');
            } else {
                tripsRows = `<tr><td colspan="4" style="border:1px solid #ccc; padding:8px; text-align:center;">لا توجد نقلات مسجلة</td></tr>`;
            }

            let tripsTableHtml = `
                <div style="margin-top:20px;">
                    <h4 style="border-bottom:1px solid #ddd; padding-bottom:5px; margin-bottom:10px;">تفاصيل النقلات (Trips)</h4>
                    <table style="width:100%; border-collapse:collapse; text-align:right;">
                        <thead style="background:#f9f9f9;">
                            <tr>
                                <th style="border:1px solid #ccc; padding:8px; text-align:center;">م</th>
                                <th style="border:1px solid #ccc; padding:8px; text-align:center;">الخلاطة (Mixer)</th>
                                <th style="border:1px solid #ccc; padding:8px; text-align:center;">اسم السائق</th>
                                <th style="border:1px solid #ccc; padding:8px; text-align:center;">عدد النقلات / الكمية</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${tripsRows}
                        </tbody>
                    </table>
                </div>
            `;

            let cashExpensesHtml = '';
            let totalCash = 0;
            if (data.cashExpenses && data.cashExpenses.length > 0) {
                let expensesRows = '';
                data.cashExpenses.forEach(exp => {
                    const amount = parseFloat(exp.amount) || 0;
                    totalCash += amount;
                    expensesRows += `
                        <tr style="border-bottom:1px solid #f1f5f9;">
                            <td style="padding:12px; color:#334155;">${exp.description || ''}</td>
                            <td style="padding:12px; color:#334155; font-weight:500;">${amount.toFixed(2)}</td>
                        </tr>
                    `;
                });
                
                cashExpensesHtml = `
                    <div style="margin-top:30px; border-top:2px dashed #cbd5e1; padding-top:20px;">
                        <h3 style="color:#1e293b; margin-bottom:15px; font-size:1.2rem;">المصروفات النقدية المباشرة (عهد)</h3>
                        <table style="width:100%; border-collapse:collapse; box-shadow:0 1px 3px rgba(0,0,0,0.1);">
                            <thead>
                                <tr style="background-color:#f8fafc; border-bottom:2px solid #e2e8f0; text-align:right;">
                                    <th style="padding:12px; font-weight:600; color:#475569;">بيان المصروف</th>
                                    <th style="padding:12px; font-weight:600; color:#475569; width:25%;">القيمة</th>
                                </tr>
                            </thead>
                            <tbody>
                                ${expensesRows}
                            </tbody>
                            <tfoot>
                                <tr style="background-color:#eff6ff; font-weight:bold; text-align:right;">
                                    <td style="padding:15px; color:#1d4ed8; border-top:2px solid #bfdbfe;">إجمالي المصروفات النقدية:</td>
                                    <td style="padding:15px; color:#1d4ed8; border-top:2px solid #bfdbfe; font-size:1.1rem;">${totalCash.toFixed(2)}</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                `;
            }

            let operationalCost = 0;
            if (info.extra_items && info.extra_items.length > 0) {
                info.extra_items.forEach(ex => {
                    const bal = window.balancesCache ? window.balancesCache[ex.item_id] : null;
                    const avgCost = bal ? parseFloat(bal.avgCost) || 0 : 0;
                    operationalCost += parseFloat(ex.qty || 0) * avgCost;
                });
            }
            
            let totalMaterialCost = parseFloat(info.total_cost || 0);
            let mixCost = totalMaterialCost - operationalCost;
            if (mixCost < 0) mixCost = totalMaterialCost; // Fallback if avgCost changed drastically

            let grandTotalCost = totalMaterialCost + totalCash;
            let totalRevenue = parseFloat(info.total_revenue || 0);
            
            let revenueHtml = '';
            if (totalRevenue > 0) {
                let profit = totalRevenue - grandTotalCost;
                let profitColor = profit >= 0 ? '#15803d' : '#b91c1c';
                let profitText = profit >= 0 ? 'صافي الربح' : 'صافي الخسارة';
                
                let extraLumpsumHtml = '';
                let extraLumpsumVal = parseFloat(info.extra_lumpsum || 0);
                if (extraLumpsumVal > 0) {
                    extraLumpsumHtml = `
                        <div style="background:#fffbeb; padding:10px; border-radius:5px; border:1px solid #f59e0b; margin-top:15px; text-align:center;">
                            <strong style="color:#d97706;">إضافات مفوترة على العميل (${info.extra_lumpsum_desc || 'مبلغ قطعي إضافي'}):</strong> 
                            <span style="font-weight:bold; color:#b45309; font-size:1.1rem;">${extraLumpsumVal.toLocaleString(undefined, {maximumFractionDigits: 0})} ج.م.</span>
                        </div>
                    `;
                }
                
                revenueHtml = `
                    ${extraLumpsumHtml}
                    <div style="display:flex; justify-content:center; gap:20px; margin-top:20px; font-size:1.2rem;">
                        <div style="background:#eff6ff; padding:15px; border-radius:5px; border:2px solid #3b82f6; width:45%;">
                            <strong style="color:#1d4ed8;">إيراد الفاتورة:</strong> <br/>
                            <span style="font-size:1.8rem; font-weight:bold; color:#1e40af;">${totalRevenue.toLocaleString(undefined, {maximumFractionDigits: 0})}</span>
                        </div>
                        <div style="background:${profit >= 0 ? '#f0fdf4' : '#fef2f2'}; padding:15px; border-radius:5px; border:2px solid ${profit >= 0 ? '#22c55e' : '#ef4444'}; width:45%;">
                            <strong style="color:${profitColor};">${profitText}:</strong> <br/>
                            <span style="font-size:1.8rem; font-weight:bold; color:${profitColor};">${profit.toLocaleString(undefined, {maximumFractionDigits: 0})}</span>
                        </div>
                    </div>
                `;
            }

            let grandTotalHtml = '';
            const allowedFinancialRoles = ['مدير عام', 'محاسب', 'مدير مالي', 'مدير'];
            const canViewFinancials = currentUser && allowedFinancialRoles.includes(currentUser.role);
            
            if (canViewFinancials) {
                grandTotalHtml = `
                    <div style="margin-top:30px; padding:20px; background:#f8fafc; border:2px solid #cbd5e1; border-radius:8px; text-align:center;">
                        <h2 style="margin:0; color:#334155; font-size:1.3rem;">الملخص المالي لأمر الصب</h2>
                        
                        <div style="display:flex; justify-content:center; gap:20px; margin-top:15px; font-size:1rem; color:#475569;">
                            <div style="background:#fff; padding:10px 15px; border-radius:5px; box-shadow:0 1px 2px rgba(0,0,0,0.1); flex:1;">
                                <strong>تكلفة الخرسانة:</strong> <br/>${mixCost.toLocaleString(undefined, {maximumFractionDigits: 0})}
                            </div>
                            <div style="background:#fff; padding:10px 15px; border-radius:5px; box-shadow:0 1px 2px rgba(0,0,0,0.1); flex:1;">
                                <strong>التكاليف التشغيلية (إضافات):</strong> <br/>${operationalCost.toLocaleString(undefined, {maximumFractionDigits: 0})}
                            </div>
                            <div style="background:#fff; padding:10px 15px; border-radius:5px; box-shadow:0 1px 2px rgba(0,0,0,0.1); flex:1;">
                                <strong>المصروفات النقدية (عهد):</strong> <br/>${totalCash.toLocaleString(undefined, {maximumFractionDigits: 0})}
                            </div>
                        </div>

                        <div style="font-size:1.5rem; font-weight:bold; color:#334155; margin-top:20px; border-top:1px dashed #cbd5e1; padding-top:10px;">
                            إجمالي التكاليف الشاملة: ${grandTotalCost.toLocaleString(undefined, {maximumFractionDigits: 0})}
                        </div>
                        
                        ${typeof extraLumpsumHtml !== 'undefined' ? extraLumpsumHtml : ''}
                        
                        ${revenueHtml}
                    </div>
                `;
            }

            let pumpOpName = 'غير محدد';
            if (info.pump_operator_id) {
                const op = employees.find(e => String(e.id) === String(info.pump_operator_id));
                pumpOpName = op ? op.name : `مشغل #${info.pump_operator_id}`;
            }

            let stationOpName = 'غير محدد';
            if (info.station_operator_id) {
                const op = employees.find(e => String(e.id) === String(info.station_operator_id));
                stationOpName = op ? op.name : `مشغل #${info.station_operator_id}`;
            }

            let html = `
                <div style="display:grid; grid-template-columns: 1fr 1fr; gap:15px; margin-bottom:15px; border:1px solid #ddd; padding:15px; border-radius:5px; background:#fdfdfd;">
                    <div><strong>رقم الأمر / الفاتورة:</strong> #${info.order_id}</div>
                    <div><strong>المحطة:</strong> ${info.warehouse_name || 'غير محدد'}</div>
                    
                    <div><strong>تاريخ الصب:</strong> ${info.order_date}</div>
                    <div><strong>اسم العميل:</strong> ${info.client_name}</div>
                    
                    <div><strong>موقع المشروع:</strong> ${info.project_location}</div>
                    <div><strong>نوع الخلطة:</strong> ${mixName}</div>
                    
                    <div><strong>الكمية المفوترة:</strong> ${info.billed_qty || info.total_qty} م³</div>
                    <div><strong>الكمية المحملة:</strong> ${info.total_qty} م³</div>
                    
                    <div><strong>المضخة المستخدمة:</strong> ${info.pump_name || 'غير محدد'} <small style="color:#777;">(${info.pump_code || ''})</small></div>
                    <div><strong>مشغل المضخة:</strong> ${pumpOpName}</div>
                    
                    <div><strong>مشغل المحطة:</strong> ${stationOpName}</div>
                    <div><strong>نوع العميل:</strong> ${info.client_type === 'project' ? 'مشروع داخلي' : 'عميل خارجي'}</div>
                </div>
                
                ${tripsTableHtml}
                ${extraItemsHtml}
                ${cashExpensesHtml}
                ${grandTotalHtml}
                
                <div style="text-align:center; margin-top:30px; font-size:12px; color:#777; border-top:1px dashed #ccc; padding-top:10px;">
                    تم إنشاء هذا المستند آلياً بواسطة نظام Easy ERP
                </div>
            `;
            
            document.getElementById('invoice-details-content').innerHTML = html;
        } catch (e) {
            console.error(e);
            document.getElementById('invoice-details-content').innerHTML = `<div style="color:red; text-align:center; font-weight:bold;">حدث خطأ أثناء جلب التفاصيل</div>`;
        }
    }

    function printInvoiceDetails() {
        window.print();
    }

    async function deleteInvoice(id) {
        if (!confirm('هل أنت متأكد من حذف مستند الخرسانة رقم ' + id + '؟\n\nتنبيه هام: إذا تم حذف هذا المستند، يجب عليك الذهاب إلى شاشة "القيود" وشاشة "المخازن" لحذف أي قيود أو حركات مخزنية تم إنشاؤها أوتوماتيكياً بواسطة هذا المستند لتجنب خلل الحسابات!')) {
            return;
        }
        
        try {
            document.body.style.cursor = 'wait';
            const res = await window.DB.remove('concrete_invoices', id);
            
            // Delete associated trips
            const allTrips = await window.DB.getAll('invoice_mixer_trips') || [];
            for (const trip of allTrips) {
                if (trip.concrete_invoice_id === id) {
                    await window.DB.remove('invoice_mixer_trips', trip.id);
                }
            }
            
            document.body.style.cursor = 'default';
            if (res.success || res.status === 'success') {
                alert('تم حذف المستند بنجاح. تذكر حذف القيود والحركات المخزنية المرتبطة.');
                renderArchiveTable();
            } else {
                alert('خطأ أثناء الحذف: ' + (res.message || ''));
            }
        } catch (e) {
            document.body.style.cursor = 'default';
            console.error(e);
            alert('حدث خطأ أثناء الحذف');
        }
    }

    async function toggleSettlementVisibility(id) {
        try {
            document.body.style.cursor = 'wait';
            const invoices = await window.DB.getAll('concrete_invoices') || [];
            const inv = invoices.find(i => String(i.id) === String(id));
            if (!inv) {
                alert('لم يتم العثور على أمر الصب المطلوب');
                document.body.style.cursor = 'default';
                return;
            }
            const isClosed = inv.settlement_closed === true || inv.settlement_closed === 'true' || String(inv.settlement_closed) === '1';
            inv.settlement_closed = !isClosed;
            await window.DB.update('concrete_invoices', inv);
            
            // Update in-memory arrays immediately
            if (typeof allConcreteInvoices !== 'undefined' && Array.isArray(allConcreteInvoices)) {
                const memIdx = allConcreteInvoices.findIndex(x => String(x.id) === String(id));
                if (memIdx !== -1) allConcreteInvoices[memIdx] = inv;
            }
            if (window.allConcreteInvoices && Array.isArray(window.allConcreteInvoices)) {
                const memIdx2 = window.allConcreteInvoices.findIndex(x => String(x.id) === String(id));
                if (memIdx2 !== -1) window.allConcreteInvoices[memIdx2] = inv;
            }

            document.body.style.cursor = 'default';
            renderArchiveTable();
        } catch(e) {
            document.body.style.cursor = 'default';
            console.error('Toggle visibility error:', e);
            alert('حدث خطأ أثناء التعديل: ' + (e.message || ''));
        }
    }

    function showModal(id) {
        document.getElementById(id).style.display = 'flex';
    }

    function closeModal(id) {
        document.getElementById(id).style.display = 'none';
    }
    
    // Close modal on outside click
    window.onclick = function(event) {
        if (event.target.classList.contains('modal')) {
            event.target.style.display = 'none';
        }
    };

    async function editOperators(invId) {
        try {
            document.getElementById('edit-operators-invoice-hidden-id').value = invId;
            document.getElementById('edit-operators-inv-id').innerText = '#' + invId;

            // Load invoices & trips
            const allInvs = await window.DB.getAll('concrete_invoices') || [];
            const inv = allInvs.find(i => String(i.id) === String(invId));
            if (!inv) return alert("المستند غير موجود");

            const allTrips = await window.DB.getAll('invoice_mixer_trips') || [];
            const trips = allTrips.filter(t => String(t.concrete_invoice_id) === String(invId));

            // Populate station operators dropdown
            const statSelect = document.getElementById('edit-station-op-select');
            const statOps = employees.filter(e => e.job_title && (e.job_title.includes('محطة') || e.job_title.includes('مشغل') || e.job_title.includes('خرسانة')));
            statSelect.innerHTML = '<option value="">-- بدون تحديد --</option>' + statOps.map(e => `<option value="${e.id}">${e.name} (${e.job_title || ''})</option>`).join('');
            if (inv.station_operator_id) statSelect.value = inv.station_operator_id;

            // Populate pump operators dropdown
            const pumpSelect = document.getElementById('edit-pump-op-select');
            const pumpOps = employees.filter(e => e.job_title && (e.job_title.includes('مضخ') || e.job_title.includes('مشغل') || e.job_title.includes('خلاط')));
            pumpSelect.innerHTML = '<option value="">-- بدون تحديد --</option>' + pumpOps.map(e => `<option value="${e.id}">${e.name} (${e.job_title || ''})</option>`).join('');
            if (inv.pump_operator_id) pumpSelect.value = inv.pump_operator_id;

            // Populate trips
            const tbody = document.getElementById('edit-operators-trips-tbody');
            if (trips.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" style="text-align:center; padding:15px; color:#64748b;">لا توجد رحلات مرتبطة بهذا الأمر</td></tr>';
            } else {
                const allDrivers = employees.filter(e => e.job_title && (e.job_title.includes('سائق') || e.job_title.includes('سواق')));
                const driversOptions = '<option value="">-- سائق غير محدد --</option>' + allDrivers.map(e => `<option value="${e.id}">${e.name}</option>`).join('');
                
                tbody.innerHTML = trips.map((t, idx) => {
                    const mx = mixers.find(m => String(m.id) === String(t.mixer_id));
                    const mxName = mx ? (mx.code || mx.name) : `خلاطة #${t.mixer_id}`;
                    const cap = t.capacity || (mx ? mx.capacity : 'غير محدد');
                    return `
                        <tr>
                            <td style="border:1px solid #cbd5e1; padding:8px;">${idx + 1}</td>
                            <td style="border:1px solid #cbd5e1; padding:8px;">${mxName}</td>
                            <td style="border:1px solid #cbd5e1; padding:8px;">${t.trips_count} سحبة <br><small style="color:#aaa;">سعة: ${cap}</small></td>
                            <td style="border:1px solid #cbd5e1; padding:8px;">
                                <select class="form-control trip-driver-select" data-trip-id="${t.id}" style="width:100%; padding:6px; border:1px solid #cbd5e1; border-radius:4px;">
                                    ${driversOptions}
                                </select>
                            </td>
                        </tr>
                    `;
                }).join('');

                setTimeout(() => {
                    const selects = tbody.querySelectorAll('.trip-driver-select');
                    selects.forEach((sel, idx) => {
                        if (trips[idx] && trips[idx].driver_id) {
                            sel.value = trips[idx].driver_id;
                        }
                    });
                }, 50);
            }

            showModal('edit-operators-modal');
        } catch (e) {
            console.error('Error opening edit modal:', e);
            alert("حدث خطأ أثناء تحميل البيانات للتعديل");
        }
    }

    async function saveOperators() {
        try {
            const invId = document.getElementById('edit-operators-invoice-hidden-id').value;
            if (!invId) return;

            const statOpId = document.getElementById('edit-station-op-select').value;
            const pumpOpId = document.getElementById('edit-pump-op-select').value;

            // 1. Update invoice
            const allInvs = await window.DB.getAll('concrete_invoices');
            const inv = allInvs.find(i => String(i.id) === String(invId));
            if (inv) {
                inv.station_operator_id = statOpId ? parseInt(statOpId) : null;
                inv.pump_operator_id = pumpOpId ? parseInt(pumpOpId) : null;
                await window.DB.update('concrete_invoices', inv);
            }

            // 2. Update trips
            const allTrips = await window.DB.getAll('invoice_mixer_trips');
            const selects = document.querySelectorAll('.trip-driver-select');
            for (let sel of selects) {
                const tripId = sel.getAttribute('data-trip-id');
                const driverId = sel.value;
                const trip = allTrips.find(t => String(t.id) === String(tripId));
                if (trip) {
                    trip.driver_id = driverId ? parseInt(driverId) : null;
                    const drv = employees.find(e => String(e.id) === String(driverId));
                    trip.driver_name = drv ? drv.name : '';
                    await window.DB.update('invoice_mixer_trips', trip);
                }
            }

            closeModal('edit-operators-modal');
            alert("تم تحديث المشغلين والسائقين بنجاح!");
            renderArchiveTable();
            renderRMDashboard();

        } catch (e) {
            console.error('Error saving operators:', e);
            alert("حدث خطأ أثناء حفظ التعديلات");
        }
    }

    function populateEmployeesDropdown(selectId, filterJob, jobTitle) {
        const select = document.getElementById(selectId);
        select.innerHTML = '<option value="">-- بدون تعيين --</option>';
        
        let filtered = employees;
        if (filterJob) {
            filtered = employees.filter(e => e.job_title && e.job_title.includes(jobTitle));
        }
        
        filtered.forEach(emp => {
            select.innerHTML += `<option value="${emp.id}">${emp.name}</option>`;
        });
    }

    function getStatusBadge(status) {
        switch(status) {
            case 'active': return '<span class="status-badge status-active">تعمل</span>';
            case 'maintenance': return '<span class="status-badge status-maintenance">صيانة</span>';
            case 'inactive': return '<span class="status-badge status-inactive">معطلة</span>';
            default: return '<span class="status-badge status-active">تعمل</span>';
        }
    }

    function getEmployeeName(id) {
        if (!id) return '-';
        const emp = employees.find(e => String(e.id) === String(id));
        return emp ? emp.name : '-';
    }

    // ======================
    // USER STATIONS HELPER
    // ======================
    function getUserAllowedStationIds() {
        if (typeof currentUser === 'undefined' || !currentUser) return null; // Admin or not loaded
        if (currentUser.role === 'مدير عام' || String(currentUser.role).toLowerCase() === 'admin') return null; // Admin sees all
        
        let allowed = [];
        if (currentUser.allowed_warehouses && currentUser.allowed_warehouses.length > 0) {
            allowed = currentUser.allowed_warehouses.map(w => String(w));
        }
        if (currentUser.warehouse_id && !allowed.includes(String(currentUser.warehouse_id))) {
            allowed.push(String(currentUser.warehouse_id));
        }
        
        return allowed.length > 0 ? allowed : null;
    }

    // ======================
    // MIXERS CRUD
    // ======================

    function getStationName(stationId) {
        if (!stationId) return '-- المحطة الأساسية --';
        const wh = warehouses.find(w => String(w.id) === String(stationId));
        return wh ? wh.name : 'غير معروف';
    }

    function renderMixers() {
        const tbody = document.getElementById('mixers-tbody');
        tbody.innerHTML = '';
        
        let filteredMixers = mixers;
        const allowedStations = getUserAllowedStationIds();
        
        if (allowedStations) {
            filteredMixers = mixers.filter(m => allowedStations.includes(String(m.station_id)));
        }
        
        if (filteredMixers.length === 0) {
            tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;">لا توجد خلاطات مضافة</td></tr>`;
            return;
        }
        
        filteredMixers.forEach(mx => {
            tbody.innerHTML += `
                <tr>
                    <td><strong>${mx.code || mx.id}</strong></td>
                    <td>${mx.type || 'خلاطة'}</td>
                    <td>${mx.plate || '-'}</td>
                    <td>${mx.capacity || 0}</td>
                    <td>${getEmployeeName(mx.driver_id)}</td>
                    <td>${getStationName(mx.station_id)}</td>
                    <td>${formatExpiryDate(mx.vehicle_license_expiry)}</td>
                    <td>${formatExpiryDate(mx.vehicle_insurance_expiry)}</td>
                    <td>${getStatusBadge(mx.status)}</td>
                    <td>
                        <button class="btn btn-primary" onclick="window.RMApp.editMixer(${mx.id})">تعديل</button>
                        <button class="btn btn-danger" style="background:#e74c3c; border:none;" onclick="window.RMApp.deleteMixer(${mx.id})">حذف</button>
                    </td>
                </tr>
            `;
        });
    }

    function populateStationDropdown(elementId) {
        const select = document.getElementById(elementId);
        select.innerHTML = '<option value="">-- المحطة الأساسية / بدون تحديد --</option>';
        warehouses.forEach(wh => {
            const opt = document.createElement('option');
            opt.value = wh.id;
            opt.textContent = wh.name;
            select.appendChild(opt);
        });
    }

    function showMixerModal() {
        document.getElementById('mixer-id').value = '';
        document.getElementById('mixer-type').value = 'خلاطة';
        document.getElementById('mixer-code').value = '';
        document.getElementById('mixer-plate').value = '';
        document.getElementById('mixer-capacity').value = '10';
        document.getElementById('mixer-status').value = 'active';
        document.getElementById('mixer-notes').value = '';
        
        document.getElementById('mixer-vehicle-license-expiry').value = '';
        document.getElementById('mixer-vehicle-insurance-expiry').value = '';
        document.getElementById('mixer-driver-license-preview').innerHTML = '';
        document.getElementById('mixer-vehicle-license-preview').innerHTML = '';
        document.getElementById('mixer-driver-license').value = '';
        document.getElementById('mixer-vehicle-license').value = '';
        
        // Hide magic link
        document.getElementById('mixer-magic-link-group').style.display = 'none';
        
        isSavingMixer = false;
        
        document.getElementById('mixer-modal-title').innerText = 'إضافة معدة / خلاطة';
        
        document.getElementById('mixer-driver-filter').checked = true;
        populateEmployeesDropdown('mixer-driver', true, 'سائق');
        populateStationDropdown('mixer-station');
        document.getElementById('mixer-station').value = '';
        
        showModal('mixer-modal');
    }

    function editMixer(id) {
        const mx = mixers.find(m => String(m.id) === String(id));
        if (!mx) return;
        
        document.getElementById('mixer-id').value = mx.id;
        document.getElementById('mixer-type').value = mx.type || 'خلاطة';
        document.getElementById('mixer-code').value = mx.code || '';
        document.getElementById('mixer-plate').value = mx.plate || '';
        document.getElementById('mixer-capacity').value = mx.capacity || '10';
        document.getElementById('mixer-status').value = mx.status || 'active';
        document.getElementById('mixer-notes').value = mx.notes || '';
        document.getElementById('mixer-vehicle-license-expiry').value = mx.vehicle_license_expiry || '';
        document.getElementById('mixer-vehicle-insurance-expiry').value = mx.vehicle_insurance_expiry || '';
        
        const dlPreview = document.getElementById('mixer-driver-license-preview');
        dlPreview.innerHTML = mx.driver_license_img ? `<img src="${mx.driver_license_img}" onclick="window.RMApp.previewImage(this.src)" style="cursor:pointer; max-width:80px; max-height:50px; border:1px solid #ccc; border-radius:4px; margin-top:5px; object-fit:cover;" title="اضغط للتكبير">` : '';
        const vlPreview = document.getElementById('mixer-vehicle-license-preview');
        vlPreview.innerHTML = mx.vehicle_license_img ? `<img src="${mx.vehicle_license_img}" onclick="window.RMApp.previewImage(this.src)" style="cursor:pointer; max-width:80px; max-height:50px; border:1px solid #ccc; border-radius:4px; margin-top:5px; object-fit:cover;" title="اضغط للتكبير">` : '';
        
        document.getElementById('mixer-driver-license').value = '';
        document.getElementById('mixer-vehicle-license').value = '';
        
        // Setup Magic Link
        const mlGroup = document.getElementById('mixer-magic-link-group');
        const mlInput = document.getElementById('mixer-magic-link');
        mlGroup.style.display = 'block'; // Always show in edit mode
        if (mx.driver_token) {
            const link = window.location.origin + window.location.pathname.replace(/[^/]*$/, '') + 'driver_update.php?token=' + mx.driver_token;
            mlInput.value = link;
        } else {
            mlInput.value = 'اضغط على زر (حفظ) بالأسفل لتوليد الرابط أولاً...';
        }

        document.getElementById('mixer-modal-title').innerText = 'تعديل معدة / خلاطة';
        
        // Populate dropdown appropriately
        const emp = employees.find(e => String(e.id) === String(mx.driver_id));
        let isDriver = emp ? (emp.job_title && emp.job_title.includes('سائق')) : true;
        
        document.getElementById('mixer-driver-filter').checked = isDriver;
        populateEmployeesDropdown('mixer-driver', isDriver, 'سائق');
        document.getElementById('mixer-driver').value = mx.driver_id || '';
        
        populateStationDropdown('mixer-station');
        document.getElementById('mixer-station').value = mx.station_id || '';
        
        showModal('mixer-modal');
    }

    async function saveMixer() {
        if (isSavingMixer) return;
        isSavingMixer = true;
        
        try {
            const id = document.getElementById('mixer-id').value;
            const data = {
                type: document.getElementById('mixer-type').value,
                code: document.getElementById('mixer-code').value.trim(),
                plate: document.getElementById('mixer-plate').value.trim(),
                capacity: document.getElementById('mixer-capacity').value,
                driver_id: document.getElementById('mixer-driver').value,
                station_id: document.getElementById('mixer-station').value,
                status: document.getElementById('mixer-status').value,
                notes: document.getElementById('mixer-notes').value.trim(),
                vehicle_license_expiry: document.getElementById('mixer-vehicle-license-expiry').value,
                vehicle_insurance_expiry: document.getElementById('mixer-vehicle-insurance-expiry').value
            };
            
            const driverLicenseFile = document.getElementById('mixer-driver-license').files[0];
            if (driverLicenseFile) {
                data.driver_license_img = await fileToBase64(driverLicenseFile);
            } else if (id) {
                const existing = mixers.find(m => m.id == id);
                if (existing && existing.driver_license_img) data.driver_license_img = existing.driver_license_img;
            }

            const vehicleLicenseFile = document.getElementById('mixer-vehicle-license').files[0];
            if (vehicleLicenseFile) {
                data.vehicle_license_img = await fileToBase64(vehicleLicenseFile);
            } else if (id) {
                const existing = mixers.find(m => m.id == id);
                if (existing && existing.vehicle_license_img) data.vehicle_license_img = existing.vehicle_license_img;
            }
            
            if (!data.code || !data.capacity) {
                alert('يرجى إدخال الحقول الإجبارية (الكود والسعة)');
                isSavingMixer = false;
                return;
            }

            if (id) {
                data.id = id;
                await window.DB.update('mixers', data);
            } else {
                await window.DB.add('mixers', data);
            }
            closeModal('mixer-modal');
            await loadData();
        } catch (e) {
            console.error('Error saving mixer:', e);
            alert('حدث خطأ أثناء الحفظ');
        } finally {
            isSavingMixer = false;
        }
    }

    async function deleteMixer(id) {
        if (!confirm('هل أنت متأكد من حذف هذه الخلاطة؟')) return;
        try {
            await window.DB.remove('mixers', id);
            await loadData();
        } catch (e) {
            console.error(e);
            alert('حدث خطأ أثناء الحذف');
        }
    }

    // ======================
    

    function updateStationDropdowns() {
        const whSelect = document.getElementById('batch-warehouse');
        const stationId = whSelect ? whSelect.value : null;

        if (stationId) {
            localStorage.setItem('rm_favorite_warehouse', stationId);
        }

        // Filter Pumps
        const pumpSelect = document.getElementById('batch-pump');
        if (pumpSelect) {
            let filteredPumps = mixers.filter(m => m.type && m.type.trim().startsWith('مضخ'));
            if (stationId) {
                const pumps = mixers.filter(m => m.type && m.type.trim().startsWith('مضخ'));
                filteredPumps = pumps.filter(p => {
                    const stId = p.station || p.station_id;
                    return !stId || String(stId) === String(stationId);
                });
            }
            pumpSelect.innerHTML = '<option value="">بدون مضخة (صب مباشر)</option>' + 
                filteredPumps.map(p => `<option value="${p.id}">${p.code || 'مضخة ' + p.id} - ${p.plate || ''}</option>`).join('');

            // Restore favorite pump if available in the new list
            const favPump = localStorage.getItem('rm_favorite_pump');
            if (favPump && filteredPumps.find(p => String(p.id) === favPump)) {
                pumpSelect.value = favPump;
                handlePumpChange();
            }
        }

        // Re-render trips to filter mixers
        renderBatchTripsTable();
    }

    // ======================
    // BATCH ENTRY LOGIC
    // ======================

    function populateBatchForm() {
        const whSelect = document.getElementById('batch-warehouse');
        
        let allowedWhs = warehouses.filter(w => w.name && (w.name.includes("محطة") || w.name.includes("خرسان")));
        const allowedStations = getUserAllowedStationIds();
        if (allowedStations) {
            allowedWhs = allowedWhs.filter(w => allowedStations.includes(String(w.id)));
        }
        if (whSelect) {
            whSelect.innerHTML = '<option value="">اختر محطة</option>' + allowedWhs.map(w => `<option value="${w.id}">${w.name || "محطة " + w.id}</option>`).join("");
        }

        // Apply Station Multi-Tenancy Rules
        if (allowedStations && allowedStations.length === 1) {
            whSelect.value = allowedStations[0];
            whSelect.disabled = true;
        } else {
            whSelect.disabled = false;
            const favWh = localStorage.getItem('rm_favorite_warehouse');
            if (favWh && allowedWhs.find(w => String(w.id) === favWh)) {
                whSelect.value = favWh;
            }
        }

        // Add event listener to update pumps and mixers when station changes
        whSelect.addEventListener('change', () => { updateStationDropdowns();  });

        const targetSelect = document.getElementById('batch-target');
        let projOptions = '<optgroup label="المشاريع (توريد داخلي)">' + 
            projects.filter(p => p && (!p.status || p.status === 'active' || p.status === 'مستمر')).map(p => `<option value="project_${p.id}">${p.name || 'مشروع ' + p.id}</option>`).join('') + 
            '</optgroup>';
        let contOptions = '<optgroup label="العملاء (مبيعات خارجية)">' + 
            contacts.map(c => `<option value="contact_${c.id}">${c.name || 'عميل ' + c.id}</option>`).join('') + 
            '</optgroup>';
        targetSelect.innerHTML = '<option value="">اختر التوجيه</option>' + projOptions + contOptions;

        const mixSelect = document.getElementById('batch-mix');
        mixSelect.innerHTML = '<option value="">اختر الخلطة (الصنف)</option>' + 
            mixItems.map(m => `<option value="${m.id}" data-price="${m.price || 0}">${m.name || 'خلطة ' + m.id}</option>`).join('');

        const pumpOpSelect = document.getElementById('batch-pump-operator');
        if (pumpOpSelect) {
            const pumpOps = employees.filter(e => e.job_title && (e.job_title.includes('سائق') || e.job_title.includes('مشغل') || e.job_title.includes('مضخة')));
            pumpOpSelect.innerHTML = '<option value="">غير محدد</option>' + 
                pumpOps.map(e => `<option value="${e.id}">${e.name}</option>`).join('');
        }

        const stationOpSelect = document.getElementById('batch-station-operator');
        if (stationOpSelect) {
            const stationOps = employees.filter(e => e.job_title && (e.job_title.includes('محطة') || e.job_title.includes('مشغل') || e.job_title.includes('مدير')));
            stationOpSelect.innerHTML = '<option value="">غير محدد</option>' + 
                stationOps.map(e => `<option value="${e.id}">${e.name}</option>`).join('');

            const favStationOp = localStorage.getItem('rm_favorite_station_op');
            if (favStationOp) stationOpSelect.value = favStationOp;
            
            stationOpSelect.addEventListener('change', () => {
                if (stationOpSelect.value) {
                    localStorage.setItem('rm_favorite_station_op', stationOpSelect.value);
                } else {
                    localStorage.removeItem('rm_favorite_station_op');
                }
            });
        }

        // Initialize pumps based on selected station
        updateStationDropdowns();
        

        // Restore favorite project if exists
        const favTarget = localStorage.getItem('rm_favorite_target');
        if (favTarget) {
            targetSelect.value = favTarget;
            handleTargetChange();
        }

        renderBatchTripsTable();
    }

    function handlePumpChange() {
        const pumpSelect = document.getElementById('batch-pump');
        if (pumpSelect && pumpSelect.value) {
            localStorage.setItem('rm_favorite_pump', pumpSelect.value);
        } else {
            localStorage.removeItem('rm_favorite_pump');
        }

        const pumpId = pumpSelect ? pumpSelect.value : null;
        const opSelect = document.getElementById('batch-pump-operator');
        if (!pumpId || !opSelect) return;
        
        const pump = mixers.find(p => p.id == pumpId);
        if (pump && (pump.driver_id || pump.operator_id)) {
            opSelect.value = pump.driver_id || pump.operator_id;
        } else {
            opSelect.value = "";
        }
    }

    async function handleTargetChange() {
        const targetSelect = document.getElementById('batch-target');
        if (targetSelect && targetSelect.value) {
            localStorage.setItem('rm_favorite_target', targetSelect.value);
        }
        const targetVal = document.getElementById('batch-target').value;
        const priceGroup = document.getElementById('batch-price-group');
        const taxGroup = document.getElementById('batch-tax-group');
        const lumpsumGroup = document.getElementById('batch-lumpsum-group');
        const lumpsumDescGroup = document.getElementById('batch-lumpsum-desc-group');
        const priceInput = document.getElementById('batch-price');
        const mixSelect = document.getElementById('batch-mix');

        if (targetVal && targetVal.startsWith('contact_')) {
            priceGroup.style.display = 'block';
            if (taxGroup) taxGroup.style.display = 'block';
            if (lumpsumGroup) lumpsumGroup.style.display = 'block';
            if (lumpsumDescGroup) lumpsumDescGroup.style.display = 'block';
            if (mixSelect && mixSelect.value) {
                const opt = mixSelect.options[mixSelect.selectedIndex];
                let defaultPrice = opt ? parseFloat(opt.getAttribute('data-price') || 0) : 0;
                
                try {
                    let allInvoices = await window.DB.getAll('concrete_invoices');
                    if (allInvoices) {
                        let clientId = targetVal.split('_')[1];
                        let mixId = mixSelect.value;
                        
                        let clientInvoices = allInvoices.filter(i => String(i.target_id) === String(clientId) && String(i.client_type) === 'contact' && String(i.mix_item_id) === String(mixId));
                        
                        if (clientInvoices.length > 0) {
                            // Sort by ID descending to get the latest invoice
                            clientInvoices.sort((a, b) => b.id - a.id);
                            let lastInvoice = clientInvoices[0];
                            let lastPrice = parseFloat(lastInvoice.total_revenue) / parseFloat(lastInvoice.total_qty);
                            if (!isNaN(lastPrice) && lastPrice > 0) {
                                priceInput.value = lastPrice.toFixed(2);
                                return;
                            }
                        }
                    }
                } catch (e) { console.error('Error fetching last price:', e); }
                
                // Fallback to default price
                priceInput.value = defaultPrice;
            }
        } else {
            priceGroup.style.display = 'none';
            if (taxGroup) taxGroup.style.display = 'none';
            if (lumpsumGroup) lumpsumGroup.style.display = 'none';
            if (lumpsumDescGroup) lumpsumDescGroup.style.display = 'none';
        }
    }

    document.getElementById('batch-mix')?.addEventListener('change', () => {
        handleTargetChange();
        
    });

    document.getElementById('batch-warehouse')?.addEventListener('change', () => {
        updateStationDropdowns();
        
    });

        function addExtraItemRow() {
        batchExtraItems.push({ item_id: '', qty: 1 });
        renderExtraItemsTable();
    }

    function removeExtraItemRow(idx) {
        batchExtraItems.splice(idx, 1);
        renderExtraItemsTable();
    }

    function updateExtraItemRow(idx, field, value) {
        batchExtraItems[idx][field] = value;
    }

    function renderExtraItemsTable() {
        const tbody = document.getElementById('batch-extra-items-tbody');
        if (!tbody) return;
        
        const itOptions = allItems.map(i => `<option value="${i.id}">${i.name}</option>`).join('');

        tbody.innerHTML = batchExtraItems.map((item, idx) => `
            <tr>
                <td style="padding:10px;">
                    <select class="form-control" onchange="window.RMApp.updateExtraItemRow(${idx}, 'item_id', this.value)">
                        <option value="">اختر الصنف</option>
                        ${itOptions.replace(`value="${item.item_id}"`, `value="${item.item_id}" selected`)}
                    </select>
                </td>
                <td style="padding:10px;">
                    <input type="number" class="form-control" min="0" step="0.01" value="${item.qty}" onchange="window.RMApp.updateExtraItemRow(${idx}, 'qty', this.value)">
                </td>
                <td style="padding:10px;">
                    <button class="btn-delete" style="padding:4px 8px;" onclick="window.RMApp.removeExtraItemRow(${idx})">حذف</button>
                </td>
            </tr>
        `).join('');
    }

    function recalculateTotalQty() {
        let total = 0;
        batchTrips.forEach(trip => {
            if (trip.mixer_id) {
                const capacity = parseFloat(trip.capacity || 0);
                const count = parseFloat(trip.trips_count || 1);
                total += (capacity * count);
            }
        });
        if (total > 0) {
            document.getElementById('batch-qty').value = total.toFixed(2);
        } else {
            document.getElementById('batch-qty').value = '';
        }
    }

    function addTripRow() {
        batchTrips.push({ mixer_id: '', driver_id: '', trips_count: 1, capacity: '' });
        renderBatchTripsTable();
        recalculateTotalQty();
    }

    function removeTripRow(idx) {
        batchTrips.splice(idx, 1);
        renderBatchTripsTable();
        recalculateTotalQty();
    }

    function updateTripRow(idx, field, val) {
        batchTrips[idx][field] = val;
        
        // Auto-select driver and capacity if mixer changes
        if (field === 'mixer_id') {
            const mx = mixers.find(m => m.id == val);
            if (mx) {
                if (mx.driver_id) batchTrips[idx].driver_id = mx.driver_id;
                batchTrips[idx].capacity = parseFloat(mx.capacity || 10);
            }
        }
        renderBatchTripsTable();
        recalculateTotalQty();
    }

    function renderBatchTripsTable() {
        const tbody = document.getElementById('batch-trips-tbody');
        if (!tbody) return;
        
        if (batchTrips.length === 0) {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align:center; padding: 20px;">لم يتم إضافة نقلات. <a href="#" onclick="window.RMApp.addTripRow()">إضافة نقلة الآن</a></td></tr>';
            return;
        }

        const whSelect = document.getElementById('batch-warehouse');
        const stationId = whSelect ? whSelect.value : null;

        let filteredMixers = mixers;
        if (stationId) {
            filteredMixers = mixers.filter(m => !m.station_id || String(m.station_id) === String(stationId));
        }

        const mxOptions = '<option value="">اختر الخلاطة</option>' + 
            filteredMixers.map(m => `<option value="${m.id}">${m.code || 'خلاطة ' + m.id}</option>`).join('');
            
        const drOptions = '<option value="">بدون سائق / السائق الافتراضي</option>' + 
            employees.map(e => `<option value="${e.id}">${e.name}</option>`).join('');

        tbody.innerHTML = batchTrips.map((trip, idx) => `
            <tr>
                <td style="padding:10px;">
                    <select class="form-control" onchange="window.RMApp.updateTripRow(${idx}, 'mixer_id', this.value)">
                        ${mxOptions.replace(`value="${trip.mixer_id}"`, `value="${trip.mixer_id}" selected`)}
                    </select>
                </td>
                <td style="padding:10px;">
                    <select class="form-control" onchange="window.RMApp.updateTripRow(${idx}, 'driver_id', this.value)">
                        ${drOptions.replace(`value="${trip.driver_id}"`, `value="${trip.driver_id}" selected`)}
                    </select>
                </td>
                <td style="padding:10px;">
                    <input type="number" class="form-control" min="0" step="0.1" value="${trip.capacity || ''}" onchange="window.RMApp.updateTripRow(${idx}, 'capacity', this.value)">
                </td>
                <td style="padding:10px;">
                    <input type="number" class="form-control" min="1" value="${trip.trips_count}" onchange="window.RMApp.updateTripRow(${idx}, 'trips_count', this.value)">
                </td>
                <td style="padding:10px;">
                    <button class="btn btn-danger" onclick="window.RMApp.removeTripRow(${idx})">حذف</button>
                </td>
            </tr>
        `).join('');
    }

    let isSubmittingBatch = false;
    async function submitBatch() {
        if (isSubmittingBatch) return;
        isSubmittingBatch = true;

        const warehouse_id = document.getElementById('batch-warehouse').value;
        const targetVal = document.getElementById('batch-target').value;
        const mix_item_id = document.getElementById('batch-mix').value;
        const total_qty = document.getElementById('batch-qty').value;
        const billed_qty_input = document.getElementById('billed-qty').value;
        const selling_price = document.getElementById('batch-price').value;
        const tax_percent = document.getElementById('batch-tax-percent') ? document.getElementById('batch-tax-percent').value : 0;

        if (!warehouse_id || !targetVal || !mix_item_id || !total_qty) {
            alert('يرجى تعبئة كافة الحقول الإجبارية!');
            isSubmittingBatch = false;
            return;
        }

        if (batchTrips.length === 0) {
            if(!confirm('لم تقم بإضافة أي نقلات بالخلاطات. هل تريد حفظ الفاتورة المخزنية والمالية بدون نقلات؟')) {
                isSubmittingBatch = false;
                return;
            }
        }
        
        // Validate trips
        for (let i=0; i<batchTrips.length; i++) {
            if (!batchTrips[i].mixer_id) {
                alert('يرجى اختيار الخلاطة لكل النقلات المدخلة.');
                isSubmittingBatch = false;
                return;
            }
        }

        const [client_type, target_id] = targetVal.split('_'); // e.g., "project_5" or "contact_2"
        const pump_id = document.getElementById('batch-pump') ? document.getElementById('batch-pump').value : '';
        const pump_op_id = document.getElementById('batch-pump-operator') ? document.getElementById('batch-pump-operator').value : '';
        const station_op_id = document.getElementById('batch-station-operator') ? document.getElementById('batch-station-operator').value : '';

        // Validate inventory balances
        if (window.balancesCache) {
            let requiredStock = {};
            
            const mixDef = mixItems.find(m => m.id == mix_item_id);
            if (mixDef && mixDef.bom) {
                mixDef.bom.forEach(b => {
                    requiredStock[b.item_id] = (requiredStock[b.item_id] || 0) + (parseFloat(b.qty) * parseFloat(total_qty));
                });
            }
            
            batchExtraItems.forEach(ex => {
                if(ex.item_id && ex.qty > 0) {
                    requiredStock[ex.item_id] = (requiredStock[ex.item_id] || 0) + parseFloat(ex.qty);
                }
            });
            
            let insufficientItems = [];
            for (let item_id in requiredStock) {
                const requiredQty = requiredStock[item_id];
                const bal = window.balancesCache[item_id];
                const available = (bal && bal.warehouses && bal.warehouses[warehouse_id]) ? bal.warehouses[warehouse_id] : 0;
                if (available < requiredQty) {
                    const itemObj = allItems.find(i => i.id == item_id);
                    insufficientItems.push(`- ${itemObj ? itemObj.name : 'صنف غير معروف'} (المطلوب: ${requiredQty.toFixed(2)}, المتاح: ${available.toFixed(2)})`);
                }
            }
            
            if (insufficientItems.length > 0) {
                alert('لا يمكن إتمام الفاتورة! رصيد المخزن المحدد لا يكفي للأصناف التالية:\n' + insufficientItems.join('\n'));
                isSubmittingBatch = false;
                return;
            }
        }

        // Calculate current cost for raw materials
        const mixDef = mixItems.find(m => m.id == mix_item_id);
        const costs_map = {};
        if (mixDef && mixDef.bom) {
            mixDef.bom.forEach(b => {
                const bal = window.balancesCache ? window.balancesCache[b.item_id] : null;
                costs_map[b.item_id] = bal ? bal.avgCost : 0;
            });
        }
        batchExtraItems.forEach(e => {
            const bal = window.balancesCache ? window.balancesCache[e.item_id] : null;
            costs_map[e.item_id] = bal ? bal.avgCost : 0;
        });

        const payload = {
            warehouse_id: parseInt(warehouse_id),
            client_type: client_type,
            target_id: parseInt(target_id),
            mix_item_id: parseInt(mix_item_id),
            pump_id: pump_id ? parseInt(pump_id) : null,
            pump_operator_id: pump_op_id ? parseInt(pump_op_id) : null,
            station_operator_id: station_op_id ? parseInt(station_op_id) : null,
            total_qty: parseFloat(total_qty),
            billed_qty: billed_qty_input ? parseFloat(billed_qty_input) : parseFloat(total_qty),
            selling_price: parseFloat(selling_price) || 0,
            tax: parseFloat(tax_percent) || 0,
            extra_lumpsum: document.getElementById('batch-extra-lumpsum') ? (parseFloat(document.getElementById('batch-extra-lumpsum').value) || 0) : 0,
            extra_lumpsum_desc: document.getElementById('batch-extra-lumpsum-desc') ? document.getElementById('batch-extra-lumpsum-desc').value : '',
            trips_array: batchTrips,
            extra_items: batchExtraItems,
            costs_map: costs_map,
            date: new Date(Date.now() - new Date().getTimezoneOffset() * 60000).toISOString().slice(0, 19).replace('T', ' '),
            user_id: currentUser ? currentUser.id : null,
            user_name: currentUser ? currentUser.name : 'مسؤول'
        };

        document.body.style.cursor = 'wait';

        try {
            const res = await fetch('api.php?store=process_concrete_batch', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(payload)
            });
            const data = await res.json();
            if (data.success || data.status === 'success') {
                alert('تم حفظ الفاتورة وإنشاء القيود والحركات المخزنية بنجاح!');
                document.getElementById('batch-qty').value = '';
                document.getElementById('batch-price').value = '';
                if (document.getElementById('batch-diesel')) document.getElementById('batch-diesel').value = '0';
                if (document.getElementById('batch-extra-lumpsum')) document.getElementById('batch-extra-lumpsum').value = '0';
                if (document.getElementById('batch-extra-lumpsum-desc')) document.getElementById('batch-extra-lumpsum-desc').value = '';
                batchTrips = [];
                batchExtraItems = [];
                renderBatchTripsTable();
                renderExtraItemsTable();
            } else {
                alert('خطأ: ' + (data.error || 'غير معروف'));
            }
        } catch (e) {
            console.error(e);
            alert('حدث خطأ أثناء الاتصال بالخادم.');
        } finally {
            isSubmittingBatch = false;
            document.body.style.cursor = 'default';
        }
    }

    async function createWarehouse() {
        const name = prompt('أدخل اسم المحطة (المخزن) الجديد:');
        if (!name || name.trim() === '') return;
        try {
            document.body.style.cursor = 'wait';
            await window.DB.add('warehouses', { name: name.trim(), type: 'ready_mix' });
            await loadData();
            alert('تمت إضافة المحطة بنجاح');
        } catch (e) {
            console.error(e);
            alert('حدث خطأ أثناء إضافة المحطة');
        } finally {
            document.body.style.cursor = 'default';
        }
    }

    // ======================
    

    // ======================
    // BOOTSTRAP
    // ======================
    
    window.addEventListener('DOMContentLoaded', init);

    function shareMixerMagicLink() {
        const link = document.getElementById('mixer-magic-link').value;
        if (!link || link.includes('اضغط على زر')) {
            alert('الرجاء الضغط على (حفظ) أولاً لتوليد الرابط.');
            return;
        }
        const text = encodeURIComponent(`رابط التحديث الخاص بخلاطتك:\n${link}`);
        window.open(`https://wa.me/?text=${text}`, '_blank');
    }

    // Export public methods
    
    
    function addScenarioRow() {
        const container = document.getElementById('calc-scenario-container');
        if (!container) return;
        
        let mixes = typeof mixItems !== 'undefined' ? mixItems : [];
        let optionsHtml = '<option value="">-- اختر خلطة --</option>' + mixes.map(m => `<option value="${m.id}">${m.name}</option>`).join('');
        
        const rowId = 'scen_' + Date.now() + Math.floor(Math.random()*1000);
        const rowDiv = document.createElement('div');
        rowDiv.className = 'calc-scenario-row';
        rowDiv.id = rowId;
        rowDiv.style.display = 'flex';
        rowDiv.style.gap = '10px';
        rowDiv.style.marginBottom = '10px';
        rowDiv.style.alignItems = 'flex-end';
        
        rowDiv.innerHTML = `
            <div style="flex:2;">
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:12px; color:#1e293b;">الخلطة المراد إنتاجها:</label>
                <select class="form-control calc-mix-select" style="width:100%; border:1px solid #cbd5e1; padding:6px; border-radius:5px;" onchange="if(window.RMApp) window.RMApp.runProdCalculator()">${optionsHtml}</select>
            </div>
            <div style="flex:1;">
                <label style="display:block; margin-bottom:5px; font-weight:bold; font-size:12px; color:#1e293b;">الكمية (م³):</label>
                <input type="number" class="form-control calc-qty-input" style="width:100%; border:1px solid #cbd5e1; padding:6px; border-radius:5px;" value="0" min="0" step="0.5" oninput="if(window.RMApp) window.RMApp.runProdCalculator()">
            </div>
            <div style="width:30px;">
                <button type="button" onclick="document.getElementById('${rowId}').remove(); if(window.RMApp) window.RMApp.runProdCalculator();" style="background:#ef4444; color:#fff; border:none; border-radius:3px; padding:6px 0; width:100%; cursor:pointer;" title="إزالة"><i class="fas fa-times"></i></button>
            </div>
        `;
        
        container.appendChild(rowDiv);
    }
    
    function initProdCalculator() {
        try {
            const stSelect = document.getElementById('calc-station');
            if (stSelect) {
                const allowedIds = typeof getUserAllowedStationIds === 'function' ? getUserAllowedStationIds() : null;
                let displayStations = typeof warehouses !== 'undefined' ? warehouses : [];
                
                if (allowedIds !== null) {
                    displayStations = displayStations.filter(w => allowedIds.includes(String(w.id)));
                }
                stSelect.innerHTML = '<option value="">-- اختر محطة --</option>' + displayStations.map(s => `<option value="${s.id}">${s.name}</option>`).join('');
            }
            
            const container = document.getElementById('calc-scenario-container');
            if (container) {
                container.innerHTML = ''; // clear
                addScenarioRow(); // add initial empty row
            }
            
            runProdCalculator();
        } catch(e) {
            console.error("Error in initProdCalculator:", e);
            const resDiv = document.getElementById('calc-result');
            if(resDiv) resDiv.innerHTML = '<span style="color:red">حدث خطأ: ' + e.message + '</span>';
        }
    }

    function runProdCalculator() {
        const resDiv = document.getElementById('calc-result');
        if (!resDiv) return;
        
        const whId = document.getElementById('calc-station')?.value;
        if (!whId) {
            resDiv.innerHTML = 'الرجاء اختيار المحطة أولاً.';
            resDiv.style.color = '#475569';
            return;
        }

        if (typeof window.balancesCache === 'undefined' || !window.balancesCache) {
            resDiv.innerHTML = '<i class="fas fa-exclamation-circle" style="color:#ef4444;"></i> الأرصدة غير محملة. الرجاء فتح النظام الرئيسي ثم العودة.';
            resDiv.style.color = '#b91c1c';
            return;
        }

        // Collect Scenario Data
        const rows = document.querySelectorAll('.calc-scenario-row');
        let scenarioData = [];
        let totalTargetQty = 0;
        
        rows.forEach(row => {
            let select = row.querySelector('.calc-mix-select');
            let qtyInput = row.querySelector('.calc-qty-input');
            if (select && qtyInput && select.value) {
                let qty = parseFloat(qtyInput.value) || 0;
                scenarioData.push({
                    mixId: select.value,
                    mixName: select.options[select.selectedIndex].text,
                    qty: qty
                });
                totalTargetQty += qty;
            }
        });

        if (scenarioData.length === 0) {
            resDiv.innerHTML = 'الرجاء اختيار خلطة واحدة على الأقل وإدخال كمية لإنتاجها.';
            resDiv.style.color = '#475569';
            return;
        }

        // Aggregate BOM
        let aggregatedMats = {};
        scenarioData.forEach(scenario => {
            const mixObj = typeof mixItems !== 'undefined' ? mixItems.find(m => String(m.id) === String(scenario.mixId)) : null;
            if (mixObj && mixObj.bom) {
                mixObj.bom.forEach(comp => {
                    const rawItemId = comp.item_id;
                    const requiredQtyPerM3 = parseFloat(comp.qty) || 0;
                    if (requiredQtyPerM3 <= 0) return;

                    const totalRequiredQty = requiredQtyPerM3 * scenario.qty;

                    if (!aggregatedMats[rawItemId]) {
                        const balInfo = window.balancesCache[rawItemId];
                        const stockQty = (balInfo && balInfo.warehouses) ? parseFloat(balInfo.warehouses[whId] || 0) : 0;
                        
                        let matName = 'خامة مجهولة';
                        let baseUnit = 'كجم';
                        let altUnit = '';
                        let convFactor = 1;
                        if (typeof allItems !== 'undefined') {
                            const itemObj = allItems.find(i => String(i.id) === String(rawItemId));
                            if (itemObj) {
                                matName = itemObj.name || itemObj.item_name || itemObj.title || 'صنف بدون اسم';
                                baseUnit = itemObj.unit || 'كجم';
                                altUnit = itemObj.alt_unit || '';
                                convFactor = parseFloat(itemObj.conv_factor) || 1;
                            }
                        }
                        
                        aggregatedMats[rawItemId] = {
                            rawItemId, matName, baseUnit, altUnit, convFactor, stockQty,
                            reqPerMix: {},
                            totalReq: 0
                        };
                    }
                    
                    aggregatedMats[rawItemId].reqPerMix[scenario.mixId] = (aggregatedMats[rawItemId].reqPerMix[scenario.mixId] || 0) + totalRequiredQty;
                    aggregatedMats[rawItemId].totalReq += totalRequiredQty;
                });
            }
        });

        if (Object.keys(aggregatedMats).length === 0) {
            resDiv.innerHTML = '<i class="fas fa-exclamation-circle" style="color:#f59e0b;"></i> الخلطات المختارة ليس لها مكونات مسجلة بالنظام.';
            resDiv.style.color = '#b45309';
            return;
        }

        let minPossibleScale = Infinity;
        let limitingMat = null;

        // Build Table
        let tableHtml = '<div style="overflow-x:auto;"><table class="calc-table-hover" style="width:100%; border-collapse:collapse; margin-top:15px; font-size:11px; text-align:right;">';
        let thead = '<tr style="background:#334155; color:#fff;"><th style="padding:5px; border:1px solid #475569;">الخامة</th><th style="padding:5px; border:1px solid #475569; width:60px;">الوحدة</th><th style="padding:5px; border:1px solid #475569;">الرصيد المتاح</th>';
        
        scenarioData.forEach((s, i) => {
            // Shorten name
            let shortName = s.mixName.length > 15 ? s.mixName.substring(0,15)+'..' : s.mixName;
            thead += `<th style="padding:5px; border:1px solid #475569; font-size:10px; line-height:1.2;" title="${s.mixName}"><span style="color:#94a3b8;">#${i+1}</span><br>${shortName}</th>`;
        });
        
        thead += '<th style="padding:5px; border:1px solid #475569; font-weight:bold; width:70px;">إجمالي<br>المطلوب</th><th style="padding:5px; border:1px solid #475569;">الفرق</th><th style="padding:5px; border:1px solid #475569; text-align:center;">يكفي لـ<br>(م³)</th></tr>';
        tableHtml += thead;


        Object.values(aggregatedMats).forEach((mat, idx) => {
            // Calculate base requirement per m3 (weighted if qty>0, average if qty=0)
            let baseReqPerM3 = 0;
            if (totalTargetQty > 0) {
                baseReqPerM3 = mat.totalReq / totalTargetQty;
            } else {
                let sumBom = 0;
                scenarioData.forEach(s => {
                    const mixObj = typeof mixItems !== 'undefined' ? mixItems.find(m => String(m.id) === String(s.mixId)) : null;
                    if (mixObj && mixObj.bom) {
                        const comp = mixObj.bom.find(c => String(c.item_id) === String(mat.rawItemId));
                        if (comp) sumBom += (parseFloat(comp.qty) || 0);
                    }
                });
                baseReqPerM3 = sumBom / scenarioData.length;
            }

            let possibleM3 = baseReqPerM3 > 0 ? (mat.stockQty / baseReqPerM3) : Infinity;

            // Scale Calculation
            let possibleScale = Infinity;
            if (totalTargetQty > 0) {
                possibleScale = mat.totalReq > 0 ? (mat.stockQty / mat.totalReq) : Infinity;
            } else {
                possibleScale = possibleM3; // If 0 qty, treat 1m3 total as the scenario
            }

            if (possibleScale < minPossibleScale) {
                minPossibleScale = possibleScale;
                limitingMat = mat.matName;
            }

            let activeFactor = (mat.altUnit && mat.convFactor > 1) ? mat.convFactor : 1;
            
            let unitOptions = '';
            if (mat.altUnit && mat.convFactor > 1) {
                unitOptions += `<option value="${mat.altUnit}" data-factor="${mat.convFactor}" selected>${mat.altUnit}</option>`;
                unitOptions += `<option value="${mat.baseUnit}" data-factor="1">${mat.baseUnit}</option>`;
            } else {
                unitOptions += `<option value="${mat.baseUnit}" data-factor="1" selected>${mat.baseUnit}</option>`;
            }

            let initialStock = mat.stockQty / activeFactor;
            let initialTotalReq = mat.totalReq / activeFactor;
            let diff = initialStock - initialTotalReq;
            
            let diffHtml = '';
            if (diff >= 0) {
                diffHtml = `<span style="color:#059669; font-weight:bold;">+${diff.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2})}</span>`;
            } else {
                diffHtml = `<span style="color:#dc2626; font-weight:bold; background:#fee2e2; padding:2px 4px; border-radius:3px;">${diff.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2})}</span>`;
            }

            // Create global arrays for dynamic recalculation
            if (!window.scenarioReqData) window.scenarioReqData = {};
            window.scenarioReqData[idx] = mat; // store raw data

            let trHtml = `<tr>
                <td style="padding:5px; border:1px solid #cbd5e1; white-space:nowrap;">${mat.matName}</td>
                <td style="padding:5px; border:1px solid #cbd5e1;">
                    <select id="calc-unit-${idx}" onchange="window.calcScenarioMaterialDiff(${idx})" style="width:100%; border:1px solid #ccc; border-radius:3px; padding:2px;">
                        ${unitOptions}
                    </select>
                </td>
                <td style="padding:5px; border:1px solid #cbd5e1; direction:ltr;" id="calc-stock-${idx}">${initialStock.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2})}</td>`;
                
            scenarioData.forEach(s => {
                let reqForThisMix = (mat.reqPerMix[s.mixId] || 0) / activeFactor;
                trHtml += `<td style="padding:5px; border:1px solid #cbd5e1; direction:ltr;" id="calc-mix-req-${idx}-${s.mixId}">${reqForThisMix > 0 ? reqForThisMix.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2}) : '-'}</td>`;
            });

            trHtml += `
                <td style="padding:5px; border:1px solid #cbd5e1; direction:ltr; font-weight:bold;" id="calc-req-${idx}">${initialTotalReq.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2})}</td>
                <td style="padding:5px; border:1px solid #cbd5e1; white-space:nowrap;" id="calc-diff-${idx}">${diffHtml}</td>
                <td style="padding:5px; border:1px solid #cbd5e1; text-align:center; background:#f8fafc; font-weight:bold; color:#0f172a;">${possibleM3 !== Infinity ? possibleM3.toLocaleString(undefined, {maximumFractionDigits:1}) + ' م³' : '∞ م³'}</td>
            </tr>`;
            
            tableHtml += trHtml;
        });
        tableHtml += '</table></div>';

        let topMsg = '';
        if (totalTargetQty === 0) {
            topMsg = `<strong style="color:#059669; font-size:14px;">القدرة القصوى لإنتاج هذا السيناريو: ${Math.floor(minPossibleScale)} م³</strong><br><small style="color:#b45309;">(الخامة الحاكمة: ${limitingMat})</small>`;
        } else if (minPossibleScale < 1) {
            topMsg = `<strong style="color:#dc2626; font-size:14px;">الرصيد لا يكفي للسيناريو بالكامل (عجز في: ${limitingMat})</strong><br><small style="color:#475569;">يمكنك فقط إنتاج ${(minPossibleScale * 100).toFixed(1)}% من هذا السيناريو بالرصيد الحالي.</small>`;
        } else {
            topMsg = `<strong style="color:#059669; font-size:14px;">الرصيد يكفي لهذا السيناريو بنجاح.</strong><br><small style="color:#475569;">بإمكانك تكرار هذا السيناريو ${Math.floor(minPossibleScale)} مرة إضافية بالرصيد الحالي (المحدد: ${limitingMat}).</small>`;
        }
    
        resDiv.innerHTML = topMsg + tableHtml;
    }

    // New recalulate function for scenario table
    window.calcScenarioMaterialDiff = function(idx) {
        const mat = window.scenarioReqData[idx];
        if (!mat) return;
        
        const unitSelect = document.getElementById('calc-unit-' + idx);
        const diffSpan = document.getElementById('calc-diff-' + idx);
        const stockTd = document.getElementById('calc-stock-' + idx);
        const reqTd = document.getElementById('calc-req-' + idx);
        
        if (!diffSpan || !unitSelect || !stockTd || !reqTd) return;
        
        let factor = parseFloat(unitSelect.options[unitSelect.selectedIndex].getAttribute('data-factor')) || 1;
        
        let stockInUnit = mat.stockQty / factor;
        let totalReqInUnit = mat.totalReq / factor;
        let diff = stockInUnit - totalReqInUnit;
        
        if (diff >= 0) {
            diffSpan.innerHTML = '<span style="color:#059669; font-weight:bold;">متبقي: ' + diff.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2}) + '</span>';
        } else {
            diffSpan.innerHTML = '<span style="color:#dc2626; font-weight:bold;">عجز: ' + Math.abs(diff).toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2}) + '</span>';
        }
        
        reqTd.innerText = totalReqInUnit.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2});
        stockTd.innerText = stockInUnit.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2});
        
        // Update individual mix cells
        Object.keys(mat.reqPerMix).forEach(mixId => {
            const cell = document.getElementById('calc-mix-req-' + idx + '-' + mixId);
            if (cell) {
                let v = mat.reqPerMix[mixId] / factor;
                cell.innerText = v > 0 ? v.toLocaleString(undefined, {minimumFractionDigits: 0, maximumFractionDigits: 2}) : '-';
            }
        });
    };

    return {
        renderProductionReport,
        addScenarioRow,

        login,
        logout,
        switchTab,
        previewImage,
        showMixerModal,
        closeModal,
        saveMixer,
        shareMixerMagicLink,
        deleteMixer,
        editMixer,
        
        
        
        
        
        
        
        
        populateEmployeesDropdown,
        handleTargetChange,
        addTripRow,
        removeTripRow,
        updateTripRow,
        addExtraItemRow,
        removeExtraItemRow,
        updateExtraItemRow,
        submitBatch,
        createWarehouse,
        handlePumpChange,
        renderArchiveTable,
        viewInvoiceDetails,
        printInvoiceDetails,
        deleteInvoice,
        toggleSettlementVisibility,
        editOperators,
        saveOperators
    ,
        initProdCalculator,
        runProdCalculator,
        renderRMDashboard,
        populateClientStatementDropdown,
        refreshClientStatement,
        printClientStatement
    };

})();
