/**
 * InvReportsSection.js — گزارش‌های انبار
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class InvReportsSection extends SectionBase {

    constructor(p) { super(p); this._products = []; this._warehouses = []; }

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📈 گزارش‌های انبار</h2>
            </div>

            <!-- انتخاب گزارش -->
            <div style="display:flex;gap:12px;margin-bottom:20px;flex-wrap:wrap;">
                <button class="acc-btn acc-btn--primary" data-report="card">📋 کاردکس محصول</button>
                <button class="acc-btn acc-btn--secondary" data-report="valuation">💰 ارزش‌گذاری انبار</button>
                <button class="acc-btn acc-btn--warning" data-report="low">⚠️ کم‌موجودی</button>
                <button class="acc-btn" data-report="expiring" style="background:#fef9c3;color:#854d0e;border:1px solid #fde68a;">⏰ در حال انقضا</button>
            </div>

            <!-- فیلترهای کاردکس -->
            <div data-ref="cardFilters" style="display:none;background:#f8fafc;padding:12px;border-radius:8px;margin-bottom:16px;display:none;">
                <div style="display:flex;gap:8px;align-items:end;flex-wrap:wrap;">
                    <div class="acc-form-group" style="margin:0;">
                        <label style="font-size:11px;">محصول *</label>
                        <select data-ref="cardProd" class="acc-input" style="width:200px;">
                            <option value="">انتخاب...</option>
                        </select>
                    </div>
                    <div class="acc-form-group" style="margin:0;">
                        <label style="font-size:11px;">انبار (اختیاری)</label>
                        <select data-ref="cardWh" class="acc-input">
                            <option value="">همه انبارها</option>
                        </select>
                    </div>
                    <button class="acc-btn acc-btn--primary" data-ref="cardRunBtn">📋 نمایش کاردکس</button>
                </div>
            </div>

            <div data-ref="reportWrap"></div>
        </div>`;
    }

    async afterRender() {
        await Promise.all([this._loadProducts(), this._loadWarehouses()]);

        this.container.querySelectorAll("[data-report]").forEach(btn =>
            btn.addEventListener("click", () => this._selectReport(btn.dataset.report))
        );
        this.on(this.ref("cardRunBtn"), "click", () => this._runCard());
    }

    async _loadProducts() {
        try {
            const res = await this.api.get("/inv/products");
            this._products = res?.data ?? [];
            const sel = this.ref("cardProd");
            this._products.forEach(p => {
                const o = document.createElement("option"); o.value = p.id;
                o.textContent = `${p.name} [${p.code}]`; sel.appendChild(o);
            });
        } catch {}
    }

    async _loadWarehouses() {
        try {
            const res = await this.api.get("/inv/warehouses");
            this._warehouses = res?.data ?? [];
            const sel = this.ref("cardWh");
            this._warehouses.forEach(w => {
                const o = document.createElement("option"); o.value = w.id;
                o.textContent = w.name; sel.appendChild(o);
            });
        } catch {}
    }

    _selectReport(type) {
        const filters = this.ref("cardFilters");
        filters.style.display = type === "card" ? "block" : "none";
        this.ref("reportWrap").innerHTML = "";

        if (type === "valuation") this._runValuation();
        if (type === "low")       this._runLow();
        if (type === "expiring")  this._runExpiring();
    }

    async _runCard() {
        const pid  = this.ref("cardProd")?.value;
        const whid = this.ref("cardWh")?.value;
        if (!pid) { alert("محصول را انتخاب کنید"); return; }
        this.ref("reportWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری کاردکس...</div>`;
        try {
            const params = { product_id: pid };
            if (whid) params.warehouse_id = whid;
            const res  = await this.api.get("/inv/reports/card", params);
            const rows = res?.data ?? [];
            const prod = this._products.find(p => p.id == pid);

            if (!rows.length) { this.ref("reportWrap").innerHTML = `<div class="acc-empty">تراکنشی یافت نشد</div>`; return; }

            this.ref("reportWrap").innerHTML = `
            <div style="margin-bottom:8px;font-weight:700;font-size:14px;">
                📋 کاردکس: ${this.escape(prod?.name ?? "")}
                <small style="color:#94a3b8;">موجودی نهایی: ${this._fmt(res.final_balance)} ${this.escape(prod?.unit ?? "")}</small>
            </div>
            <table class="acc-table" style="font-size:12px;">
                <thead><tr>
                    <th>شماره سند</th><th>نوع</th><th>تاریخ</th>
                    <th>از انبار</th><th>به انبار</th>
                    <th>ورودی</th><th>خروجی</th><th>مانده</th>
                    <th>قیمت واحد</th>
                </tr></thead>
                <tbody>
                ${rows.map(r => `<tr>
                    <td>${this.escape(r.voucher_no)}</td>
                    <td style="font-size:11px;">${this.escape(r.type)}</td>
                    <td>${r.date}</td>
                    <td style="font-size:11px;">${this.escape(r.from_wh ?? "—")}</td>
                    <td style="font-size:11px;">${this.escape(r.to_wh   ?? "—")}</td>
                    <td style="color:#10b981;font-weight:${r.in_qty  > 0 ? '700' : '400'};">${r.in_qty  > 0 ? this._fmt(r.in_qty)  : "—"}</td>
                    <td style="color:#ef4444;font-weight:${r.out_qty > 0 ? '700' : '400'};">${r.out_qty > 0 ? this._fmt(r.out_qty) : "—"}</td>
                    <td style="font-weight:700;color:#1d4ed8;">${this._fmt(r.balance)}</td>
                    <td>${r.unit_price > 0 ? this._fmt(r.unit_price) : "—"}</td>
                </tr>`).join("")}
                </tbody>
            </table>`;
        } catch { this.ref("reportWrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    async _runValuation() {
        this.ref("reportWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res  = await this.api.get("/inv/reports/valuation");
            const rows = res?.data ?? [];
            const total = res?.total_value ?? 0;
            if (!rows.length) { this.ref("reportWrap").innerHTML = `<div class="acc-empty">موجودی‌ای یافت نشد</div>`; return; }
            this.ref("reportWrap").innerHTML = `
            <div style="background:#f0fdf4;padding:10px 16px;border-radius:8px;margin-bottom:12px;font-size:14px;">
                💰 ارزش کل انبار: <b style="color:#166534;font-size:16px;">${this._fmt(total)} ﷼</b>
            </div>
            <table class="acc-table">
                <thead><tr><th>محصول</th><th>انبار</th><th>موجودی</th><th>بهای میانگین</th><th>ارزش</th><th>روش</th></tr></thead>
                <tbody>
                ${rows.map(r => `<tr>
                    <td>${this.escape(r.name)}</td>
                    <td>${this.escape(r.warehouse_name)}</td>
                    <td>${this._fmt(r.qty)} ${this.escape(r.unit)}</td>
                    <td>${this._fmt(r.avg_cost)}</td>
                    <td style="font-weight:700;color:#166534;">${this._fmt(r.value)} ﷼</td>
                    <td><small>${r.costing_method === "fifo" ? "FIFO" : "میانگین"}</small></td>
                </tr>`).join("")}
                </tbody>
            </table>`;
        } catch { this.ref("reportWrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    async _runLow() {
        this.ref("reportWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res  = await this.api.get("/inv/stock/low");
            const rows = res?.data ?? [];
            if (!rows.length) { this.ref("reportWrap").innerHTML = `<div class="acc-empty">✅ همه محصولات موجودی کافی دارند</div>`; return; }
            this.ref("reportWrap").innerHTML = `
            <div style="background:#fef2f2;padding:10px 16px;border-radius:8px;margin-bottom:12px;color:#991b1b;">
                ⚠️ <b>${rows.length}</b> محصول زیر حداقل موجودی
            </div>
            <table class="acc-table">
                <thead><tr><th>کد</th><th>نام</th><th>موجودی فعلی</th><th>حداقل</th><th>سفارش پیشنهادی</th></tr></thead>
                <tbody>
                ${rows.map(r => `<tr style="background:#fef2f2;">
                    <td>${this.escape(r.code)}</td>
                    <td>${this.escape(r.name)}</td>
                    <td style="color:#ef4444;font-weight:700;">${this._fmt(r.total_qty)} ${this.escape(r.unit)}</td>
                    <td>${this._fmt(r.min_stock)}</td>
                    <td style="color:#166534;font-weight:700;">${this._fmt(r.reorder_qty || (r.min_stock - r.total_qty))}</td>
                </tr>`).join("")}
                </tbody>
            </table>`;
        } catch { this.ref("reportWrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    async _runExpiring() {
        this.ref("reportWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res  = await this.api.get("/inv/reports/expiring", { days: 30 });
            const rows = res?.data ?? [];
            if (!rows.length) { this.ref("reportWrap").innerHTML = `<div class="acc-empty">✅ بچ منقضی‌شونده‌ای در ۳۰ روز آینده وجود ندارد</div>`; return; }
            this.ref("reportWrap").innerHTML = `
            <table class="acc-table">
                <thead><tr><th>بچ</th><th>محصول</th><th>تاریخ انقضا</th><th>روز باقیمانده</th><th>موجودی</th></tr></thead>
                <tbody>
                ${rows.map(r => {
                    const d = parseInt(r.days_left);
                    return `<tr style="background:${d <= 7 ? '#fef2f2' : '#fefce8'};">
                        <td>${this.escape(r.batch_no)}</td>
                        <td>${this.escape(r.product_name)}</td>
                        <td style="color:${d <= 7 ? '#ef4444' : '#ca8a04'};font-weight:700;">${r.exp_date}</td>
                        <td style="color:${d <= 7 ? '#ef4444' : '#ca8a04'};font-weight:700;">${d} روز</td>
                        <td>${this._fmt(r.total_qty)} ${this.escape(r.unit)}</td>
                    </tr>`;
                }).join("")}
                </tbody>
            </table>`;
        } catch { this.ref("reportWrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _fmt(v) { return new Intl.NumberFormat("fa-IR").format(Math.round(Number(v ?? 0))); }
    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
