// pricing.js — Mobile App View Pricing Controller

const dom = {
    statusTime: document.getElementById("status-time"),
    themeToggle: document.getElementById("device-theme-toggle"),
    
    // Bottom Nav Tabs
    navItems: document.querySelectorAll(".app-nav .nav-item"),
    sheets: document.querySelectorAll(".app-sheet"),
    navPricingTab: document.getElementById("nav-pricing-tab"),
    
    // Select Form Panel
    formSearchInput: document.getElementById("form-search-input"),
    formsListContainer: document.getElementById("forms-list-container"),
    
    // Pricing Editor Workspace
    pricingCustomerName: document.getElementById("pricing-customer-name"),
    pricingFormId: document.getElementById("pricing-form-id"),
    pricingCardsContainer: document.getElementById("pricing-cards-container"),
    
    // Summaries
    summarySubtotal: document.getElementById("summary-subtotal"),
    summaryCommission: document.getElementById("summary-commission"),
    summaryWorkerShare: document.getElementById("summary-worker-share"),
    summaryGrandTotal: document.getElementById("summary-grand-total"),
    
    btnSubmitPricing: document.getElementById("btn-submit-pricing"),
    
    // Success Modal Overlay
    successOverlay: document.getElementById("success-overlay"),
    btnSuccessClose: document.getElementById("btn-success-close"),
    confirmCustomer: document.getElementById("confirm-customer"),
    confirmTotal: document.getElementById("confirm-total")
};

let state = {
    openForms: [],
    filteredForms: [],
    selectedForm: null,
    selectedFormItems: [],
    isSaving: false
};

// -------------------------------------------------------------
// 1. Application Entry & Tab Navigation
// -------------------------------------------------------------
document.addEventListener("DOMContentLoaded", () => {
    initClock();
    initTheme();
    setupEventListeners();
    
    // Pull the forms list
    loadOpenForms().then(() => {
        if (typeof PRESELECTED_FORM_ID !== 'undefined' && PRESELECTED_FORM_ID > 0) {
            const form = state.openForms.find(f => f.id == PRESELECTED_FORM_ID);
            if (form) {
                selectForm(form);
            } else {
                fetchFormDirectly(PRESELECTED_FORM_ID);
            }
        }
    });

    // Start background polling for open forms every 5 seconds
    setInterval(() => {
        const selectSheet = document.getElementById("sheet-select-form");
        if (selectSheet && selectSheet.classList.contains("active")) {
            loadOpenForms(true);
        }
    }, 5000);
});

function setupEventListeners() {
    // Tab switching
    dom.navItems.forEach(item => {
        item.addEventListener("click", () => {
            const targetId = item.getAttribute("data-target");
            switchSheet(targetId);
        });
    });

    // Live filtering of unpriced forms list
    dom.formSearchInput?.addEventListener("input", () => {
        applyFormFilters();
    });

    // Device Theme Toggle
    dom.themeToggle?.addEventListener("click", () => {
        toggleTheme();
    });

    // Submit Pricing
    dom.btnSubmitPricing?.addEventListener("click", () => {
        submitPrices();
    });

    // Close success overlay
    dom.btnSuccessClose?.addEventListener("click", () => {
        if (dom.successOverlay) dom.successOverlay.classList.remove("active");
        showSelectFormSheet();
    });
}

function switchSheet(targetSheetId) {
    dom.sheets.forEach(sheet => {
        sheet.classList.toggle("active", sheet.id === targetSheetId);
    });
    
    dom.navItems.forEach(item => {
        item.classList.toggle("active", item.getAttribute("data-target") === targetSheetId);
    });

    const contentPanel = document.querySelector(".app-content");
    if (contentPanel) {
        contentPanel.scrollTop = 0;
    }
}

function showSelectFormSheet() {
    state.selectedForm = null;
    state.selectedFormItems = [];
    if (dom.navPricingTab) dom.navPricingTab.style.display = "none";
    switchSheet("sheet-select-form");
    loadOpenForms();
}

// -------------------------------------------------------------
// 2. API Integrations (Loading forms & items)
// -------------------------------------------------------------
function loadOpenForms(isSilent = false) {
    return fetch('api/forms.php?action=list&shift_only=1')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                // Filter ONLY forms explicitly assigned/sent for pricing (is_sent_to_pricing === 1)
                state.openForms = (res.data || []).filter(f => parseInt(f.isSentToPricing) === 1);
                applyFormFilters();
            } else {
                if (!isSilent) renderEmptyFormsState();
            }
        })
        .catch(err => {
            console.error("Error loading forms:", err);
            if (!isSilent) renderEmptyFormsState();
        });
}

function fetchFormDirectly(formId) {
    fetch('api/forms.php?action=list&shift_only=1')
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                const form = (res.data || []).find(f => f.id == formId);
                if (form) {
                    selectForm(form);
                } else {
                    alert("تعذّر العثور على الاستمارة المطلوبة.");
                    showSelectFormSheet();
                }
            }
        });
}

function applyFormFilters() {
    const q = dom.formSearchInput ? dom.formSearchInput.value.trim().toLowerCase() : "";
    if (!q) {
        state.filteredForms = [...state.openForms];
    } else {
        state.filteredForms = state.openForms.filter(f => 
            (f.customerName || '').toLowerCase().includes(q) || 
            String(f.id).includes(q)
        );
    }
    renderFormsList();
}

function renderFormsList() {
    if (!dom.formsListContainer) return;
    
    if (state.filteredForms.length === 0) {
        dom.formsListContainer.innerHTML = `
            <div style="text-align:center; padding:50px 20px; color:var(--text-secondary); grid-column: 1 / -1;">
                <div style="width:60px; height:60px; border-radius:50%; background:rgba(99,102,241,0.1); color:var(--primary-color, #818cf8); display:inline-flex; align-items:center; justify-content:center; font-size:26px; margin-bottom:12px;">
                    <i class="fa-solid fa-folder-open"></i>
                </div>
                <h3 style="font-size:14px; font-weight:700; margin-bottom:4px; color:var(--text-primary);">لا توجد استمارات للتسعير حالياً</h3>
                <p style="font-size:11.5px; margin:0;">سيتم إظهار أي استمارة جديدة فور إرسالها من قسم الفواتير تلقائياً.</p>
            </div>
        `;
        return;
    }
    
    dom.formsListContainer.innerHTML = "";
    state.filteredForms.forEach(form => {
        const firstChar = form.customerName ? form.customerName.trim().charAt(0) : "ز";
        const formNum = form.id;
        const dateFormatted = formatDateString(form.createdAt);
        const materialsCount = form.materialsCount || (form.items ? form.items.length : 0) || 0;
        
        const card = document.createElement("div");
        card.className = "app-form-card";
        card.style.cssText = `
            background: var(--card-bg);
            border: 1px solid var(--card-border);
            border-radius: 16px;
            padding: 14px 16px;
            margin-bottom: 12px;
            transition: all 0.25s ease;
            box-shadow: var(--shadow-sm);
            cursor: pointer;
            position: relative;
            overflow: hidden;
            color: var(--text-primary);
        `;

        card.addEventListener("click", () => selectForm(form));
        
        // Hover effect
        card.addEventListener("mouseenter", () => {
            card.style.borderColor = "var(--primary-color)";
            card.style.transform = "translateY(-2px)";
            card.style.boxShadow = "var(--shadow-md)";
        });
        card.addEventListener("mouseleave", () => {
            card.style.borderColor = "var(--card-border)";
            card.style.transform = "none";
            card.style.boxShadow = "var(--shadow-sm)";
        });

        card.innerHTML = `
            <!-- Header Row: Serial Badge & Status -->
            <div style="display:flex; justify-space-between; align-items:center; margin-bottom:10px; border-bottom:1px dashed var(--card-border); padding-bottom:8px;">
                <div style="display:flex; align-items:center; gap:6px;">
                    <span style="background:rgba(99, 102, 241, 0.08); color:var(--primary-color); padding:3px 10px; border-radius:20px; font-size:11.5px; font-weight:800; border:1px solid rgba(99, 102, 241, 0.2); display:inline-flex; align-items:center; gap:5px;">
                        <i class="fa-solid fa-file-invoice"></i> استمارة #${escapeHTML(formNum)}
                    </span>
                </div>
                <span style="background:rgba(245, 158, 11, 0.1); color:#d97706; border:1px solid rgba(245, 158, 11, 0.25); padding:3px 10px; border-radius:20px; font-size:10.5px; font-weight:700; display:inline-flex; align-items:center; gap:4px;">
                    <i class="fa-solid fa-hourglass-half" style="font-size:9.5px;"></i> بانتظار التسعير
                </span>
            </div>

            <!-- Customer Details Row -->
            <div style="display:flex; align-items:center; gap:12px; margin-bottom:12px;">
                <div style="width:40px; height:40px; border-radius:12px; background:var(--primary-gradient); color:#fff; display:flex; align-items:center; justify-content:center; font-weight:800; font-size:16px; flex-shrink:0; box-shadow:0 3px 10px rgba(99, 102, 241, 0.25);">
                    ${escapeHTML(firstChar)}
                </div>
                <div style="flex:1; min-width:0;">
                    <h4 style="font-size:14px; font-weight:800; margin:0 0 3px 0; color:var(--text-primary); white-space:nowrap; overflow:hidden; text-overflow:ellipsis;" title="${escapeHTML(form.customerName)}">
                        ${escapeHTML(form.customerName || 'زبون عام')}
                    </h4>
                    <div style="font-size:11px; color:var(--text-secondary); display:flex; align-items:center; gap:4px;">
                        <i class="fa-regular fa-clock" style="font-size:10px;"></i>
                        <span>${dateFormatted}</span>
                    </div>
                </div>
            </div>

            <!-- Card Footer Row: Materials Badge & Price Action Button -->
            <div style="display:flex; justify-content:space-between; align-items:center; border-top:1px dashed var(--card-border); padding-top:8px;">
                <div style="display:flex; align-items:center; gap:6px;">
                    <span style="background:rgba(99, 102, 241, 0.08); color:var(--primary-color); border:1px solid rgba(99, 102, 241, 0.2); padding:3px 10px; border-radius:8px; font-size:11px; font-weight:700;">
                        <i class="fa-solid fa-boxes-stacked" style="margin-left:4px;"></i> ${materialsCount} مواد
                    </span>
                </div>
                <button type="button" class="btn-price-action" style="background:var(--primary-gradient); color:#ffffff; border:none; padding:6px 14px; border-radius:10px; font-size:11.5px; font-weight:800; display:inline-flex; align-items:center; gap:6px; cursor:pointer; box-shadow:0 3px 10px rgba(99,102,241,0.25); font-family: 'Cairo', sans-serif;">
                    <span>تسعير المواد</span>
                    <i class="fa-solid fa-arrow-left"></i>
                </button>
            </div>
        `;

        dom.formsListContainer.appendChild(card);
    });
}

function renderEmptyFormsState() {
    if (dom.formsListContainer) {
        dom.formsListContainer.innerHTML = `
            <div style="text-align:center; padding:40px 20px; color:var(--danger-color);">
                <i class="fa-solid fa-triangle-exclamation" style="font-size:24px; margin-bottom:8px;"></i>
                <p style="font-size:12px;">فشل الاتصال بالخادم</p>
            </div>
        `;
    }
}

function selectForm(form) {
    state.selectedForm = form;
    if (dom.pricingCustomerName) dom.pricingCustomerName.textContent = form.customerName;
    if (dom.pricingFormId) dom.pricingFormId.value = form.id;
    
    fetch(`api/forms.php?action=get_items&form_id=${form.id}`)
        .then(r => r.json())
        .then(res => {
            if (res.status === 'success') {
                state.selectedFormItems = res.data || [];
                renderPricingCards();
                
                if (dom.navPricingTab) dom.navPricingTab.style.display = "flex";
                switchSheet("sheet-price-items");
            } else {
                alert("فشل تحميل مواد الاستمارة.");
            }
        })
        .catch(err => {
            console.error(err);
            alert("فشل الاتصال بالخادم.");
        });
}

// -------------------------------------------------------------
// 3. Client-side dynamic pricing calculations
// -------------------------------------------------------------
function renderPricingCards() {
    if (!dom.pricingCardsContainer) return;
    
    dom.pricingCardsContainer.innerHTML = "";
    
    state.selectedFormItems.forEach((item, index) => {
        const isWeightType = item.accountingType === "وزن * سعر";
        const subtitleText = isWeightType 
            ? `الكمية: ${item.quantity} | الوزن: ${item.weight} كجم`
            : `الكمية: ${item.quantity} عدد`;
            
        const card = document.createElement("div");
        card.className = "material-item-card";
        card.innerHTML = `
            <div class="material-card-header">
                <span class="material-card-title">
                    <i class="fa-solid fa-box-open" style="margin-left:5px; color:var(--primary);"></i>
                    ${escapeHTML(item.name)}
                </span>
                <span class="material-qty-badge">
                    <i class="fa-solid fa-calculator" style="font-size:9.5px; margin-left:3px; color:var(--text-muted);"></i>
                    ${subtitleText}
                </span>
            </div>
            
            <div style="display:flex; flex-direction:column; gap:4px; margin-bottom: 8px;">
                <label style="font-size:11px; font-weight:700; color:var(--text-secondary); display:block; text-align:right;">سعر المفرد</label>
                <div class="price-input-wrapper">
                    <input type="text" class="item-price-input" data-index="${index}" data-id="${item.id}" placeholder="أدخل السعر..." value="${item.price ? formatCurrency(item.price) : ''}">
                    <span class="price-currency-label">د.ع</span>
                </div>
            </div>
            
            <div class="pricing-calc-badge-row" id="live-calc-${item.id}">
                <span title="حصص العمال" style="display:inline-flex; align-items:center; gap:3px;">
                    <i class="fa-solid fa-users" style="color: #6366f1;"></i> عمال: <strong class="worker-val">0</strong>
                </span>
                <span title="عمولة الصندوق" style="display:inline-flex; align-items:center; gap:3px; margin-right:12px;">
                    <i class="fa-solid fa-building-columns" style="color: #f59e0b;"></i> عمولة: <strong class="comm-val">0</strong>
                </span>
            </div>
        `;
        dom.pricingCardsContainer.appendChild(card);
    });

    // Attach real-time calculation hook & comma formatting to input fields
    document.querySelectorAll(".item-price-input").forEach(input => {
        input.addEventListener("input", function (e) {
            let cursorPosition = this.selectionStart;
            let originalLength = this.value.length;

            let value = this.value.replace(/,/g, '');
            let parts = value.split('.');
            parts[0] = parts[0].replace(/\D/g, '');
            parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
            
            if (parts.length > 1) {
                parts[1] = parts[1].replace(/\D/g, '').substring(0, 2);
                this.value = parts[0] + '.' + parts[1];
            } else {
                this.value = parts[0];
            }

            let newLength = this.value.length;
            cursorPosition = cursorPosition + (newLength - originalLength);
            this.setSelectionRange(cursorPosition, cursorPosition);

            recalculatePricing();
        });
    });

    recalculatePricing();
}

function recalculatePricing() {
    let grandSubtotal = 0;
    let grandCommission = 0;
    let grandWorkerShare = 0;
    let grandTotal = 0;

    const inputs = document.querySelectorAll(".item-price-input");
    inputs.forEach(input => {
        const index = parseInt(input.getAttribute("data-index"));
        const item = state.selectedFormItems[index];
        const price = parseFloat(input.value.replace(/,/g, '')) || 0;

        if (!item) return;

        const qty = item.quantity;
        const weight = item.weight || 0;
        const accType = item.accountingType || "";
        const commType = item.commissionType || "";
        const workType = item.workerShareType || "";

        const subtotal = accType === "وزن * سعر" ? (weight * price) : (qty * price);
        const commParts = calculateCommissionParts(commType, qty, weight, price, accType);
        const commission = commParts.commission + commParts.commission_10;
        const worker_share = calcFormula(workType, qty, weight, price, accType);
        const total = subtotal + commission;

        grandSubtotal += subtotal;
        grandCommission += commission;
        grandWorkerShare += worker_share;
        grandTotal += total;

        // Update live calc preview for this card
        const badge = document.getElementById(`live-calc-${item.id}`);
        if (badge) {
            badge.querySelector(".worker-val").textContent = formatCurrency(worker_share);
            badge.querySelector(".comm-val").textContent = formatCurrency(commission);
        }
    });

    // Update summaries
    dom.summarySubtotal.textContent = formatCurrency(grandSubtotal) + " د.ع";
    dom.summaryCommission.textContent = "+" + formatCurrency(grandCommission) + " د.ع";
    dom.summaryWorkerShare.textContent = "-" + formatCurrency(grandWorkerShare) + " د.ع";
    dom.summaryGrandTotal.textContent = formatCurrency(grandTotal) + " د.ع";
}

// -------------------------------------------------------------
// 4. Submit pricing details to API
// -------------------------------------------------------------
function submitPrices() {
    if (state.isSaving || !state.selectedForm) return;

    // Collect prices
    const itemsData = [];
    const inputs = document.querySelectorAll(".item-price-input");
    let missingPrice = false;

    inputs.forEach(input => {
        const itemId = input.getAttribute("data-id");
        const val = input.value.trim().replace(/,/g, '');
        if (val === "" || parseFloat(val) < 0) {
            missingPrice = true;
            input.style.borderColor = "var(--danger)";
        } else {
            input.style.borderColor = "";
            itemsData.push({
                id: parseInt(itemId),
                price: parseFloat(val)
            });
        }
    });

    if (missingPrice) {
        alert("يرجى إدخال أسعار صحيحة لجميع المواد.");
        return;
    }

    state.isSaving = true;
    const originalText = dom.btnSubmitPricing.querySelector(".btn-text").textContent;
    dom.btnSubmitPricing.disabled = true;
    dom.btnSubmitPricing.querySelector(".btn-text").textContent = "جاري الحفظ...";

    fetch('api/forms.php?action=save_prices', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            form_id: state.selectedForm.id,
            items: itemsData
        })
    })
    .then(r => r.json())
    .then(res => {
        if (res.status === 'success') {
            if (dom.confirmCustomer && state.selectedForm) dom.confirmCustomer.textContent = state.selectedForm.customerName;
            if (dom.confirmTotal && dom.summaryGrandTotal) dom.confirmTotal.textContent = dom.summaryGrandTotal.textContent;
            if (dom.successOverlay) {
                dom.successOverlay.classList.add("active");
            } else {
                showSelectFormSheet();
            }
            loadOpenForms();
        } else {
            showToast(res.message || "فشل حفظ الأسعار.", "error");
        }
    })
    .catch(err => {
        console.error(err);
        showToast("فشل الاتصال بالخادم.", "error");
    })
    .finally(() => {
        state.isSaving = false;
        dom.btnSubmitPricing.disabled = false;
        dom.btnSubmitPricing.querySelector(".btn-text").textContent = originalText;
    });
}

// -------------------------------------------------------------
// 5. Formula calculation helpers
// -------------------------------------------------------------
function calculateCommissionParts(formula, qty, weight, price, accountingType = '') {
    if (!formula || formula.trim() === '' || formula.trim() === '---') {
        return { commission: 0, commission_10: 0 };
    }
    
    let parts = formula.split('+');
    let commission = 0;
    let commission_10 = 0;
    
    parts.forEach(part => {
        const trimmed = part.trim();
        const pctMatch = trimmed.match(/(\d+(?:\.\d+)?)\s*%/);
        if (pctMatch) {
            const pct = parseFloat(pctMatch[1]);
            let base = 0;
            if (accountingType === "وزن * سعر") {
                base = weight * price;
            } else if (accountingType === "عدد * سعر") {
                base = qty * price;
            } else {
                base = (weight > 0) ? (weight * price) : (qty * price);
            }
            commission_10 += base * pct / 100;
        } else {
            commission += calcFormula(trimmed, qty, weight, price, accountingType);
        }
    });
    
    return { commission, commission_10 };
}

function calcFormula(formula, qty, weight, price, accountingType = '') {
    if (!formula || formula.trim() === '' || formula.trim() === '---') return 0;
    
    if (formula.includes('+')) {
        return formula.split('+').reduce((sum, part) => sum + calcFormula(part, qty, weight, price, accountingType), 0);
    }
    
    const f = formula.trim();

    const pctMatch = f.match(/(\d+(?:\.\d+)?)\s*%/);
    if (pctMatch) {
        const subtotal = accountingType === "وزن * سعر" ? weight * price : (accountingType === "عدد * سعر" ? qty * price : (weight > 0 ? weight * price : qty * price));
        return subtotal * parseFloat(pctMatch[1]) / 100;
    }

    const qtyMatch = f.match(/(?:عدد|العدد)\s*[*×]\s*(\d+(?:\.\d+)?)/);
    if (qtyMatch) return qty * parseFloat(qtyMatch[1]);

    const wgtMatch = f.match(/(?:وزن|الوزن)\s*[*×]\s*(\d+(?:\.\d+)?)/);
    if (wgtMatch) return (weight || qty) * parseFloat(wgtMatch[1]);

    const numMatch = f.match(/^(\d+(?:\.\d+)?)$/);
    if (numMatch) return parseFloat(numMatch[1]);

    return 0;
}

// -------------------------------------------------------------
// 6. Ambient clock & styling helpers
// -------------------------------------------------------------
function initClock() {
    const updateTime = () => {
        const now = new Date();
        let hours = now.getHours();
        let minutes = now.getMinutes();
        
        hours = hours < 10 ? '0' + hours : hours;
        minutes = minutes < 10 ? '0' + minutes : minutes;
        
        const timeStr = `${hours}:${minutes}`;
        if (dom.statusTime) dom.statusTime.textContent = timeStr;
    };
    updateTime();
    setInterval(updateTime, 60000);
}

function initTheme() {
    if (localStorage.getItem("dashboard_theme") === "dark") {
        document.body.classList.add("dark-theme");
        if (dom.themeToggle) dom.themeToggle.innerHTML = '<i class="fa-solid fa-sun"></i>';
    }
}

function toggleTheme() {
    const isDark = document.body.classList.toggle("dark-theme");
    localStorage.setItem("dashboard_theme", isDark ? "dark" : "light");
    if (dom.themeToggle) {
        dom.themeToggle.innerHTML = isDark 
            ? '<i class="fa-solid fa-sun"></i>' 
            : '<i class="fa-solid fa-moon"></i>';
    }
}

function escapeHTML(str) {
    if (!str) return '';
    return str.replace(/[&<>'"]/g, 
        tag => ({
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            "'": '&#39;',
            '"': '&quot;'
        }[tag] || tag)
    );
}

function formatCurrency(val) {
    return parseFloat(val).toLocaleString('en-US', { minimumFractionDigits: 0, maximumFractionDigits: 0 });
}

function formatDateString(dateStr) {
    if (!dateStr) return "";
    try {
        const normalized = dateStr.replace(" ", "T");
        const date = new Date(normalized);
        return date.toLocaleDateString("ar-IQ", { day: 'numeric', month: 'long', year: 'numeric' }) + " - " + 
               date.toLocaleTimeString("ar-IQ", { hour: '2-digit', minute: '2-digit', hour12: true });
    } catch (e) {
        return dateStr;
    }
}
