/**
 * HrAttendanceSection.js — حضور غیاب با GPS
 */
import SectionBase from "../../accounting/SectionBase.js";

const STATUS = { present:'حاضر', absent:'غایب', leave:'مرخصی', late:'تأخیر' };

export default class HrAttendanceSection 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="empFilter" class="acc-input" style="width:200px;"><option value="">همه کارمندان</option></select>
                    <input type="date" data-ref="fromDate" class="acc-input">
                    <input type="date" data-ref="toDate" class="acc-input">
                    <button class="acc-btn acc-btn--primary" data-ref="checkBtn">⏱️ ثبت ورود/خروج</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 ?? [];
            const sel = this.ref("empFilter");
            this._emps.forEach(e => { const o = document.createElement("option"); o.value = e.id; o.textContent = e.full_name; sel.appendChild(o); });
        } catch {}

        const today = new Date().toISOString().split("T")[0];
        const monthAgo = new Date(Date.now() - 30*86400e3).toISOString().split("T")[0];
        this.ref("fromDate").value = monthAgo;
        this.ref("toDate").value   = today;

        await this._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("checkBtn"),   "click", () => this._openCheckModal());
        this.on(this.ref("empFilter"),  "change",() => this._load());
        this.on(this.ref("fromDate"),   "change",() => this._load());
        this.on(this.ref("toDate"),     "change",() => this._load());
    }

    async _load() {
        const params = {
            from: this.ref("fromDate")?.value,
            to:   this.ref("toDate")?.value,
        };
        const emp = this.ref("empFilter")?.value;
        if (emp) params.employee_id = emp;

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳ بارگذاری...</div>`;
        try {
            const res = await this.api.get("/hr/attendance", 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>GPS</th></tr></thead>
            <tbody>
            ${rows.map(r => `<tr>
                <td><b>${this.escape(r.employee_name)}</b></td>
                <td>${r.date}</td>
                <td style="font-family:monospace;">${r.check_in  ? r.check_in.substring(11,16) : '—'}</td>
                <td style="font-family:monospace;">${r.check_out ? r.check_out.substring(11,16) : '—'}</td>
                <td><b>${r.hours ? r.hours + ' ساعت' : '—'}</b></td>
                <td>${STATUS[r.status] ?? r.status}</td>
                <td>${r.check_in_lat ? '<span title="ورود ثبت GPS شده">📍</span>' : ''}</td>
            </tr>`).join("")}
            </tbody>
        </table>`;
    }

    _openCheckModal() {
        const empOpts = this._emps.map(e =>
            `<option value="${e.id}">${this.escape(e.full_name)}</option>`).join("");
        const ov = document.createElement("div"); ov.className = "acc-modal-overlay";
        ov.innerHTML = `
        <div class="acc-modal" style="max-width:380px;">
            <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="acc-form-group"><label>عملیات</label>
                    <select name="action">
                        <option value="check_in">ورود</option>
                        <option value="check_out">خروج</option>
                    </select>
                </div>
                <div data-ref-gps style="background:#f0fdf4;padding:8px;border-radius:6px;font-size:12px;color:#166534;">
                    📍 در حال دریافت GPS...
                </div>
                <input type="hidden" name="lat"><input type="hidden" name="lng">
                <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(); });

        // دریافت GPS
        const gpsEl = ov.querySelector("[data-ref-gps]");
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(pos => {
                ov.querySelector("[name=lat]").value = pos.coords.latitude;
                ov.querySelector("[name=lng]").value = pos.coords.longitude;
                gpsEl.innerHTML = `📍 ثبت شد: ${pos.coords.latitude.toFixed(5)}, ${pos.coords.longitude.toFixed(5)}`;
            }, err => {
                gpsEl.innerHTML = `⚠️ GPS در دسترس نیست — ثبت بدون موقعیت`;
                gpsEl.style.background = '#fef9c3'; gpsEl.style.color = '#854d0e';
            });
        } else {
            gpsEl.innerHTML = `⚠️ مرورگر از GPS پشتیبانی نمی‌کند`;
        }

        ov.querySelector("form").addEventListener("submit", async ev => {
            ev.preventDefault();
            const body = Object.fromEntries(new FormData(ev.target).entries());
            try {
                await this.api.post("/hr/attendance", body);
                close(); this._load();
                this._toast("✅ ثبت شد", "#10b981");
            } catch(e) { alert("خطا: " + (e?.message ?? "")); }
        });
    }

    escape(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); }
    _toast(m, b = "#10b981") {
        const t = document.createElement("div");
        t.style.cssText = `position:fixed;bottom:24px;left:24px;background:${b};color:#fff;padding:12px 20px;border-radius:10px;font-size:13px;z-index:9999;`;
        t.textContent = m; document.body.appendChild(t); setTimeout(() => t.remove(), 3000);
    }
}
