/**
 * VouchersSection.js — اسناد حرکت انبار
 */
import SectionBase from "../../accounting/SectionBase.js";

const VOUCHER_TYPES = {
    purchase_receipt:   { label: "ورود از خرید",      icon: "📥", color: "#10b981" },
    sale_issue:         { label: "خروج برای فروش",     icon: "📤", color: "#3b82f6" },
    return_in:          { label: "مرجوعی ورودی",       icon: "↩️",  color: "#8b5cf6" },
    return_out:         { label: "مرجوعی خروجی",       icon: "↪️",  color: "#f97316" },
    waste:              { label: "ضایعات",              icon: "🗑️",  color: "#ef4444" },
    consignment_out:    { label: "صدور امانی",          icon: "📦", color: "#f59e0b" },
    consignment_return: { label: "برگشت امانت",         icon: "🔄", color: "#06b6d4" },
    transfer:           { label: "انتقال بین انبار",    icon: "🔃", color: "#6366f1" },
    adjustment:         { label: "تعدیل موجودی",        icon: "⚖️",  color: "#64748b" },
    project_issue:      { label: "خروج پروژه",          icon: "🏗️",  color: "#84cc16" },
};

const STATUS = {
    draft:     { label: "پیش‌نویس",  color: "#94a3b8" },
    confirmed: { label: "تأیید شده", color: "#10b981" },
    cancelled: { label: "لغو شده",   color: "#ef4444" },
};

export default class VouchersSection extends SectionBase {

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

    async template() {
        const typeOpts = Object.entries(VOUCHER_TYPES)
            .map(([k,v]) => `<option value="${k}">${v.icon} ${v.label}</option>`).join("");

        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📄 اسناد حرکت انبار</h2>
                <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;">
                    <select data-ref="typeFilter" class="acc-input">
                        <option value="">همه انواع</option>${typeOpts}
                    </select>
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        <option value="draft">پیش‌نویس</option>
                        <option value="confirmed">تأیید شده</option>
                        <option value="cancelled">لغو شده</option>
                    </select>
                    <input type="date" data-ref="fromDate" class="acc-input" title="از تاریخ">
                    <input type="date" data-ref="toDate"   class="acc-input" title="تا تاریخ">
                    <button class="acc-btn acc-btn--primary" data-ref="newBtn" data-perm="inv.vouchers.create">➕ سند جدید</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="tableWrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await Promise.all([this._loadWarehouses(), this._loadProducts()]);
        await this._load();
        this.on(this.ref("refreshBtn"),    "click",  () => this._load());
        this.on(this.ref("newBtn"),        "click",  () => this._openModal());
        this.on(this.ref("typeFilter"),    "change", () => this._load());
        this.on(this.ref("statusFilter"),  "change", () => this._load());
        this.on(this.ref("fromDate"),      "change", () => this._load());
        this.on(this.ref("toDate"),        "change", () => this._load());
    }

    async _loadWarehouses() {
        try { const r = await this.api.get("/inv/warehouses"); this._warehouses = r?.data ?? []; } catch {}
    }
    async _loadProducts() {
        try { const r = await this.api.get("/inv/products");   this._products   = r?.data ?? []; } catch {}
    }

    async _load() {
        const params = {};
        const type   = this.ref("typeFilter")?.value;
        const status = this.ref("statusFilter")?.value;
        const from   = this.ref("fromDate")?.value;
        const to     = this.ref("toDate")?.value;
        if (type)   params.type   = type;
        if (status) params.status = status;
        if (from)   params.from   = from;
        if (to)     params.to     = to;

        this.ref("tableWrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/inv/vouchers", params);
            this._renderTable(res?.data ?? []);
        } catch {
            this.ref("tableWrap").innerHTML = `<div class="acc-error">❌ خطا در بارگذاری</div>`;
        }
    }

    _renderTable(rows) {
        if (!rows.length) {
            this.ref("tableWrap").innerHTML = `<div class="acc-empty">سندی یافت نشد</div>`;
            return;
        }
        this.ref("tableWrap").innerHTML = `
        <table class="acc-table">
            <thead><tr>
                <th>شماره سند</th><th>نوع</th><th>تاریخ</th><th>وضعیت</th>
                <th>ردیف</th><th>توضیح</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${rows.map(r => {
                const t = VOUCHER_TYPES[r.type] ?? { label: r.type, icon: "📄", color: "#64748b" };
                const s = STATUS[r.status]      ?? { label: r.status, color: "#64748b" };
                return `<tr>
                    <td style="font-weight:700;">${this.escape(r.voucher_no)}</td>
                    <td><span style="color:${t.color};font-weight:600;">${t.icon} ${t.label}</span></td>
                    <td>${r.date ?? ''}</td>
                    <td><span style="color:${s.color};font-weight:600;">${s.label}</span></td>
                    <td>${r.item_count ?? 0} ردیف</td>
                    <td style="max-width:180px;overflow:hidden;text-overflow:ellipsis;">${this.escape(r.description ?? '')}</td>
                    <td style="display:flex;gap:4px;">
                        <button class="acc-btn acc-btn--xs" data-action="view" data-id="${r.id}">👁️</button>
                        ${r.status === 'draft' ? `
                        <button class="acc-btn acc-btn--xs" data-action="confirm" data-id="${r.id}" data-perm="inv.vouchers.confirm" style="background:#d1fae5;color:#065f46;">✅ تأیید</button>
                        <button class="acc-btn acc-btn--xs" data-action="edit"    data-id="${r.id}" data-perm="inv.vouchers.create">✏️</button>
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-action="cancel" data-id="${r.id}" data-perm="inv.vouchers.cancel">🗑️</button>
                        ` : ''}
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("tableWrap").querySelectorAll("[data-action]").forEach(btn => {
            btn.addEventListener("click", () => {
                const id = parseInt(btn.dataset.id);
                if (btn.dataset.action === "view")    this._viewVoucher(id);
                if (btn.dataset.action === "edit")    this._openModal(id);
                if (btn.dataset.action === "confirm") this._confirm(id);
                if (btn.dataset.action === "cancel")  this._cancel(id);
            });
        });

        // اعمال ACL روی دکمه‌های داینامیک
        this.applyAclToDom(this.ref("tableWrap"));
    }

    async _viewVoucher(id) {
        try {
            const res = await this.api.get(`/inv/vouchers/${id}`);
            const v   = res?.data;
            if (!v) return;
            const t = VOUCHER_TYPES[v.type] ?? { label: v.type, icon: "📄" };
            const s = STATUS[v.status]      ?? { label: v.status };
            const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
            ov.innerHTML = `
            <div class="acc-modal" style="max-width:700px;max-height:90vh;overflow-y:auto;">
                <button class="acc-modal__close">✕</button>
                <div class="acc-modal__title">${t.icon} سند ${this.escape(v.voucher_no)}</div>
                <div style="display:flex;gap:12px;margin-bottom:12px;font-size:13px;flex-wrap:wrap;">
                    <span>📅 ${v.date}</span>
                    <span>وضعیت: <b>${s.label}</b></span>
                    ${v.ref_no ? `<span>مرجع: ${this.escape(v.ref_no)}</span>` : ""}
                    ${v.created_by ? `<span>ثبت‌کننده: ${this.escape(v.created_by)}</span>` : ""}
                </div>
                ${v.description ? `<div style="background:#f8fafc;padding:8px;border-radius:6px;margin-bottom:12px;font-size:12px;">${this.escape(v.description)}</div>` : ""}
                <table class="acc-table">
                    <thead><tr><th>محصول</th><th>از انبار</th><th>به انبار</th><th>تعداد</th><th>قیمت واحد</th><th>مبلغ کل</th></tr></thead>
                    <tbody>
                    ${(v.items ?? []).map(i => `<tr>
                        <td>${this.escape(i.product_name ?? "")} <small style="color:#94a3b8;">${this.escape(i.product_code ?? "")}</small></td>
                        <td>${this.escape(i.from_warehouse_name ?? "—")}</td>
                        <td>${this.escape(i.to_warehouse_name   ?? "—")}</td>
                        <td>${this._fmt(i.qty)} ${this.escape(i.unit ?? "")}</td>
                        <td>${i.unit_price  > 0 ? this._fmt(i.unit_price)  : "—"}</td>
                        <td>${i.total_price > 0 ? this._fmt(i.total_price) : "—"}</td>
                    </tr>`).join("")}
                    </tbody>
                </table>
                <div style="margin-top:12px;text-align:left;">
                    <b>جمع کل: ${this._fmt((v.items ?? []).reduce((s,i) => s + parseFloat(i.total_price ?? 0), 0))} ﷼</b>
                </div>
            </div>`;
            document.body.appendChild(ov);
            ov.querySelector(".acc-modal__close").addEventListener("click", () => ov.remove());
            ov.addEventListener("click", e => { if (e.target === ov) ov.remove(); });
        } catch(e) { alert("خطا در بارگذاری سند"); }
    }

    async _confirm(id) {
        if (!confirm("آیا از تأیید این سند مطمئن هستید؟")) return;
        try {
            await this.api.post(`/inv/vouchers/${id}/confirm`, {});
            this._toast("✅ سند تأیید شد", "#10b981");
            this._load();
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    async _cancel(id) {
        if (!confirm("آیا از لغو این سند مطمئن هستید؟")) return;
        try {
            await this.api.delete(`/inv/vouchers/${id}`);
            this._toast("🗑️ سند لغو شد");
            this._load();
        } catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    _openModal(id = null) {
        const typeOpts = Object.entries(VOUCHER_TYPES)
            .map(([k,v]) => `<option value="${k}">${v.icon} ${v.label}</option>`).join("");
        const whOpts = this._warehouses.map(w => `<option value="${w.id}">${w.name} (${w.type})</option>`).join("");
        const prodOpts = this._products.map(p => `<option value="${p.id}" data-unit="${p.unit}">${p.name} [${p.code}]</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:700px;max-height:90vh;overflow-y:auto;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">📄 سند جدید حرکت انبار</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group">
                        <label>نوع سند *</label>
                        <select name="type" required>${typeOpts}</select>
                    </div>
                    <div class="acc-form-group">
                        <label>تاریخ *</label>
                        <input name="date" type="date" value="${new Date().toISOString().split("T")[0]}" required>
                    </div>
                </div>
                <div class="acc-form-group">
                    <label>توضیح</label>
                    <input name="description" type="text" placeholder="اختیاری">
                </div>
                <div class="acc-form-group">
                    <label>ثبت‌کننده</label>
                    <input name="created_by" type="text" placeholder="نام">
                </div>

                <div class="gis-info-divider">ردیف‌های سند</div>
                <div data-ref-inner="items" id="inv-items-container"></div>
                <button type="button" id="inv-add-row" class="acc-btn acc-btn--secondary acc-btn--sm" style="margin-bottom:12px;">
                    ➕ افزودن ردیف
                </button>

                <div class="acc-modal__actions">
                    <button type="button" class="acc-btn acc-btn--secondary" data-action="cancel">انصراف</button>
                    <button type="submit" class="acc-btn acc-btn--primary">💾 ذخیره پیش‌نویس</button>
                </div>
            </form>
        </div>`;

        document.body.appendChild(ov);
        const close = () => ov.remove();
        ov.querySelector(".acc-modal__close").addEventListener("click", close);
        ov.querySelector("[data-action=cancel]").addEventListener("click", close);
        ov.addEventListener("click", e => { if (e.target === ov) close(); });

        const container = ov.querySelector("#inv-items-container");
        let rowIdx = 0;

        const addRow = () => {
            const i = rowIdx++;
            const div = document.createElement("div");
            div.className = "inv-item-row";
            div.style.cssText = "display:grid;grid-template-columns:2fr 1fr 1fr 1fr 1fr auto;gap:6px;margin-bottom:6px;align-items:end;";
            div.innerHTML = `
                <div><label style="font-size:11px;">محصول</label>
                    <select name="items[${i}][product_id]" class="acc-input" required><option value="">انتخاب...</option>${prodOpts}</select>
                </div>
                <div><label style="font-size:11px;">از انبار</label>
                    <select name="items[${i}][from_warehouse_id]" class="acc-input"><option value="">—</option>${whOpts}</select>
                </div>
                <div><label style="font-size:11px;">به انبار</label>
                    <select name="items[${i}][to_warehouse_id]" class="acc-input"><option value="">—</option>${whOpts}</select>
                </div>
                <div><label style="font-size:11px;">تعداد</label>
                    <input name="items[${i}][qty]" type="number" min="0.001" step="any" class="acc-input" required>
                </div>
                <div><label style="font-size:11px;">قیمت واحد</label>
                    <input name="items[${i}][unit_price]" type="number" min="0" step="any" class="acc-input" placeholder="0">
                </div>
                <button type="button" class="acc-btn acc-btn--xs gis-btn--danger" style="margin-top:18px;" onclick="this.closest('.inv-item-row').remove()">✕</button>
            `;
            container.appendChild(div);
        };

        addRow(); // یک ردیف پیش‌فرض
        ov.querySelector("#inv-add-row").addEventListener("click", addRow);

        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const fd   = new FormData(ev.target);
            const body = { type: fd.get("type"), date: fd.get("date"), description: fd.get("description") ?? "", created_by: fd.get("created_by") ?? "", items: [] };

            // جمع‌آوری ردیف‌ها
            const rows = container.querySelectorAll(".inv-item-row");
            rows.forEach(row => {
                const pid  = row.querySelector("[name$='[product_id]']")?.value;
                const qty  = parseFloat(row.querySelector("[name$='[qty]']")?.value ?? 0);
                if (!pid || qty <= 0) return;
                body.items.push({
                    product_id:        parseInt(pid),
                    from_warehouse_id: row.querySelector("[name$='[from_warehouse_id]']")?.value || null,
                    to_warehouse_id:   row.querySelector("[name$='[to_warehouse_id]']")?.value   || null,
                    qty,
                    unit_price: parseFloat(row.querySelector("[name$='[unit_price]']")?.value ?? 0),
                });
            });

            if (!body.items.length) { alert("حداقل یک ردیف وارد کنید"); return; }
            const btn = ev.target.querySelector("[type=submit]");
            btn.disabled = true; btn.textContent = "در حال ذخیره...";
            try {
                await this.api.post("/inv/vouchers", body);
                close();
                this._toast("✅ سند ذخیره شد");
                this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); btn.disabled = false; btn.textContent = "💾 ذخیره پیش‌نویس"; }
        });
    }

    _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;"); }
    _toast(msg, bg = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${bg};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;font-weight:600;z-index:9999;`;
        t.textContent = msg; document.body.appendChild(t);
        setTimeout(() => t.remove(), 3000);
    }
}
