/**
 * HrPositionsSection.js — سمت‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

const LEVELS = { exec:'مدیر اجرایی', manager:'مدیر', supervisor:'سرپرست', senior:'ارشد', staff:'کارمند', intern:'کارآموز' };

export default class HrPositionsSection extends SectionBase {

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

    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() {
        try { const r = await this.api.get("/hr/departments"); this._depts = r?.data ?? []; } catch {}
        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("addBtn"),     "click", () => this._openModal());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/hr/positions");
            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></tr></thead>
            <tbody>
            ${this._rows.map(p => `<tr>
                <td><small style="font-family:monospace;">${this.escape(p.code)}</small></td>
                <td><b>${this.escape(p.title)}</b></td>
                <td>${this.escape(p.dept_name ?? '—')}</td>
                <td><span style="background:#f1f5f9;padding:2px 8px;border-radius:6px;font-size:11px;">${LEVELS[p.level] ?? p.level}</span></td>
                <td><b style="color:#3b82f6;">${p.emp_count}</b></td>
                <td style="display:flex;gap:4px;">
                    <button class="acc-btn acc-btn--xs" data-edit="${p.id}">✏️</button>
                    <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${p.id}">🗑️</button>
                </td>
            </tr>`).join("")}
            </tbody>
        </table>`;

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

    _openModal(p = null) {
        const isEdit = !!p;
        const deptOpts = `<option value="">—</option>` + this._depts.map(d =>
            `<option value="${d.id}" ${p?.department_id == d.id ? 'selected' : ''}>${this.escape(d.name)}</option>`).join("");
        const lvlOpts = Object.entries(LEVELS).map(([k,v]) =>
            `<option value="${k}" ${p?.level === k ? 'selected' : ''}>${v}</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:440px;">
            <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="code" value="${this.escape(p?.code ?? '')}"></div>
                    <div class="acc-form-group"><label>عنوان *</label><input name="title" required value="${this.escape(p?.title ?? '')}"></div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>بخش</label><select name="department_id">${deptOpts}</select></div>
                    <div class="acc-form-group"><label>سطح</label><select name="level">${lvlOpts}</select></div>
                </div>
                <div class="acc-form-group"><label>شرح وظایف</label>
                    <textarea name="description" rows="3">${this.escape(p?.description ?? '')}</textarea>
                </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(`/hr/positions/${p.id}`, body);
                else        await this.api.post("/hr/positions", body);
                close(); this._load();
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

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