{% 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 "Candidate 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 "Candidate" %}</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 'Name' %}</label>
                                                    {{ f.form.candidate_name }}
                                                </div>
                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'Phone' %}</label>
                                                  {{ f.form.mobile }}
                                                </div>
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Country' %}</label>
                                                    <select name="country" class="oh-select-2 w-100 country" id="country">
                                                    </select>
                                                </div>

                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Recruitment' %}</label>
                                                    {{ f.form.recruitment_id }}
                                                </div>
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Job Position' %}</label>
                                                    {{ f.form.job_position_id }}
                                                </div>

                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'Is Hired' %}?</label>
                                                  {{ f.form.hired }}
                                                </div>
                                                <div class="col-sm-12 col-md-12 col-lg-12 mb-2">
                                                    <div class="oh-input-group">
                                                      <label class="oh-label">{% trans "Offer Status" %}</label>
                                                      {{f.form.offer_letter_status}}
                                                    </div>
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'Email' %}</label>
                                                  {{ f.form.email }}
                                                </div>

                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'Gender' %}</label>
                                                  {{ f.form.gender }}
                                                </div>

                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'State' %}</label>
                                                  <select name="state" class="oh-select-2 w-100 country" id="state">
                                                  </select>
                                                </div>

                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Department' %}</label>
                                                    {{ f.form.job_position_id__department_id }}
                                                </div>

                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Stage Type' %}</label>
                                                    {{ f.form.stage_id__stage_type }}
                                                </div>

                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans 'Is Canceled' %}?</label>
                                                  {{ f.form.canceled }}
                                                </div>
                                              </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Recruitment" %}</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 "Recruitment" %}</label>
                                                {{fr.form.title}}
                                            </div>
                                              <div class="oh-input-group">
                                                  <label class="oh-label">{% trans "Managers" %}</label>
                                                  {{fr.form.recruitment_managers}}
                                              </div>
                                              <div class="oh-input-group">
                                                <label class="oh-label">{% trans "Start Date" %}</label>
                                                {{fr.form.start_date}}
                                              </div>
                                              <div class="oh-input-group">
                                                <label class="oh-label">{% trans "Is Closed" %}</label>
                                                <select name="closed" id="closed" class="oh-select oh-select-2 w-100">
                                                  <option value="unknown">{% trans "Unknown" %}</option>
                                                  <option value="true">{% trans "True" %}</option>
                                                  <option value="false" selected>{% trans "False" %}</option>
                                                </select>
                                              </div>
                                            </div>
                                            <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans "Job Position" %}</label>
                                                    {{fr.form.open_positions}}
                                                </div>
                                              <div class="oh-input-group">
                                                <label class="oh-label">{% trans "Company" %}</label>
                                                {{fr.form.company_id}}
                                              </div>
                                              <div class="oh-input-group">
                                                <label class="oh-label">{% trans "End Date" %}</label>
                                                {{fr.form.end_date}}
                                              </div>
                                              <div class="oh-input-group">
                                                <label class="oh-label">{% trans "Is Published" %}</label>
                                                {{fr.form.is_published}}
                                              </div>
                                            </div>
                                            <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans "Start Date From" %}</label>
                                                  {{fr.form.start_from}}
                                                </div>
                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans "Is Active" %}?</label>
                                                  {{fr.form.is_active}}
                                                </div>
                                              </div>
                                              <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                  <label class="oh-label">{% trans "Till End Date" %}</label>
                                                  {{fr.form.end_till}}
                                                </div>
                                              </div>

                                            </div>
                                        </div>
                                    </div>

                                    <div class="oh-accordion">
                                        <div class="oh-accordion-header">{% trans "Onboarding" %}</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 "Recruitment" %}</label>
                                                    {{fo.form.recruitment_id}}
                                                </div>
                                                <div class="oh-input-group">
                                                <label class="oh-label">{% trans 'Stage' %}</label>
                                                {{ fo.form.stage_title }}
                                                </div>
                                                <div class="oh-input-group">
                                                <label class="oh-label">{% trans 'Task' %}</label>
                                                {{ fo.form.onboarding_task__task_title }}
                                                </div>
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Company' %}</label>
                                                    {{ fo.form.recruitment_id__company_id }}
                                                    </div>
                                            </div>

                                            <div class="col-sm-12 col-md-12 col-lg-6">
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Candidates' %}</label>
                                                    {{ fo.form.onboarding_task__candidates }}
                                                </div>
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Stage Manager' %}</label>
                                                    {{ fo.form.employee_id }}
                                                </div>
                                                <div class="oh-input-group">
                                                    <label class="oh-label">{% trans 'Task Manager' %}</label>
                                                    {{ fo.form.onboarding_task__employee_id }}
                                                </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;">{% trans "Choose Report" %} : </span>
    <select id="model-select" class="oh-select oh-select--sm ml-2 mb-2" style="width: 200px;">
        <option value="candidate">{% trans "Candidate" %}</option>
        <option value="recruitment">{% trans "Recruitment" %}</option>
        <option value="onboarding">{% trans "Onboarding" %}</option>
    </select>


    <!-- Pivot Container -->
    <div id="pivot-container" class="mb-5" style="width: 100%; overflow-x: auto;">
        <div id="pivot-candidate" class="pivot-wrapper" style="display:none;width: 100%; overflow-x: auto;"></div>
        <div id="pivot-recruitment" class="pivot-wrapper" style="display:none;width: 100%; overflow-x: auto;"></div>
        <div id="pivot-onboarding" 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 = `recruitment-pivot?model=${model}`;

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

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

            if (model === "candidate") {
                containerId = "pivot-candidate";
                rowsConfig = ["Recruitment","Job Position","Department","Candidate","Gender","Email"];
            } else if (model === "recruitment") {
                containerId = "pivot-recruitment";
                rowsConfig = ["Recruitment","Vacancy","Manager","Job Position","Start Date","End Date"];
            } else if (model === "onboarding") {
                containerId = "pivot-onboarding";
                rowsConfig = ["Recruitment","Candidates","Stage","Stage Manager","Task","Task Manager","Company"];
            }

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

            $.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
                        }
                        // Hide fields from dropdown but keep them available in the table
                        let hiddenFields = [
                            "Vacancy",
                        ];

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

                        setTimeout(function () {
                            $(".pvtAttrDropdown option").each(function () {
                                if (hiddenFields.includes($(this).text())) {
                                    $(this).remove(); // Remove from selection
                                }
                            });
                        }, 10);
                    },
                    renderers: $.extend(
                        $.pivotUtilities.renderers,
                        plotlyRenderers // Adding Plotly renderers
                    )
                });

            });
        }

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

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

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

            if (selectedModel === "candidate") {
                containerId = "pivot-candidate";
                rowsConfig = ["Recruitment","Job Position","Department","Candidate","Gender","Email"];
            } else if (selectedModel === "recruitment") {
                containerId = "pivot-recruitment";
                rowsConfig = ["Recruitment","Vacancy","Manager","Job Position","Start Date","End Date"];
            } else if (selectedModel === "onboarding") {
                containerId = "pivot-onboarding";
                rowsConfig = ["Recruitment","Candidates","Stage","Stage Manager","Task","Task Manager","Company"];
            }

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

            $.getJSON(`recruitment-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("candidate");

        // 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) => {

                    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;

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