/**
 * AclMenusSection.js — مدیریت منوها و مجوز لازم
 */
import SectionBase from "../../accounting/SectionBase.js";

export default class AclMenusSection extends SectionBase {

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

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📋 منوها</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--primary" data-ref="addBtn">➕ منوی جدید</button>
                    <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>
                </div>
            </div>
            <div data-ref="wrap"><div class="acc-loading">⏳ بارگذاری...</div></div>
        </div>`;
    }

    async afterRender() {
        await this._loadPerms();
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
    }

    async _loadPerms() {
        try {
            const r = await this.api.get("/acl/permissions");
            this._perms = r?.data ?? [];
        } catch {}
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/acl/menus");
            this._rows = res?.data ?? [];
            this._render();
        } catch { this.ref("wrap").innerHTML = `<div class="acc-error">❌ خطا</div>`; }
    }

    _render() {
        if (!this._rows.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">منویی یافت نشد</div>`;
            return;
        }
        this.ref("wrap").innerHTML = `
        <table class="acc-table">
            <thead><tr>
                <th>ترتیب</th><th>منو</th><th>کلید</th><th>مسیر</th>
                <th>مجوز لازم</th><th>وضعیت</th><th>اقدام</th>
            </tr></thead>
            <tbody>
            ${this._rows.map(m => `<tr>
                <td>${m.sort_order}</td>
                <td>${m.icon} ${this.escape(m.title)}</td>
                <td><small style="font-family:monospace;">${this.escape(m.menu_key)}</small></td>
                <td><small>${this.escape(m.route)}</small></td>
                <td>
                    ${m.required_permission
                        ? `<small style="font-family:monospace;color:#1d4ed8;">${this.escape(m.required_permission)}</small>`
                        : `<span style="color:#94a3b8;font-size:11px;">بدون محدودیت</span>`}
                </td>
                <td>${m.is_active == 1 ? '✅' : '❌'}</td>
                <td style="display:flex;gap:4px;">
                    <button class="acc-btn acc-btn--xs" data-edit="${m.id}">✏️</button>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${m.id}">🗑️</button>
                </td>
            </tr>`).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-edit]").forEach(btn =>
            btn.addEventListener("click", () =>
                this._openModal(this._rows.find(r => r.id == btn.dataset.edit)))
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(btn =>
            btn.addEventListener("click", async () => {
                if (!confirm("حذف این منو؟")) return;
                try { await this.api.delete(`/acl/menus/${btn.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    _openModal(menu = null) {
        const isEdit = !!menu;
        const permOpts = `<option value="">— بدون محدودیت —</option>` +
            this._perms.map(p =>
                `<option value="${p.permission_key}" ${menu?.required_permission === p.permission_key ? 'selected' : ''}>${this.escape(p.label)} [${this.escape(p.permission_key)}]</option>`
            ).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:480px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">${isEdit ? '✏️ ویرایش منو' : '➕ منوی جدید'}</div>
            <form>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>کلید *</label>
                        <input name="menu_key" required value="${this.escape(menu?.menu_key ?? '')}" ${isEdit ? 'readonly' : ''}>
                    </div>
                    <div class="acc-form-group"><label>عنوان *</label>
                        <input name="title" required value="${this.escape(menu?.title ?? '')}">
                    </div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>آیکن</label>
                        <input name="icon" value="${this.escape(menu?.icon ?? '')}" placeholder="مثلاً 🗺️">
                    </div>
                    <div class="acc-form-group"><label>مسیر / تب</label>
                        <input name="route" value="${this.escape(menu?.route ?? '')}" placeholder="مثلاً gis">
                    </div>
                </div>
                <div class="acc-form-group"><label>مجوز لازم برای نمایش</label>
                    <select name="required_permission">${permOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>ترتیب نمایش</label>
                        <input name="sort_order" type="number" value="${menu?.sort_order ?? 0}">
                    </div>
                    <div class="acc-form-group"><label>وضعیت</label>
                        <select name="is_active">
                            <option value="1" ${menu?.is_active == 1 ? 'selected' : ''}>✅ فعال</option>
                            <option value="0" ${menu?.is_active == 0 ? 'selected' : ''}>❌ غیرفعال</option>
                        </select>
                    </div>
                </div>
                <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(); });
        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            try {
                if (isEdit) await this.api.put(`/acl/menus/${menu.id}`, body);
                else        await this.api.post("/acl/menus", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
}
