{% extends "index.html" %}
{% block content %}
{% load static %}
{% load i18n %}
{% include 'filter_tags.html' %}

<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 "Leave 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 "Leave Request" %}</div>
                                        <div class="oh-accordion-body">
                                            <input type="hidden" value="{{request.GET.id}}" name="id">
                                            <div class="row">
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id.id_for_label }}">{% trans "Employees" %}</label>
                                                  {{form.employee_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.leave_type_id.id_for_label }}">{% trans "Leave Type" %}</label>
                                                  {{form.leave_type_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.start_date.id_for_label }}">{% trans "Start Date" %}</label>
                                                  {{form.start_date}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.end_date.id_for_label }}">{% trans "End Date" %}</label>
                                                  {{form.end_date}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.status.id_for_label }}">{% trans "Status" %}</label>
                                                  {{form.status}}
                                                </div>
                                              </div>

                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.from_date.id_for_label }}">{% trans "From Date" %}</label>
                                                  {{form.from_date}}
                                                </div>
                                              </div>

                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.to_date.id_for_label }}">{% trans "To Date" %}</label>
                                                  {{form.to_date}}
                                                </div>
                                              </div>

                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__company_id.id_for_label }}">{% trans "Company" %}</label>
                                                  {{form.employee_id__employee_work_info__company_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__reporting_manager_id.id_for_label }}">{% trans "Reporting Manager" %}</label>
                                                  {{form.employee_id__employee_work_info__reporting_manager_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__department_id.id_for_label }}">{% trans "Department" %}</label>
                                                  {{form.employee_id__employee_work_info__department_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__job_position_id.id_for_label }}">{% trans "Job Position" %}</label>
                                                  {{form.employee_id__employee_work_info__job_position_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__shift_id.id_for_label }}">{% trans "Shift" %}</label>
                                                  {{form.employee_id__employee_work_info__shift_id}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label" for="{{ form.employee_id__employee_work_info__work_type_id.id_for_label }}">{% trans "Work Type" %}</label>
                                                  {{form.employee_id__employee_work_info__work_type_id}}
                                                </div>
                                              </div>

                                            </div>
                                          </div>
                                    </div>
                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Available Leave" %}</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">{% trans "Employees" %}</label>
                                                        {{f.form.employee_id}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label">{% trans "Leave Type" %}</label>
                                                        {{f.form.leave_type_id}}
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label">{% trans "Available Days" %}</label>
                                                        {{f.form.available_days}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label">{% trans "Carryforward Days" %}</label>
                                                        {{f.form.carryforward_days}}
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label">{% trans "Total Leave Days" %}</label>
                                                        {{f.form.total_leave_days}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label">{% trans "Assigned Date" %}</label>
                                                        {{f.form.assigned_date}}
                                                    </div>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Available Days Greater or Equal" %}</label
                                                        >
                                                        {{f.form.available_days__gte}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Available Days Less Than or Equal" %}</label
                                                        >
                                                        {{f.form.available_days__lte}}
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Carryforward Days Greater or Equal" %}</label
                                                        >
                                                        {{f.form.carryforward_days__gte}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Carryforward Days Less Than or Equal" %}</label
                                                        >
                                                        {{f.form.carryforward_days__lte}}
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Total Leave Days Greater or Equal" %}</label
                                                        >
                                                        {{f.form.total_leave_days__gte}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label"
                                                            >{% trans "Total Leave Days Less Than or Equal" %}</label
                                                        >
                                                        {{f.form.total_leave_days__lte}}
                                                    </div>
                                                </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>
            </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>

    <!-- Model Selection Dropdown -->
    <span class="ms-1 fw-bold" style="font-size:16px;">Choose Report : </span>
    <select id="model-select" class="oh-select oh-select--sm ml-2 mb-2" style="width: 200px;">
        <option value="leave_request">Leave Request</option>
        <option value="available_leave">Available Leave</option>
    </select>

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



<script>

    $(function () {
        // Function to load pivot data dynamically
        function loadPivotData(model) {
            let url = `leave-pivot?model=${model}`;

            // Hide all container
            $(".pivot-wrapper").hide();

            let containerId = "";
            let rowsConfig = [];

            if (model === "leave_request"){
                containerId = "pivot-leave";
                rowsConfig = ["Name","Department","Shift", "Leave Type","Requested Days","Start Date","End Date","Status"]
            }else if (model === "available_leave"){
                containerId = "pivot-availableleave";
                rowsConfig = ["Name","Department", "Leave Type","Assigned Date","Total Leave Days","Available Days","Carryforward Days"]
            }


            // Show relevant container
            $("#" + containerId).show();

            // Fetch data dynamically based on model
            $.getJSON(url, function (data) {

                // Add Plotly renderers correctly
                let plotlyRenderers = $.pivotUtilities.plotly_renderers;

                // Initialize pivot table with Plotly enabled
                $("#" + containerId).pivotUI(data, {
                    rows: rowsConfig,
                    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, plotlyRenderers), // Add Plotly renderers
                });
            });
        }

        window.loadFilteredPivotData =function loadFilteredPivotData() {
            const selectedModel = $("#model-select").val();
            const formData = $("#filterForm").serialize();

            $(".pivot-wrapper").hide();

            let containerId = "";
            let rowsConfig = [];

            if (selectedModel === "leave_request"){
                containerId = "pivot-leave";
                rowsConfig = ["Name","Department","Shift", "Leave Type","Requested Days","Start Date","End Date","Status"]
            }else if (selectedModel === "available_leave"){
                containerId = "pivot-availableleave";
                rowsConfig = ["Name","Department", "Leave Type","Assigned Date","Total Leave Days","Available Days","Carryforward Days"]
            }

            $("#" + containerId).show();

            $.getJSON(`leave-pivot?model=${selectedModel}&${formData}`, function (data) {

                const plotlyRenderers = $.pivotUtilities.plotly_renderers;

                $("#" + containerId).pivotUI(data, {
                    rows: rowsConfig,
                    cols: [],
                    aggregatorName: "Count",
                    rendererName: "Table",
                    renderers: $.extend($.pivotUtilities.renderers, plotlyRenderers),
                    onRefresh: function (config) {
                        const currentRenderer = config.rendererName;
                        if (["Table", "Table Barchart", "Heatmap", "Row Heatmap", "Col Heatmap"].includes(currentRenderer)) {
                            $("#export-btn").show();
                        } else {
                            $("#export-btn").hide();
                        }

                    }
                });
            });
        }

        // Initial load with all models
        loadPivotData("leave_request");

        // Model selection change event
        $("#model-select").on("change", function () {
            let selectedModel = $(this).val();
            loadPivotData(selectedModel); // Reload pivot data with selected model
        });

        // Export to Excel on button click
        $("#export-btn").on("click", function () {
            let visiblePivot = $(".pivot-wrapper:visible .pvtTable").closest(".pivot-wrapper");

            if (visiblePivot.length) {
                exportTableToExcel(visiblePivot.attr("id"), "pivot_report.xlsx");
            }
        });



        // Export Function
        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; // Leave some rows before the table

            // ------------------------
            // Render pivot table
            // ------------------------
            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" };

                    // Merge
                    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

            // Auto-adjust column widths
            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;
            });

            // Save
            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 %}
