<?php
include_once('dbClass.php');
session_start();
$k_head_title=$k_page_title ='HOME';
include 'k_files/k_header.php';
?>
<section class="panel grid1">
    <header class="panel-heading">
        <div style="display: flex; justify-content: space-between;">
            <h2 class="panel-title" style="margin: 0;">Report</h2>
        </div>
        <p class="panel-subtitle">Template</p>
    </header>
    <div class="panel-body">
        <div id="grid1" class="ag-theme-alpine" style="height: 300px;"></div>
    </div>
</section>
<section class="panel grid2">
    <header class="panel-heading">
        <div style="display: flex; justify-content: space-between;">
            <h2 class="panel-title" style="margin: 0;">Report</h2>
        </div>
        <p class="panel-subtitle">Template</p>
    </header>
    <div class="panel-body">
        <div id="grid2" class="ag-theme-alpine" style="height: 300px;"></div>
    </div>
</section>
<section class="panel grid3">
    <header class="panel-heading">
        <div style="display: flex; justify-content: space-between;">
            <h2 class="panel-title" style="margin: 0;">Report</h2>
        </div>
        <p class="panel-subtitle">Template</p>
    </header>
    <div class="panel-body">
        <div id="grid3" class="ag-theme-alpine" style="height: 300px;"></div>
    </div>
</section>
<section class="panel grid4">
    <header class="panel-heading">
        <div style="display: flex; justify-content: space-between;">
            <h2 class="panel-title" style="margin: 0;">Report</h2>
        </div>
        <p class="panel-subtitle">Template</p>
    </header>
    <div class="panel-body">
        <div id="grid4" class="ag-theme-alpine" style="height: 300px;"></div>
    </div>
</section>

<script src="https://cdn.jsdelivr.net/npm/ag-grid-enterprise@33.2.1/dist/ag-grid-enterprise.js?t=55198984654"></script>
<!-- <script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script> -->
<script src="https://cdn.jsdelivr.net/npm/ag-charts-enterprise@11.2.0/dist/umd/ag-charts-enterprise.min.js"></script>
<script>
    agGrid.LicenseManager.setLicenseKey("[TRIAL]_this_{AG_Charts_and_AG_Grid}_Enterprise_key_{AG-076336}_is_granted_for_evaluation_only___Use_in_production_is_not_permitted___Please_report_misuse_to_legal@ag-grid.com___For_help_with_purchasing_a_production_key_please_contact_info@ag-grid.com___You_are_granted_a_{Single_Application}_Developer_License_for_one_application_only___All_Front-End_JavaScript_developers_working_on_the_application_would_need_to_be_licensed___This_key_will_deactivate_on_{31 March 2025}____[v3]_[0102]_MTc0MzM3NTYwMDAwMA==c6567fdb808acaba121aed5798506e61"); //new taken from ai mindforge
    
    async function initializeGrid(gridId, apiUrl) {
        const { 0: rowData, 1: columnStructure } = await fetchGridData(apiUrl);
        
        const gridOptions = {
            columnDefs: generateColumnDefs(columnStructure),
            rowData: rowData,
            pagination: true,
            defaultColDef: { flex: 1, filter: true, sortable: true },
        };

        // new agGrid.Grid(document.getElementById(gridId), gridOptions);
        console.log("==>>>",document.getElementById(gridId)); // Should NOT be null
        agGrid.createGrid(document.getElementById(gridId), gridOptions);
    }
    async function initializeGrid1(gridId, apiUrl) {
        alert(gridId);
        var { 0: rowData, 1: columnStructure, 4: gridConfig, 5: TemplateName, 6: ReportName } = await fetchGridData(apiUrl);
        gridConfig = JSON.parse(gridConfig);
        // console.log(".grid" + gridId + " .panel-title");
        $("." + gridId + " .panel-title").text(ReportName);
        $("." + gridId + " .panel-subtitle").html(TemplateName);
        const gridOptions = {
            columnDefs: generateColumnDefs(columnStructure),
            rowData: rowData,
            pagination: true,
            defaultColDef: { flex: 1, filter: true, sortable: true },
            pivotMode: gridConfig?.pivot?.pivotMode ?? false,
            // sideBar: gridConfig.sideBar, // Apply sidebar settings
            onGridReady: params => {
                if (params.api) {
                    window[`${gridId}Api`] = params.api; // Store API reference

                    // Apply Column Sizing
                    if (gridConfig?.columnSizing?.columnSizingModel) {
                        params.api.applyColumnState({
                            state: gridConfig.columnSizing.columnSizingModel,
                            applyOrder: true
                        });
                    } else {
                        console.warn("columnSizingModel is missing or incorrectly formatted.");
                    }

                    // Apply Sorting
                    if (gridConfig?.sort?.sortModel && Array.isArray(gridConfig.sort.sortModel)) {
                        params.api.applyColumnState({
                            state: gridConfig.sort.sortModel.map(model => ({
                                colId: model.colId,
                                sort: model.sort
                            })),
                            applyOrder: true
                        });
                    } else {
                        console.warn("sortModel is missing or incorrectly formatted.");
                    }

                    // Apply Row Grouping
                    if (gridConfig?.rowGroup?.groupColIds && Array.isArray(gridConfig.rowGroup.groupColIds)) {
                        params.api.applyColumnState({
                            state: gridConfig.rowGroup.groupColIds.map(colId => ({ colId, rowGroup: true }))
                        });
                    } else {
                        console.warn("rowGroup.groupColIds is missing or incorrectly formatted.");
                    }

                    // Apply Aggregations
                    if (gridConfig?.aggregation?.aggregationModel && Array.isArray(gridConfig.aggregation.aggregationModel)) {
                        params.api.applyColumnState({
                            state: gridConfig.aggregation.aggregationModel.map(model => ({
                                colId: model.colId,
                                aggFunc: model.aggFunc
                            })),
                            applyOrder: true
                        });
                    } else {
                        console.warn("aggregationModel is missing or incorrectly formatted.");
                    }

                    // Apply Column Visibility
                    if (gridConfig?.columnVisibility?.hiddenColIds && Array.isArray(gridConfig.columnVisibility.hiddenColIds)) {
                        gridConfig.columnVisibility.hiddenColIds.forEach(colId => {
                            if (params.columnApi) {
                                params.columnApi.setColumnVisible(colId, false);
                            }
                        });
                    } else {
                        console.warn("hiddenColIds is missing or incorrectly formatted.");
                    }

                    // Set Focused Cell if Available
                    if (gridConfig?.focusedCell) {
                        params.api.setFocusedCell(gridConfig.focusedCell.rowIndex, gridConfig.focusedCell.colId);
                    }
                
                } else {
                    console.error("Grid API not available.");
                }
            }

        };

        agGrid.createGrid(document.getElementById(gridId), gridOptions);
    }

    document.addEventListener("DOMContentLoaded", function() {
        // Call function to initialize grid
        initializeGrid( 'grid2', 'https://ai.mindforgeerp.com/reportGetDataFromView2-Template.php?ReportID=5193&username=mitesh');
        initializeGrid1('grid1', 'https://ai.mindforgeerp.com/reportGetDataFromView2-Template.php?ReportID=0&username=mitesh&TemplateID=1170');
        initializeGrid( 'grid3', 'https://ai.mindforgeerp.com/reportGetDataFromView2-Template.php?ReportID=4867&username=mitesh');
        initializeGrid( 'grid4', 'https://ai.mindforgeerp.com/reportGetDataFromView2-Template.php?ReportID=4740&username=mitesh');
    });

    async function fetchGridData(apiUrl) {
        try {
            const response = await fetch(apiUrl);
            if (!response.ok) throw new Error("Failed to fetch data");
            const data = await response.json();
            return data;
        } catch (error) {
            console.error("Error fetching data:", error);
            return { rowData: [], columnStructure: [] };
        }
    }

    function generateColumnDefs(columnStructure) {
        return columnStructure.map(col => ({
            field: col.COLUMN_NAME,
            headerName: col.COLUMN_NAME.replace(/_/g, ' ').toUpperCase(),
            sortable: true,
            filter: true,
            resizable: true,
            editable: false, // Change if needed
            ...(col.DATA_TYPE === 'float' || col.DATA_TYPE === 'bigint' ? { type: 'numericColumn', cellStyle: { textAlign: 'right' } } : {}),
        }));
    }

</script>

<?php
include "k_files/k_footer.php"; 
?>
<script>
    $(document).ready(function(){
        // $(".sidebar-toggle").click();
        // $("#mySearch").focus();
        $(".page-header h2").html("Dashboard");
	    $(document).prop('title', 'Dashboard');
    });
</script>