/* Utility Helper Functions */

const Utils = {
    // Pakistani/Urdu Number Formatting (1,23,456.00)
    formatNumber: function(num) {
        if (num === null || num === undefined || isNaN(num)) return "0.00";
        return new Intl.NumberFormat('en-PK', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2
        }).format(num);
    },

    // Remove commas and parse to float
    parseNumber: function(val) {
        if (typeof val === 'number') return val;
        if (!val) return 0;
        return parseFloat(val.toString().replace(/,/g, '')) || 0;
    },

    // Current Urdu Date
    getTodayUrdu: function() {
        const days = ['اتوار', 'پیر', 'منگل', 'بدھ', 'جمعرات', 'جمعہ', 'ہفتہ'];
        const months = ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'];
        const now = new Date();
        return `${days[now.getDay()]}، ${now.getDate()} ${months[now.getMonth()]} ${now.getFullYear()}`;
    },

    // Standard ISO Date (YYYY-MM-DD) in browser's local timezone
    getISODate: function() {
        const d = new Date();
        const year = d.getFullYear();
        const month = String(d.getMonth() + 1).padStart(2, '0');
        const day = String(d.getDate()).padStart(2, '0');
        return `${year}-${month}-${day}`;
    },

    // Generate Parchi/Lot Numbers
    generateVoucherId: function(prefix, count) {
        return `${prefix}-${count}`;
    },

    // Setup Enter key navigation for forms
    setupEnterNavigation: function(formId) {
        $(`${formId} input, ${formId} select, ${formId} textarea`).on('keydown', function(e) {
            if (e.key === 'Enter') {
                e.preventDefault();
                const inputs = $(this).closest('form').find(':input:visible:not([disabled]):not([readonly])');
                const index = inputs.index(this);
                if (index > -1 && index < inputs.length - 1) {
                    inputs.eq(index + 1).focus();
                } else {
                    // Final input, trigger primary button
                    $(this).closest('form').find('.btn-primary').focus();
                }
            }
        });
    },

    // Populate Select2 with dummy data
    populateSelect: function(elementId, data, placeholder, typeFilter = null) {
        const $el = $(`#${elementId}`);
        $el.empty().append('<option value=""></option>');
        
        let filteredData = data;
        if (typeFilter) {
            filteredData = data.filter(item => item.type === typeFilter);
        }

        filteredData.forEach(item => {
            $el.append(new Option(item.name, item.id));
        });

        $el.select2({
            placeholder: placeholder,
            allowClear: true,
            dir: "rtl",
            width: '100%'
        });
    },

    // Get current logged in user data
    getCurrentUser: function() {
        return MandiData.users.find(u => u.id == MandiData.currentUser.id);
    },

    // Check if user has specific permission
    hasPermission: function(module, action) {
        const user = this.getCurrentUser();
        if (!user || !user.permissions[module]) return false;
        // Admins have all permissions automatically
        if (user.role === "ایڈمن") return true; 
        return !!user.permissions[module][action];
    },

    // Global UI Permission Application
    applyPermissions: function() {
        const currentUser = API.getCurrentUser();
        if (!currentUser || !currentUser.permissions) return;

        $('[data-module][data-action]').each(function() {
            const module = $(this).data('module');
            const action = $(this).data('action');
            const perms = currentUser.permissions[module];
            const isAdmin = currentUser.role === 'admin';
            
            const hasPermission = isAdmin || (perms && perms[action]);

            if (!hasPermission) {
                if (action === 'view') {
                    $(this).hide();
                } else {
                    $(this).prop('disabled', true).addClass('disabled-permission');
                    if ($(this).is('button, a')) {
                        $(this).attr('title', 'معذرت، آپ کو اس عمل کی اجازت نہیں ہے۔');
                    }
                }
            } else {
                if (action === 'view') {
                    $(this).show();
                } else {
                    $(this).prop('disabled', false).removeClass('disabled-permission');
                }
            }
        });

        // Update user badge in header
        if (currentUser) {
            $('#userBadge').text(`${currentUser.full_name} | ${currentUser.role}`);
        }
    },

    /**
     * Extract form data as a plain object
     */
    getFormData: function($form) {
        const data = {};
        $form.serializeArray().forEach(item => {
            data[item.name] = item.value;
        });
        return data;
    },

    /**
     * Format date from ISO (2026-04-01) to Urdu-readable
     */
    /**
     * Format date from ISO (2026-04-01) to Urdu-readable
     */
    formatDate: function(dateStr) {
        if (!dateStr) return '-';
        const d = new Date(dateStr);
        if (isNaN(d.getTime())) return dateStr;
        
        const months = ['جنوری', 'فروری', 'مارچ', 'اپریل', 'مئی', 'جون', 'جولائی', 'اگست', 'ستمبر', 'اکتوبر', 'نومبر', 'دسمبر'];
        return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
    },

    /**
     * Show/Print Katchi Parchi (Purchase)
     */
    showPurchaseVoucher: async function(id) {
        try {
            const res = await API.get(`/purchases/${id}`);
            const p = res.data;
            
            const html = `
                <div class="print-paper">
                    <div class="print-header">
                        <h1>بابا نوید ٹریڈرز اینڈ کمیشن ایجنٹ</h1>
                        <p>غلہ منڈی، اوکاڑہ | موبائل: 0300-1234567</p>
                        <h2 style="margin-top:10px; border-top:1px solid #000; padding-top:5px;">کچی پرچی (خرید/آمد)</h2>
                    </div>
                    
                    <div class="print-grid">
                        <div class="print-label">تاریخ: <span class="print-value">${Utils.formatDate(p.voucher_date)}</span></div>
                        <div class="print-label">پرچی نمبر: <span class="print-value">${p.voucher_no}</span></div>
                        <div class="print-label">زمیندار: <span class="print-value">${p.zamidar_name}</span></div>
                        <div class="print-label">گاڑی # <span class="print-value">${p.vehicle_no || '---'}</span></div>
                    </div>

                    <table class="print-table">
                        <thead>
                            <tr>
                                <th>جنس (Lot)</th>
                                <th>وزن (Gross)</th>
                                <th>بوری/باردانہ</th>
                                <th>کاٹ/تارا</th>
                                <th>صافی وزن</th>
                                <th>ریٹ</th>
                                <th>رقم</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${p.lots.map(lot => `
                                <tr>
                                    <td class="fw-bold">${lot.item_name} <br><small>#${lot.lot_number}</small></td>
                                    <td>${parseFloat(lot.gross_weight).toLocaleString()} KG</td>
                                    <td>${lot.bori_qty} (${lot.packing})</td>
                                    <td>${(parseFloat(lot.kat) + parseFloat(lot.tara || 0)).toFixed(2)} KG</td>
                                    <td class="fw-bold">${parseFloat(lot.net_weight).toLocaleString()} KG</td>
                                    <td>${parseFloat(lot.rate).toLocaleString()} / ${lot.rate_basis}KG</td>
                                    <td class="fw-bold">${Utils.formatNumber(lot.gross_amount)}</td>
                                </tr>
                            `).join('')}
                        </tbody>
                    </table>

                    <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <div style="width: 320px;">
                            <div class="d-flex justify-between py-1" style="border-bottom: 2px solid #000;">
                                <span class="fw-bold">کل مال کی رقم:</span>
                                <span class="fw-bold">${Utils.formatNumber(p.total_gross_amount || p.gross_amount)}</span>
                            </div>
                            <div class="print-label" style="margin-top:10px; font-size: 0.9em; border-bottom: 1px solid #eee;">کٹوتی / خرچے:</div>
                            ${p.deductions.map(d => `
                                <div class="d-flex justify-between py-1" style="border-bottom: 1px dotted #ccc; font-size: 0.9em;">
                                    <span>${d.description}:</span>
                                    <span>${Utils.formatNumber(d.amount)}</span>
                                </div>
                            `).join('')}
                            <div class="d-flex justify-between py-2 mt-2" style="background:#f9f9f9; font-size:1.3em; border: 2px solid #000; padding: 10px;">
                                <span class="fw-bold">بقیہ صافی رقم:</span>
                                <span class="fw-bold text-accent">${Utils.formatNumber(p.net_payable)}</span>
                            </div>
                            ${parseFloat(p.amount_paid) > 0 ? `
                                <div class="d-flex justify-between py-1 mt-1" style="font-size: 1.1em;">
                                    <span class="text-success fw-bold">ادائیگی (ذریعہ: ${p.payment_method_name || 'کیش'}):</span>
                                    <span class="text-success fw-bold">${Utils.formatNumber(p.amount_paid)}</span>
                                </div>
                                <div class="d-flex justify-between py-1" style="border-top: 1px solid #000; font-size: 1.1em;">
                                    <span class="text-danger fw-bold">باقی کھاتہ:</span>
                                    <span class="text-danger fw-bold">${Utils.formatNumber(p.remaining_balance)}</span>
                                </div>
                            ` : ''}
                        </div>
                    </div>


                    <div class="print-footer">
                        <div class="sig-box">زمیندار کے دستخط</div>
                        <div class="sig-box">منشی / کیشیئر</div>
                    </div>
                </div>
            `;
            
            $('#printArea').html(html);
            $('#printModal').fadeIn(200);
            $('body').addClass('modal-open').css('overflow', 'hidden');
        } catch (err) {
            console.error("Purchase view error:", err);
            Toast.danger("پرچی حاصل کرنے میں غلطی آئی۔");
        }
    },

    /**
     * Show/Print Pakki Parchi (Sale)
     */
    showSaleVoucher: async function(id) {
        try {
            const res = await API.get(`/sales/${id}`);
            const s = res.data;
            
            const html = `
                <div class="print-paper">
                    <div class="print-header">
                        <h1>بابا نوید ٹریڈرز اینڈ کمیشن ایجنٹ</h1>
                        <p>غلہ منڈی، اوکاڑہ | موبائل: 0300-1234567</p>
                        <h2 style="margin-top:10px; border-top:1px solid #000; padding-top:5px;">پکی پرچی (سیل/بکری)</h2>
                    </div>
                    
                    <div class="print-grid">
                        <div class="print-label">تاریخ: <span class="print-value">${Utils.formatDate(s.voucher_date)}</span></div>
                        <div class="print-label">پرچی نمبر: <span class="print-value">${s.voucher_no}</span></div>
                        <div class="print-label">خریدار: <span class="print-value">${s.khareedar_name}</span></div>
                        ${s.havala_name ? `<div class="print-label">حوالہ: <span class="print-value">${s.havala_name}</span></div>` : ''}
                    </div>

                    <table class="print-table">
                        <thead>
                            <tr>
                                <th>جنس (Lot)</th>
                                <th>کل وزن</th>
                                <th>کٹوتی</th>
                                <th>صافی وزن</th>
                                <th>ریٹ (Rate)</th>
                                <th>فی (Basis)</th>
                                <th>کل رقم (Gross)</th>
                            </tr>
                        </thead>
                        <tbody>
                            ${(s.items || [{
                                item_name: s.item_name, lot_number: s.lot_number,
                                weight: s.sale_weight, deduction: 0, rate: s.rate, rate_basis: s.rate_basis, gross_amount: s.gross_amount
                            }]).map(item => `
                            <tr>
                                <td class="fw-bold">${item.item_name} <br><small>#${item.lot_number}</small></td>
                                <td>${parseFloat(item.weight).toLocaleString()} KG</td>
                                <td>${parseFloat(item.deduction || 0).toLocaleString()} KG</td>
                                <td class="fw-bold">${(parseFloat(item.weight) - parseFloat(item.deduction || 0)).toLocaleString()} KG</td>
                                <td>${parseFloat(item.rate).toLocaleString()}</td>
                                <td>${item.rate_basis} KG</td>
                                <td class="fw-bold">${Utils.formatNumber(item.gross_amount)}</td>
                            </tr>
                            `).join('')}
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="6" class="text-right fw-bold">مجموعی رقم:</td>
                                <td class="fw-bold text-accent">${Utils.formatNumber(s.gross_amount)}</td>
                            </tr>
                        </tfoot>
                    </table>

                    <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <div style="width: 320px;">
                            ${s.additions.map(a => `
                                <div class="d-flex justify-between py-1" style="border-bottom: 1px dotted #ccc;">
                                    <span>${a.description}:</span>
                                    <span>${Utils.formatNumber(a.amount)}</span>
                                </div>
                            `).join('')}
                            <div class="d-flex justify-between py-2 mt-2" style="background:#f9f9f9; font-size:1.3em; border: 2px solid #000; padding: 10px;">
                                <span class="fw-bold">بقیہ رقم (Payable):</span>
                                <span class="fw-bold text-primary">${Utils.formatNumber(s.net_receivable)}</span>
                            </div>
                            ${parseFloat(s.amount_received) > 0 ? `
                                <div class="d-flex justify-between py-1 mt-1" style="font-size: 1.1em;">
                                    <span class="text-success fw-bold">وصولی (ذریعہ: ${s.payment_method_name || 'کیش'}):</span>
                                    <span class="text-success fw-bold">${Utils.formatNumber(s.amount_received)}</span>
                                </div>
                                <div class="d-flex justify-between py-1" style="border-top: 1px solid #000; font-size: 1.1em;">
                                    <span class="text-danger fw-bold">باقی کھاتہ:</span>
                                    <span class="text-danger fw-bold">${Utils.formatNumber(s.remaining_balance)}</span>
                                </div>
                            ` : ''}
                        </div>
                    </div>

                    <div class="print-footer">
                        <div class="sig-box">خریدار کے دستخط</div>
                        <div class="sig-box">منشی / کیشیئر</div>
                    </div>
                </div>
            `;
            
            $('#printArea').html(html);
            $('#printModal').fadeIn(200);
            $('body').addClass('modal-open').css('overflow', 'hidden');
        } catch (err) {
            console.error("Sale view error:", err);
            Toast.danger("پرچی حاصل کرنے میں غلطی آئی۔");
        }
    }
};

/**
 * Global Modal Controls
 */
window.closePrintModal = function() {
    $('#printModal').fadeOut(200);
    $('body').removeClass('modal-open').css('overflow', '');
};

// Keyboard listener for Escape key
$(document).on('keydown', function(e) {
    if (e.key === 'Escape') {
        window.closePrintModal();
    }
});

// Auto-update header date
$(function() {
    $('#currentDate').text(Utils.getTodayUrdu());
});
