@{
    Layout = "~/Views/WebNew/Shared/_Layout.cshtml";
    ViewData["Title"] = "Detail Analisis";
}

@section Style {
    <link rel="stylesheet" href="~/webnew/css/layanan/DetailItem.css" asp-append-version="true" />
}

<div class="container mt-5">

    <h3 class="page-title mb-4">Rincian Analisis</h3>

    <div class="info-card mb-4">
        <div class="info-item">
            <span class="label">Output Hasil</span>
            <span id="output" class="value"></span>
        </div>

        <div class="info-item">
            <span class="label">Jenis Baku Mutu</span>
            <span id="jenis" class="value"></span>
        </div>
    </div>

    <div class="table-card">
        <div class="table-header">
            <button type="button" onclick="exportDetailExcel()" class="btn-export">
                Download Excel
            </button>

            <input type="text" id="search" placeholder="Cari...">
        </div>

        <div class="table-responsive">
            <table class="custom-table table">
                <thead id="thead"></thead>
                <tbody id="tbody"></tbody>
            </table>
        </div>
    </div>

    <div class="back-wrapper">
        <a onclick="history.back()" class="btn-back">
            <span class="arrow">←</span>
            Kembali
        </a>
    </div>

</div>

<script>
    function getQueryParam(name) {
        return new URLSearchParams(window.location.search).get(name);
    }

    function loadDetail() {

        const kode = getQueryParam("kode");

        let total = 0;
        let tbody = "";

        fetch(`/WebNew/DetailItem/GetDetail?kode=${kode}`)
            .then(res => {
                if (!res.ok) throw new Error("Data tidak ditemukan");
                return res.json();
            })
            .then(data => {

                document.getElementById("output").innerText = data.output || "-";
                document.getElementById("jenis").innerText = data.jenis || "-";

                let thead = "<tr>";
                (data.table.columns || []).forEach(col => {
                    thead += `<th>${col}</th>`;
                });
                thead += "</tr>";
                document.getElementById("thead").innerHTML = thead;

                (data.table.data || []).forEach(row => {

                    tbody += "<tr>";

                    (data.table.fields || []).forEach(field => {

                        let value = row[field] ?? "-";

                        if (field.toLowerCase().includes("biaya")) {
                            let num = Number(value) || 0;
                            total += num;
                            value = "Rp " + num.toLocaleString();
                        }

                        tbody += `<td>${value}</td>`;
                    });

                    tbody += "</tr>";
                });

                tbody += `
                <tr style="background:#f3f4f6; font-weight:600;">
                    <td colspan="${data.table.columns.length - 1}" class="text-end">
                        Total
                    </td>
                    <td>
                        Rp ${total.toLocaleString()}
                    </td>
                </tr>
            `;

                document.getElementById("tbody").innerHTML = tbody;
            })
            .catch(err => {
                console.error(err);
                document.getElementById("tbody").innerHTML =
                    "<tr><td colspan='7'>Data tidak ditemukan</td></tr>";
            });
    }

    document.addEventListener("DOMContentLoaded", function () {

        loadDetail();

        const search = document.getElementById("search");

        if (search) {
            search.addEventListener("keyup", function () {
                const keyword = this.value.toLowerCase();
                const rows = document.querySelectorAll("#tbody tr");

                rows.forEach(row => {
                    const text = row.innerText.toLowerCase();
                    row.style.display = text.includes(keyword) ? "" : "none";
                });
            });
        }
    });

    function exportDetailExcel() {

        const table = document.querySelector(".custom-table");

        if (!table) {
            alert("Table tidak ditemukan");
            return;
        }

        if (typeof XLSX === "undefined") {
            alert("Library XLSX belum ter-load");
            return;
        }

        const output = document.getElementById("output").innerText;
        const jenis = document.getElementById("jenis").innerText;

        const tahun = new Date().getFullYear();

        const fileName = `detail-${output}-${tahun}.xlsx`
            .replace(/\s+/g, "-");

        const wb = XLSX.utils.book_new();
        const ws = XLSX.utils.table_to_sheet(table);

        XLSX.utils.sheet_add_aoa(ws, [
            ["Rincian Analisis"],
            [`Output: ${output}`],
            [`Jenis: ${jenis}`],
            []
        ], { origin: "A1" });

        XLSX.utils.book_append_sheet(wb, ws, "Detail");

        XLSX.writeFile(wb, fileName);
    }
</script>