/**
 * HrLeavesSection.js — مرخصی‌ها
 */
import SectionBase from "../../accounting/SectionBase.js";

const LEAVE_TYPES = { annual:'استحقاقی', sick:'استعلاجی', emergency:'فوریتی', unpaid:'بدون حقوق', maternity:'زایمان', other:'سایر' };
const STATUS = {
    pending:  { label:'در انتظار', color:'#f59e0b' },
    approved: { label:'تأیید شده', color:'#10b981' },
    rejected: { label:'رد شده',     color:'#ef4444' },
};

export default class HrLeavesSection extends SectionBase {

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

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">🌴 مرخصی‌ها</h2>
                <div style="display:flex;gap:8px;">
                    <select data-ref="statusFilter" class="acc-input">
                        <option value="">همه وضعیت‌ها</option>
                        ${Object.entries(STATUS).map(([k,v]) => `<option value="${k}">${v.label}</option>`).join("")}
                    </select>
                    <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/employees"); this._emps = r?.data ?? []; } catch {}
        await this._load();
        this.on(this.ref("refreshBtn"),   "click", () => this._load());
        this.on(this.ref("addBtn"),       "click", () => this._openModal());
        this.on(this.ref("statusFilter"), "change", () => this._load());
    }

    async _load() {
        const params = {};
        const s = this.ref("statusFilter")?.value;
        if (s) params.status = s;

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

    _render(rows) {
        if (!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><th>اقدام</th></tr></thead>
            <tbody>
            ${rows.map(r => {
                const s = STATUS[r.status] ?? { label:r.status, color:'#64748b' };
                return `<tr>
                    <td><b>${this.escape(r.employee_name)}</b></td>
                    <td>${LEAVE_TYPES[r.leave_type] ?? r.leave_type}</td>
                    <td>${r.from_date}</td>
                    <td>${r.to_date}</td>
                    <td><b>${r.days}</b></td>
                    <td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;">${this.escape(r.reason ?? '')}</td>
                    <td><span style="background:${s.color}1a;color:${s.color};padding:2px 8px;border-radius:10px;font-size:11px;font-weight:700;">${s.label}</span></td>
                    <td style="display:flex;gap:3px;">
                        ${r.status === 'pending' ? `
                        <button class="acc-btn acc-btn--xs" data-approve="${r.id}" style="background:#d1fae5;color:#065f46;">✅</button>
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-reject="${r.id}">❌</button>
                        ` : ''}
                        <button class="acc-btn acc-btn--xs gis-btn--danger" data-del="${r.id}">🗑️</button>
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>`;

        this.ref("wrap").querySelectorAll("[data-approve]").forEach(b =>
            b.addEventListener("click", () => this._setStatus(b.dataset.approve, 'approved'))
        );
        this.ref("wrap").querySelectorAll("[data-reject]").forEach(b =>
            b.addEventListener("click", () => this._setStatus(b.dataset.reject, 'rejected'))
        );
        this.ref("wrap").querySelectorAll("[data-del]").forEach(b =>
            b.addEventListener("click", async () => {
                if (!confirm("حذف این درخواست؟")) return;
                try { await this.api.delete(`/hr/leaves/${b.dataset.del}`); this._load(); }
                catch(e) { alert("خطا: " + (e?.message ?? "")); }
            })
        );
    }

    async _setStatus(id, status) {
        try { await this.api.put(`/hr/leaves/${id}`, { status }); this._load(); }
        catch(e) { alert("خطا: " + (e?.message ?? "")); }
    }

    _openModal() {
        const empOpts = this._emps.map(e =>
            `<option value="${e.id}">${this.escape(e.full_name)}</option>`).join("");
        const typeOpts = Object.entries(LEAVE_TYPES).map(([k,v]) =>
            `<option value="${k}">${v}</option>`).join("");

        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:420px;">
            <button class="acc-modal__close">✕</button>
            <div class="acc-modal__title">🌴 درخواست مرخصی</div>
            <form>
                <div class="acc-form-group"><label>کارمند *</label>
                    <select name="employee_id" required><option value="">انتخاب...</option>${empOpts}</select>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>نوع</label><select name="leave_type">${typeOpts}</select></div>
                    <div class="acc-form-group"><label></label><span></span></div>
                </div>
                <div class="doc-form-row">
                    <div class="acc-form-group"><label>از تاریخ *</label><input name="from_date" type="date" required></div>
                    <div class="acc-form-group"><label>تا تاریخ *</label><input name="to_date" type="date" required></div>
                </div>
                <div class="acc-form-group"><label>دلیل</label>
                    <textarea name="reason" rows="3"></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 { await this.api.post("/hr/leaves", body); close(); this._load(); }
            catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

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