{% extends "index.html" %}
{% block content %}
{% load static %}
{% load i18n %}
{% load widget_tweaks %}
{% load assets_custom_filter %}


<div class="oh-wrapper mt-3">

    <div class="d-flex mt-3 mb-3" style='justify-content: space-between;
        align-items: center;'>
        <h1 class="oh-main__titlebar-title fw-bold">
          {% trans "Asset Reports" %}
        </h1>


        <div style="display:inline-flex;">
            <!-- Filter section -->
            <form id="filterForm" onsubmit="event.preventDefault(); loadFilteredPivotData();" class="me-3" style="margin-top: 10px;">

                <div class="oh-main__titlebar oh-main__titlebar--right">

                    <div class="oh-main__titlebar-button-container">
                        <div class="oh-dropdown" x-data="{open: false}">
                            <button
                                class="oh-btn ml-2"
                                @click="open = !open"
                                onclick="event.preventDefault()"
                            >
                                <ion-icon name="filter" class="mr-1"></ion-icon>{% trans "Filter" %}
                                <div id="filterCount"></div>
                            </button>
                            <div
                                class="oh-dropdown__menu oh-dropdown__menu--right oh-dropdown__filter p-4"
                                x-show="open"
                                @click.outside="open = false"
                                style="display: none"
                            >
                                <div class="oh-dropdown__filter-body">
                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Asset" %}</div>
                                        <div class="oh-accordion-body">
                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_name.id_for_label}}">{% trans "Asset Name" %}</label>
                                                        {{asset_filter_form.asset_name}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_tracking_id.id_for_label}}">{% trans "Tracking Id" %}</label>
                                                        {{asset_filter_form.asset_tracking_id}}
                                                    </div>

                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_purchase_date.id_for_label}}">{% trans "Purchase Date" %}</label>
                                                        {{asset_filter_form.asset_purchase_date |attr:"type:date"}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_purchase_cost.id_for_label}}">{% trans "Purchase Cost" %}</label>
                                                        {{asset_filter_form.asset_purchase_cost}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_lot_number_id.id_for_label}}">{% trans "Asset Batch Number" %}</label>
                                                        {{asset_filter_form.asset_lot_number_id}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_category_id.id_for_label}}">{% trans "Category" %}</label>
                                                        {{asset_filter_form.asset_category_id}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-12">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="{{asset_filter_form.asset_status.id_for_label}}">{% trans "Status" %}</label>
                                                        {{asset_filter_form.asset_status}}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="oh-dropdown__filter-footer">
                                        <button
                                            type="button"
                                            class="oh-btn oh-btn--secondary oh-btn--small w-100 filterButton"
                                            id="objective-filter-form-submit"
                                            onclick="loadFilteredPivotData();"
                                        >
                                            {% trans "Filter" %}
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>


            <!-- Export Button -->
            <button id="export-btn" class="oh-btn oh-btn--secondary" style="margin-top: 10px;">
                <ion-icon name="download-outline" class="mr-1 md hydrated" role="img" aria-label="download"></ion-icon>
                {% trans "Export Table" %}
            </button>
        </div>
    </div>


    <!-- Pivot Container -->
    <div id="pivot-container" class="mb-5" style="width: 100%; overflow-x: auto;"></div>
</div>


<script>
    // Function to load filtered pivot data
    function loadFilteredPivotData() {
        // Get filter form data
        var formData = $("#filterForm").serialize(); // Serializing the form

        $.ajax({
            url: "asset-pivot", // Replace with your URL to fetch filtered data
            method: "GET",
            data: formData,
            success: function (data) {
                // Render the pivot table with the filtered data
                $("#pivot-container").pivotUI(data, {
                    rows: ["Asset Name","Category","Tracking ID","Batch Number","Status","Asset Cost","Asset User","Phone"],
                    cols: [],
                    aggregatorName: "Count",
                    rendererName: "Table", // Default view as Table
                    onRefresh: function (config) {
                        let currentRenderer = config.rendererName;
                        if (currentRenderer === "Table" || currentRenderer === "Table Barchart" ||
                            currentRenderer === "Heatmap" || currentRenderer === "Row Heatmap" || currentRenderer === "Col Heatmap" ) {
                            $("#export-btn").show(); // Show button for tables
                        } else {
                            $("#export-btn").hide(); // Hide button for charts
                        }
                    },
                    renderers: $.extend(
                        $.pivotUtilities.renderers,
                        $.pivotUtilities.plotly_renderers // Adding Plotly renderers
                    )
                });
            },
            error: function (error) {
                console.log("Error fetching filtered data: ", error);
            }
        });
    }

    $(document).ready(function () {
        // Initialize the pivot table on page load
        $.getJSON("asset-pivot", function (data) {
            $("#pivot-container").pivotUI(data, {
                rows: ["Asset Name","Category","Tracking ID","Batch Number","Status","Asset Cost","Asset User","Phone"],
                cols: [],
                aggregatorName: "Count",
                rendererName: "Table", // Default view as Table
                onRefresh: function (config) {
                    let currentRenderer = config.rendererName;
                    if (currentRenderer === "Table" || currentRenderer === "Table Barchart" ||
                        currentRenderer === "Heatmap" || currentRenderer === "Row Heatmap" || currentRenderer === "Col Heatmap" ) {
                        $("#export-btn").show(); // Show button for tables
                    } else {
                        $("#export-btn").hide(); // Hide button for charts
                    }
                },
                renderers: $.extend(
                    $.pivotUtilities.renderers,
                    $.pivotUtilities.plotly_renderers // Adding Plotly renderers
                )
            });
        });

        // When the filter form is submitted, prevent default action and load filtered data
        $("#filterForm").submit(function (event) {
            event.preventDefault();
            loadFilteredPivotData(); // Call the function to load filtered data
        });

        // Export to Excel on button click
        $("#export-btn").on("click", function () {
            exportTableToExcel("pivot-container", "pivot_report.xlsx");
        });
    });

    // Export FunctionN
    async function exportTableToExcel(containerId, filename) {
        let table = document.querySelector(`#${containerId} .pvtTable`);
        if (!table) {
            alert("No table found to export.");
            return;
        }

        const workbook = new ExcelJS.Workbook();
        const worksheet = workbook.addWorksheet("Pivot Data");
        const baseRow = 5;
        const baseCol = 5;
        let currentRow = baseRow;

        // Add company details first (if not 'all')
        if ('{{company}}' !== 'all') {
            const companyDetails = {
                name: "{{ company.company|escapejs }}",
                address: "{{ company.address|escapejs }}",
                country: "{{ company.country|escapejs }}",
                state: "{{ company.state|escapejs }}",
                city: "{{ company.city|escapejs }}",
                zip: "{{ company.zip|escapejs }}"
            };

            function getBase64FromUrl(url) {
                return fetch(url)
                    .then(response => response.blob())
                    .then(blob => new Promise((resolve, reject) => {
                        const reader = new FileReader();
                        reader.onloadend = () => resolve(reader.result);
                        reader.onerror = reject;
                        reader.readAsDataURL(blob);
                    }));
            }

            const logoUrl = "{{ protocol }}://{{ host }}{{ company.icon.url }}";
            await getBase64FromUrl(logoUrl).then((base64) => {
                const base64Data = base64.split(',')[1];
                const imageId = workbook.addImage({
                    base64: base64Data,
                    extension: 'png'
                });

                worksheet.addImage(imageId, {
                    tl: { col: baseCol - 1, row: currentRow - 1 },
                    ext: { width: 80, height: 80 }
                });
            });

            // Merge cells for company details text
            const companyTextCell = worksheet.getCell(currentRow, baseCol + 1);
            worksheet.mergeCells(currentRow, baseCol + 1, currentRow, baseCol + 2);
            companyTextCell.value = {
                richText: [
                    { text: `\n${companyDetails.name}\n`, font: { size: 14, bold: true, color: { argb: 'FF333333' } } },
                    { text: `${companyDetails.address}\n`, font: { size: 11, color: { argb: 'FF333333' } } },
                    { text: `${companyDetails.country}, ${companyDetails.state}, ${companyDetails.city}\n`, font: { size: 11, color: { argb: 'FF333333' } } },
                    { text: `ZIP: ${companyDetails.zip}`, font: { size: 11, color: { argb: 'FF333333' } } }
                ]
            };
            companyTextCell.alignment = {
                horizontal: 'left',
                vertical: 'top',
                wrapText: true
            };
            worksheet.getRow(currentRow).height = 80;

            currentRow += 2; // Leave a blank row
        }

        // Add timestamp
        const timestamp = new Date().toLocaleDateString('en-GB') + ' ' +
            new Date().toLocaleTimeString('en-US', {
                hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: true
            });

        const downloadCell = worksheet.getCell(currentRow, baseCol);
        worksheet.mergeCells(currentRow, baseCol, currentRow, baseCol + 3);
        downloadCell.value = `Generated on: ${timestamp}`;
        downloadCell.alignment = { horizontal: 'left', vertical: 'middle', wrapText: true };
        downloadCell.font = { size: 10, italic: true, color: { argb: 'FF666666' }, bold: true };

        currentRow += 3;

        // Table rendering
        const cellMap = {};
        const allRows = Array.from(table.rows);
        const lastRowIndex = allRows.length - 1;

        allRows.forEach((row, rowIndex) => {

            let colIndex = baseCol;

            Array.from(row.cells).forEach((cell) => {

                while (cellMap[`${currentRow + rowIndex}-${colIndex}`]) {
                    colIndex++;
                }

                const rowspan = parseInt(cell.getAttribute("rowspan")) || 1;
                const colspan = parseInt(cell.getAttribute("colspan")) || 1;
                const cellValue = cell.textContent.trim();

                const excelCell = worksheet.getCell(currentRow + rowIndex, colIndex);
                excelCell.value = cellValue;

                const isHeader = rowIndex === 0;
                const isLastRow = rowIndex === lastRowIndex;

                excelCell.font = {
                    bold: isHeader || isLastRow,
                    size: isHeader ? 12 : 11,
                    color: {
                        argb: isHeader ? 'FFFFFFFF' :
                            isLastRow ? 'FF000000' :
                            'FF000000'
                    }
                };

                excelCell.fill = {
                    type: 'pattern',
                    pattern: 'solid',
                    fgColor: {
                        argb: isHeader ? 'FF545454' :
                            isLastRow ? 'FFFFE599' :  // light yellow
                            'FFF5F5F5'
                    }
                };

                excelCell.border = {
                    top: { style: 'thin' },
                    left: { style: 'thin' },
                    bottom: { style: 'thin' },
                    right: { style: 'thin' }
                };
                excelCell.alignment = { horizontal: "center", vertical: "middle" };

                if (rowspan > 1 || colspan > 1) {
                    worksheet.mergeCells(
                        currentRow + rowIndex,
                        colIndex,
                        currentRow + rowIndex + rowspan - 1,
                        colIndex + colspan - 1
                    );

                    for (let r = 0; r < rowspan; r++) {
                        for (let c = 0; c < colspan; c++) {
                            cellMap[`${currentRow + rowIndex + r}-${colIndex + c}`] = true;
                        }
                    }
                } else {
                    cellMap[`${currentRow + rowIndex}-${colIndex}`] = true;
                }

                colIndex++;
            });
        });

        worksheet.getRow(currentRow + lastRowIndex).height = 25; // adjust height for Total

        worksheet.getRow(currentRow).height = 30; // adjust height for Heading

        worksheet.columns.forEach(column => {
            let maxLength = 2;
            column.eachCell({ includeEmpty: true }, cell => {
                const value = cell.value ? cell.value.toString() : '';
                maxLength = Math.max(maxLength, value.length);
            });
            column.width = maxLength + 3;
        });


        const buffer = await workbook.xlsx.writeBuffer();
        const blob = new Blob([buffer], {
            type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        });

        const link = document.createElement("a");
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
    }
</script>



{% endblock content %}
