/**

 * ServiceEquipmentSection.js — استعلام و پیشنهاد خرید تجهیزات

 */

import SectionBase from "../../accounting/SectionBase.js";



const STATUS = {

    inquiry: "استعلام",

    quoted: "پیشنهاد داده شد",

    selected: "گزینه انتخاب شد",

    installed: "نصب/تحویل",

    cancelled: "لغو",

};



export default class ServiceEquipmentSection extends SectionBase {



    async template() {

        return `

        <div class="acc-section-wrap">

            <div class="acc-toolbar">

                <h2 class="acc-section-title">🏭 خرید تجهیزات</h2>

                <button class="acc-btn acc-btn--secondary" data-ref="refreshBtn">🔄</button>

            </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());

    }



    async _load() {

        this.ref("wrap").innerHTML = `<div class="acc-loading">⏳</div>`;

        try {

            const res = await this.api.get("service/equipment/inquiries");

            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">استعلام تجهیزاتی ثبت نشده.</div>`;

            return;

        }

        this.ref("wrap").innerHTML = this._rows.map(r => this._cardHtml(r)).join("");

        this.ref("wrap").querySelectorAll("[data-eq-save]").forEach(btn => {

            btn.addEventListener("click", () => this._save(+btn.dataset.eqSave));

        });

    }



    _cardHtml(r) {

        const opts = r.quote_options || [];

        return `

        <div class="acc-card" style="margin-bottom:12px;padding:14px;border:1px solid #e2e8f0;border-radius:10px;" data-eq="${r.id}">

            <div style="display:flex;justify-content:space-between;align-items:flex-start;">

                <div>

                    <b dir="ltr">${this.escape(r.tracking_code)}</b> — ${this.escape(r.customer_name)}

                    <div style="font-size:12px;color:#64748b;">${this.escape(r.project_city)} · ${this.escape(r.application)} · ظرفیت: ${this.escape(r.required_capacity || "—")}</div>

                </div>

                <select class="acc-input" data-eq-status style="font-size:12px;width:auto;">

                    ${Object.entries(STATUS).map(([k, v]) =>

                        `<option value="${k}" ${r.status === k ? "selected" : ""}>${v}</option>`

                    ).join("")}

                </select>

            </div>

            <div style="margin-top:10px;display:grid;gap:8px;">

                ${opts.map((o, i) => `

                <div style="display:grid;grid-template-columns:1fr 120px;gap:8px;align-items:center;">

                    <input class="acc-input" data-opt-label="${i}" value="${this.escape(o.label || "")}" placeholder="عنوان گزینه">

                    <input class="acc-input" data-opt-price="${i}" type="number" value="${o.price || 0}" placeholder="قیمت">

                </div>`).join("")}

            </div>

            <div style="margin-top:8px;display:flex;gap:8px;align-items:center;">

                <label style="font-size:12px;">گزینه انتخابی:</label>

                <select class="acc-input" data-selected style="font-size:12px;width:auto;">

                    <option value="">—</option>

                    ${opts.map(o => `<option value="${this.escape(o.key)}" ${r.selected_option === o.key ? "selected" : ""}>${this.escape(o.label)}</option>`).join("")}

                </select>

                <button class="acc-btn acc-btn--primary acc-btn--sm" data-eq-save="${r.id}">💾 ذخیره پیشنهاد</button>

            </div>

        </div>`;

    }



    async _save(id) {

        const card = this.ref("wrap").querySelector(`[data-eq="${id}"]`);

        if (!card) return;

        const opts = [];

        let i = 0;

        while (card.querySelector(`[data-opt-label="${i}"]`)) {

            opts.push({

                key: ["economy", "standard", "premium"][i] || `opt_${i}`,

                label: card.querySelector(`[data-opt-label="${i}"]`).value,

                price: parseFloat(card.querySelector(`[data-opt-price="${i}"]`).value) || 0,

            });

            i++;

        }

        const selected = card.querySelector("[data-selected]").value;

        const status = card.querySelector("[data-eq-status]").value;

        const order_value = opts.find(o => o.key === selected)?.price || opts[0]?.price || 0;

        try {

            await this.api.put(`service/equipment/inquiries/${id}`, {

                quote_options: opts, selected_option: selected, status, order_value,

            });

            await this._load();

        } catch (e) { alert(e.message); }

    }

}


