/**
 * ServicePmSection.js — قراردادهای PM و یادآوری خودکار
 */
import SectionBase from "../../accounting/SectionBase.js";

const PLAN_LABELS = {
    monthly: "ماهانه",
    quarterly: "سه‌ماهه",
    semi_annual: "شش‌ماهه",
    annual: "سالانه",
};

const STATUS_LABELS = {
    active: "فعال",
    paused: "متوقف",
    cancelled: "لغو",
};

export default class ServicePmSection extends SectionBase {

    async template() {
        return `
        <div class="acc-section-wrap">
            <div class="acc-toolbar">
                <h2 class="acc-section-title">📅 قراردادهای PM</h2>
                <div style="display:flex;gap:8px;">
                    <button class="acc-btn acc-btn--primary" data-ref="runBtn">🔔 اجرای یادآوری</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._load();
        this.on(this.ref("refreshBtn"), "click", () => this._load());
        this.on(this.ref("runBtn"), "click", () => this._runReminders());
    }

    async _load() {
        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳</div>`;
        try {
            const res = await this.api.get("service/pm/contracts");
            this._rows = res?.data ?? [];
            this._render();
        } catch (e) {
            this.ref("wrap").innerHTML = `<div class="acc-error">❌ ${this.escape(e.message)}</div>`;
        }
    }

    _render() {
        if (!this._rows.length) {
            this.ref("wrap").innerHTML = `<div class="acc-empty">قرارداد PM فعالی ثبت نشده — هنگام نهایی‌سازی گزارش با پیشنهاد PM ایجاد می‌شود.</div>`;
            return;
        }
        const today = new Date().toISOString().slice(0, 10);
        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(c => {
                const due = c.next_visit_date && c.next_visit_date <= today && c.status === "active";
                const visit = (() => {
                    try {
                        return typeof c.visit_result === "string" ? JSON.parse(c.visit_result || "{}") : (c.visit_result || {});
                    } catch { return {}; }
                })();
                return `<tr style="${due ? "background:#fff7ed;" : ""}">
                    <td>${this.escape(c.customer_name || "—")}<br><small dir="ltr">${this.escape(c.phone || "")}</small></td>
                    <td>${this.escape(c.site_label || "—")}</td>
                    <td>${PLAN_LABELS[c.plan] || c.plan}</td>
                    <td>${this.escape(c.next_visit_date || "—")}${due ? " ⚠️" : ""}</td>
                    <td>${STATUS_LABELS[c.status] || c.status}</td>
                    <td><small>${this.escape((c.last_reminder_at || "—").slice(0, 16))}</small>
                        ${visit.notes ? `<br><small style="color:#059669;">✓ ${this.escape((visit.notes || "").slice(0, 40))}</small>` : ""}
                    </td>
                    <td style="white-space:nowrap;">
                        <button class="acc-btn acc-btn--sm" data-visit="${c.id}">📝 بازدید</button>
                        <select class="acc-input" style="width:auto;font-size:12px;" data-pm-status="${c.id}">
                            ${Object.entries(STATUS_LABELS).map(([k, v]) =>
                                `<option value="${k}" ${c.status === k ? "selected" : ""}>${v}</option>`
                            ).join("")}
                        </select>
                    </td>
                </tr>`;
            }).join("")}
            </tbody>
        </table>
        <p style="font-size:12px;color:#64748b;margin-top:12px;">یادآوری روزانه به‌صورت خودکار درخواست PM ایجاد می‌کند. cron: <code>run-svc-pm-cron.php</code></p>`;

        this.ref("wrap").querySelectorAll("[data-pm-status]").forEach(sel => {
            sel.addEventListener("change", async () => {
                const id = +sel.dataset.pmStatus;
                try {
                    await this.api.put(`service/pm/contracts/${id}`, { status: sel.value });
                    await this._load();
                } catch (e) {
                    alert(e.message);
                }
            });
        });
        this.ref("wrap").querySelectorAll("[data-visit]").forEach(btn => {
            btn.addEventListener("click", () => this._openVisitModal(+btn.dataset.visit));
        });
    }

    _openVisitModal(id) {
        const row = this._rows.find(c => c.id === id);
        if (!row) return;
        let existing = document.getElementById("svc-pm-visit-modal");
        if (existing) existing.remove();

        const modal = document.createElement("div");
        modal.id = "svc-pm-visit-modal";
        modal.className = "acc-modal";
        modal.innerHTML = `
        <div class="acc-modal__box" style="max-width:480px;">
            <div class="acc-modal__header"><h3>📝 ثبت نتیجه بازدید PM</h3>
                <button class="acc-modal__close">✕</button></div>
            <form data-ref="visitForm" style="padding:16px;">
                <div class="acc-form-group"><label>ساعت کارکرد دستگاه</label>
                    <input name="operating_hours" type="number" class="acc-input" value="${row.operating_hours || 0}"></div>
                <div class="acc-form-group"><label>وضعیت فیلتر</label>
                    <select name="filter_ok" class="acc-input"><option value="1">سالم</option><option value="0">نیاز تعویض</option></select></div>
                <div class="acc-form-group"><label>فشار مبرد</label><input name="pressure_ok" class="acc-input" placeholder="مثلاً نرمال"></div>
                <div class="acc-form-group"><label>یادداشت</label>
                    <textarea name="notes" class="acc-input" rows="3" placeholder="اقدامات انجام‌شده..."></textarea></div>
                <button type="submit" class="acc-btn acc-btn--primary" style="width:100%;">ثبت بازدید</button>
            </form>
        </div>`;
        document.body.appendChild(modal);
        const close = () => modal.remove();
        modal.querySelector(".acc-modal__close").addEventListener("click", close);
        modal.querySelector("[data-ref=visitForm]").addEventListener("submit", async (e) => {
            e.preventDefault();
            const fd = new FormData(e.target);
            try {
                await this.api.post(`service/pm/contracts/${id}/visit`, {
                    operating_hours: parseInt(fd.get("operating_hours") || "0", 10),
                    visit_result: {
                        filter_ok: fd.get("filter_ok") === "1",
                        pressure_ok: fd.get("pressure_ok") || "",
                        notes: fd.get("notes") || "",
                        visited_at: new Date().toISOString(),
                    },
                });
                close();
                await this._load();
            } catch (err) { alert(err.message); }
        });
    }

    async _runReminders() {
        const btn = this.ref("runBtn");
        btn.disabled = true;
        try {
            const res = await this.api.post("service/pm/run-reminders", {});
            const d = res?.data ?? {};
            alert(`بررسی: ${d.checked ?? 0} · درخواست جدید: ${d.created ?? 0}`);
            await this._load();
        } catch (e) {
            alert(e.message);
        } finally {
            btn.disabled = false;
        }
    }
}
