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

<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 "Performance 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 "Objective" %}</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=""
                                                            >{% trans "Managers" %}</label
                                                        >
                                                        {{objective_filer_form.managers}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Key Result" %}</label>
                                                        {{objective_filer_form.employee_objective__key_result_id}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Assignees" %}</label>
                                                        {{objective_filer_form.assignees}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Duration" %} </label>
                                                        {{objective_filer_form.duration}}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Employee Objective" %}</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=""
                                                            >{% trans "Employees" %}</label
                                                        >
                                                        {{emp_obj_form.form.employee_id}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Start Date From" %}</label>
                                                        {{emp_obj_form.form.start_date_from}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Key Result" %}</label>
                                                        {{emp_obj_form.form.key_result_id}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Start Date Till" %} </label>
                                                        {{emp_obj_form.form.start_date_till}}
                                                    </div>
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-6">
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for=""
                                                            >{% trans "End Date From" %}</label
                                                        >
                                                        {{emp_obj_form.form.end_date_from}}
                                                    </div>
                                                    <div class="oh-input-group">
                                                        <label class="oh-label" for="">{% trans "Status" %}</label>
                                                        {{emp_obj_form.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="">{% trans "End Date Till" %}</label>
                                                        {{emp_obj_form.form.end_date_till}}
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Feedback" %}</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="{{feedback_filter_form.review_cycle.id_for_label}}">{% trans "Feedback Title" %}</label>
                                                        {{feedback_filter_form.review_cycle}}
                                                        </div>
                                                        <div class="oh-input-group">
                                                        <label class="oh-label" for="{{feedback_filter_form.status.id_for_label}}">{% trans "Status" %} </label>
                                                        {{feedback_filter_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="{{feedback_filter_form.employee_id.id_for_label}}">{% trans "Employee" %}</label>
                                                        {{feedback_filter_form.employee_id}}
                                                        </div>
                                                        <div class="oh-input-group">
                                                        <label class="oh-label" for="{{feedback_filter_form.manager_id.id_for_label}}">{% trans "Manager" %} </label>
                                                        {{feedback_filter_form.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="{{feedback_filter_form.colleague_id.id_for_label}}">{% trans "Colleague" %} </label>
                                                        {{feedback_filter_form.colleague_id}}
                                                        </div>
                                                        <div class="oh-input-group">
                                                        <label class="oh-label" for="{{feedback_filter_form.start_date.id_for_label}}">{% trans "Start Date" %}</label>
                                                        {{feedback_filter_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="{{feedback_filter_form.subordinate_id.id_for_label}}">{% trans "Subordinate" %}</label>
                                                        {{feedback_filter_form.subordinate_id}}
                                                        </div>
                                                        <div class="oh-input-group">
                                                        <label class="oh-label" for="{{feedback_filter_form.end_date.id_for_label}}">{% trans "End Date" %}</label>
                                                        {{feedback_filter_form.end_date}}
                                                        </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="objective">Objectives</option>
        <option value="employeeobjective">Employee Objective</option>
        <option value="feedback">Feedback</option>
    </select>


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

</div>



<script>

    $(function () {

        function loadPivotData(model) {
            // Hide all containers first
            $(".pivot-wrapper").hide();

            // Determine current container and row config
            let containerId = "";
            let rowsConfig = [];

            if (model === "feedback") {
                containerId = "pivot-feedback";
                rowsConfig = ["Title","Employee","Manager","Answerable Employees","Answered Employees","Questions","Answer"];
            } else if (model === "objective") {
                containerId = "pivot-objective";
                rowsConfig = ["Objective","Key Results","Manager","Assignees"];
            } else if (model === "employeeobjective") {
                containerId = "pivot-employeeobjective";
                rowsConfig = ["Employee", "Objective","Employee Keyresult","Keyresult Target Value","Keyresult Current Value"];
            }

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

            // Fetch and render data in its own container
            $.getJSON(`pms-pivot?model=${model}`, function (data) {
                let 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();
                        }

                        $(".pvtTotal, .pvtTotalLabel, .pvtGrandTotal, .pvtAggregator").hide();

                        setTimeout(() => {
                            $(".pvtAttrDropdown option").each(function () {
                                if (hiddenFields.includes($(this).text())) {
                                    $(this).remove();
                                }
                            });
                        }, 10);
                    }
                });
            });
        }


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

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

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

            if (selectedModel === "feedback") {
                containerId = "pivot-feedback";
                rowsConfig = ["Title","Employee", "Manager", "Answerable Employees", "Answered Employees", "Questions", "Answer"];
            } else if (selectedModel === "objective") {
                containerId = "pivot-objective";
                rowsConfig = ["Objective", "Key Results", "Manager", "Assignees"];
            } else if (selectedModel === "employeeobjective") {
                containerId = "pivot-employeeobjective";
                rowsConfig = ["Employee", "Objective", "Employee Keyresult", "Keyresult Target Value", "Keyresult Current Value"];
            }

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

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

                console.log("Filtered data:", 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();
                        }

                        $(".pvtTotal, .pvtTotalLabel, .pvtGrandTotal, .pvtAggregator").hide();
                    }
                });
            });
        }


        // Listen to dropdown
        $("#model-select").on("change", function () {
            let selectedModel = $(this).val();
            loadPivotData(selectedModel);
        });

        // Initial load
        loadPivotData("objective");


        // 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 = {};
            Array.from(table.rows).forEach((row, rowIndex) => {
                if (
                    row.classList.contains("pvtTotal") ||
                    row.classList.contains("pvtGrandTotal")
                ) return;

                let colIndex = baseCol;

                Array.from(row.cells).forEach((cell) => {
                    if (
                        cell.classList.contains("pvtTotal") ||
                        cell.classList.contains("pvtTotalLabel") ||
                        cell.classList.contains("pvtAggregator") ||
                        cell.classList.contains("pvtGrandTotal")
                    ) return;

                    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;

                    excelCell.font = {
                        bold: rowIndex === 0,
                        size: rowIndex === 0 ? 12 : 11,
                        color: { argb: rowIndex === 0 ? 'FFFFFFFF' : 'FF000000' }
                    };
                    excelCell.fill = {
                        type: 'pattern',
                        pattern: 'solid',
                        fgColor: { argb: rowIndex === 0 ? 'FF545454' : '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++;
                });
            });

            // Header row height
            worksheet.getRow(currentRow).height = 30;

            // Auto-adjust column widths
            worksheet.columns.forEach(column => {
                let maxLength = 5;
                column.eachCell({ includeEmpty: true }, cell => {
                    const value = cell.value ? cell.value.toString() : '';
                    maxLength = Math.max(maxLength, value.length);
                });
                column.width = maxLength + 0;
            });

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