<?php 
$ReportID = $FormID = isset($_REQUEST['ReportID']) ? $_REQUEST['ReportID'] : 3654;
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Testing Drilldown</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-grid.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-alpine.css">
    <link rel="stylesheet" href="style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<script src="https://cdn.jsdelivr.net/npm/ag-grid-enterprise/dist/ag-grid-enterprise.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/ag-charts-enterprise@9.0.0/dist/umd/ag-charts-enterprise.js"></script>
</head>
<body>
    <div id="myGrid" class="ag-theme-alpine" style="height: 100vh; width: 100%;"></div>
	 <script>
        let gridApi;
        let gridOptions;
        async function getData1(par, col) { 
            console.log("params", par, par.dsnoid)
            try {
                const queryString = new URLSearchParams(par).toString();  // Convert row data to query string
                const response = await fetch(`/getDataForAGMasterDetail.php?detail_FormID=<?php echo $ReportID; ?>&detail_col_name=${col}&${queryString}`);
                // const response = await fetch('getDataForAGMasterDetail.php?col=' + col + '&DesignID='+ par.dsnoid );
                const data = await response.json();
                console.log('API->',data); 
                return data;
            } catch (error) {
                console.error('Error fetching data:', error);
                return [];
            }
        }

		class DetailGrid {
			constructor(params) {
				console.log("in DetailGrid Class", params)
				this.params = params;
                console.log("COLUMNS => ", params.context.selectedDetail)
				// this.rowData = await getData();
				// this.rowData = params.data.data;
				
				if (params.context.newRecords) {
					let continent = this.params.data.continent
					this.rowData = this.rowData.concat(
						params.context.newRecords[continent]
					);
				}
			}

			eGui() {
				var eTemp = document.createElement('div');
				eTemp.innerHTML = this.getTemplate();
				this.eGui = eTemp.firstElementChild;

				this.setupDetailGrid();
				return this.eGui;
			}

			async setupDetailGrid() {
				console.log('in setupDetailGrid')
                var apiResponse = await getData1(this.params.data, this.params.context.selectedDetail);
                console.log(apiResponse);
                if (!apiResponse || apiResponse.length < 2) {
                    $('.full-width-grid.ag-theme-alpine').html('<h3 style="text-align: center;">NO DATA</h3>');
                    return;
                }
                const rowData = apiResponse[0]; // First array contains the row data
                const dataStructure = apiResponse[1]; // Second array contains column definitions
                if (!rowData || rowData.length === 0) {
                    $('.full-width-grid.ag-theme-alpine').html('<h3 style="text-align: center;">NO DATA</h3>');
                    return;
                }

                // let filterParams = {maxNumConditions:5};
                var dateFilterParams = {
                    comparator: (filterLocalDateAtMidnight, cellValue) => {
                        var dateAsString = cellValue;
                        if (dateAsString == null) return -1;
                        var dateParts = dateAsString.split("-");
                        var cellDate = new Date(cellValue);
                        console.log(cellDate);
                        if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
                            return 0;
                        }
                        if (cellDate < filterLocalDateAtMidnight) {
                            return -1;
                        }
                        if (cellDate > filterLocalDateAtMidnight) {
                            return 1;
                        }
                        return 0;
                    },
                    maxNumConditions:5,
                    minValidYear: 1980,
                    maxValidYear: 2040,
                    // inRangeFloatingFilterDateFormat: "Do MMM YYYY",
                    // valueFormatter: function (params) {
                    //     return moment(params.value).format('D MMM YYYY');
                    // },
                };
                let filterParams = { maxNumConditions: 5 };
                var colDefs = dataStructure.map(col => {
                    let colDef = {
                        field: col.COLUMN_NAME,
                        colId: col.COLUMN_NAME,
                        filter: ["int", "bigint", "float", "decimal", "money"].includes(col.DATA_TYPE) ? 'agNumberColumnFilter' : 'agMultiColumnFilter',
                        filterParams
                    };

                    // Add date formatting & comparison if data type is date
                    if (["date", "smalldatetime", "datetime"].includes(col.DATA_TYPE)) {
                        colDef.filter = 'agDateColumnFilter';
                        colDef.filterParams = dateFilterParams;
                        colDef.valueFormatter = dateFormatter;
                        colDef.comparator = dateComparator;
                    }

                    return colDef;
                });
                console.log("ColDefs", colDefs)
				var detailGridOptions = {
                    columnDefs: colDefs,
					defaultColDef: {
						flex: 1,
						minWidth: 150,
					},
					rowData: rowData,
                    autoSizeStrategy: {
                        type: 'fitGridWidth',
                    }
				};
				var eDetailGrid = this.eGui.querySelector('.full-width-grid');
				// new agGrid.Grid(eDetailGrid, detailGridOptions);
				// this.detailGridApi = detailGridOptions.api;
				this.detailGridApi = agGrid.createGrid(eDetailGrid, detailGridOptions);

				var masterGridApi = this.params.api;
				var rowId = this.params.node.id;
				var gridInfo = {
					id: rowId,
					api: detailGridOptions.api,
					columnApi: detailGridOptions.columnApi,
				};
				masterGridApi.addDetailGridInfo(rowId, gridInfo);
			}

			getTemplate() {
				var template = `<div class="full-width-panel">
                    <div class="full-width-details"></div>
                    <div class="full-width-grid ag-theme-alpine"></div>
				</div>`;
				return template;
			}
		}

		class DetailCellRenderer {
			init(params) {
				console.log("in DetailCellRenderer Class")
				this.params = params;
				var colId = params.context.selectedDetail;
				// console.log(params)
                var setDetailGrid = new DetailGrid(params);
                this.eGui = setDetailGrid.eGui();
				// if (colId === "cost") {
                //     var costDetail = new CostDetail(params);
                //     this.eGui = costDetail.eGui();
				// } else if (colId === "orders") {
                //     var ordersFormDetail = new OrdersFormDetail(params);
                //     this.eGui = ordersFormDetail.eGui();
				// } else if (colId === "sales") {
                //     var salesDetail = new SalesDetail(params);
                //     this.eGui = salesDetail.eGui();
				// }
			}
			getGui() {
				return this.eGui;
			}
		}

		const treeOpen = 'https://raw.githubusercontent.com/LouisMoore-agGrid/js-ag-grid-52eyso/50413f659cdfbe903ec14d9a5d4b7cf175b76637/tree-open.svg';
		const treeClosed = 'https://raw.githubusercontent.com/LouisMoore-agGrid/js-ag-grid-52eyso/aacef9f45dae7ea5822c4b76bf1c981a74451435/tree-closed.svg';

		function makeMasterCellRenderer(params, col) {
			console.log("in makeMasterCellRenderer", params)
            console.log("Rendering Master Cell for Row:", params.node.data?.id || params.node.id);
            if (!params.node || !params.node.data) {
                console.error("Invalid node data, skipping rendering.");
                return document.createElement('span'); // Avoid undefined references
            }

			let container = document.createElement('div');
			let chevron = document.createElement('img');
			let span = document.createElement('span');
            let rowId = params?.data?.id || params?.node?.id || 'unknown'; // ← Fallback added
            // let isExpanded = !!params.context?.chevKeyMap?.[`row-${rowId}`];
            let isExpanded =  params.api.getRowNode(rowId)?.expanded;
            // let openCol = params.context?.chevKeyMap?.[`row-${rowId}`] || null;
            var openCol = params.context ? params.context.selectedDetail : null;

            console.log("=>", rowId, isExpanded, col, openCol, params.context)
            if (rowId !== 'unknown') {
                chevron.classList.add(`row-${rowId}`);
            }
            // chevron.classList.add(`row-${rowId}`); // Avoid 'row-undefined'
            chevron.classList.add('pointer-class');
            container.classList.add('master-container');

			let chevronState = isExpanded && col === openCol ? treeOpen : treeClosed;
			chevron.setAttribute('src', chevronState);
            // chevron.src = isExpanded ? treeOpen : treeClosed;
            span.innerText = params.value || '';
            container.appendChild(chevron);
            container.appendChild(span);

            chevron.addEventListener('click', (event) => {
                console.log("Opening detail grid...");
                let clickedChevron = event.target;
                openDetail(params, col, clickedChevron);
            });

            return container;
		}

        const openDetail = (params, column, cellRenderer) => {
            console.log("In openDetail");
            // Ensure gridApi is accessible
            if (!gridOptions || !gridApi || !params.node) {
                console.error("Grid or node not initialized.");
                return;
            }

            let className = '';
            cellRenderer.classList.forEach(cssClass => {
                if (cssClass.startsWith('row')) {
                    className = cssClass;
                }
            });
            if (!className) {
                console.error("Invalid class name reference in chevron.");
                return;
            }

            if (gridOptions.context.chevKeyMap[className] === column && params.node.expanded) {
                console.log("Before Closing:", params.node.data);
                params.node.setExpanded(false);
                console.log("After Closing:", params.node.data);
                cellRenderer.setAttribute('src', treeClosed);

                // **Fix: Remove reference properly to prevent undefined errors**
                delete gridOptions.context.chevKeyMap[className];
                // **Explicitly refresh the grid to ensure proper cleanup**
                // params.api.refreshCells({ force: true });
                setTimeout(() => {
                    console.log("Refreshing row renderers...");
                    // params.api.redrawRows({ rowNodes: [params.node] });
                }, 2000);

                return;
            }

            gridApi.setGridOption("context", { selectedDetail: column });

            let nodeRenderers = document.querySelectorAll(`.${className}`);
            nodeRenderers.forEach(renderer => renderer.setAttribute('src', treeClosed));

            params.node.setExpanded(true);
            gridOptions.context.chevKeyMap[className] = column;

            cellRenderer.setAttribute('src', treeOpen);

            if (params.node.detailNode) {
                params.api.redrawRows({ rowNodes: [params.node.detailNode] });
            }
        };

        async function getMasterData() { 
            try {
                const response = await fetch('https://ai.mindforgeerp.com/reportGetDataFromView2.php?ReportID=3654&fdate=2025-04-27&tdate=2025-04-27&Submit=FILTER&&username=mitesh'); // Change this to your API endpoint
                const apiResponse = await response.json();
                console.log('API Response ->', apiResponse);

                if (!apiResponse ) {
                    console.error('Invalid API response');
                    return { rowData: [], columnDefs: [], masterDetailColumns: null };
                }

                const rowData = apiResponse[0];
                const dataStructure = apiResponse[1];
                const masterDetailColumns = apiResponse[3];
                
                let filterParams = { maxNumConditions: 5 };
                let columnDefs = Object.keys(dataStructure).map(key => {
                    const { DATA_TYPE, COLUMN_NAME } = dataStructure[key];

                    let colDef = { field: COLUMN_NAME, colId: COLUMN_NAME };

                    if (["int", "bigint", "float", "decimal", "money"].includes(DATA_TYPE)) {
                        colDef.filter = 'agNumberColumnFilter';
                        colDef.filterParams = filterParams;
                    } else if (["date", "smalldatetime", "datetime"].includes(DATA_TYPE)) {
                        colDef.filter = 'agDateColumnFilter';
                        colDef.filterParams = filterParams;
                        colDef.valueFormatter = dateFormatter;
                        colDef.comparator = dateComparator;
                    } else {
                        colDef.cellDataType = 'text';
                        colDef.filter = 'agMultiColumnFilter';
                        colDef.filterParams = filterParams;
                    }

                    // **Apply Master-Detail Cell Renderer for ALL columns in masterDetailColumns array**
                    // console.log(masterDetailColumns, " CHECKING ", COLUMN_NAME, masterDetailColumns.includes(COLUMN_NAME));
                    if (masterDetailColumns.map(col => col.toLowerCase()).includes(COLUMN_NAME.toLowerCase())) {
                        console.log(COLUMN_NAME);
                        // colDef.cellRenderer = (params) => makeMasterCellRenderer(params, COLUMN_NAME);
                        colDef.cellRenderer = (params) => {
                            try {
                                return makeMasterCellRenderer(params, COLUMN_NAME);
                            } catch (e) {
                                console.error("CellRenderer error", e);
                                return '';
                            }
                        };
                    }

                    return colDef;
                });

                return { rowData, columnDefs, masterDetailColumns };         
            } catch (error) {
                console.error('Error fetching data:', error);
                return { rowData: [], columnDefs: [], masterDetailColumns: null };
            }
        }

		// Initialize the grid using the new createGrid method
		// const gridApi = agGrid.createGrid(document.querySelector('#myGrid'), gridOptions);
        (async function initializeGrid() {
            const { rowData, columnDefs, masterDetailColumns } = await getMasterData();
            // console.log(rowData)
            gridOptions = {
                columnDefs,
                rowData,
                masterDetail: true,
                getRowId: params => params.data.id,
                detailCellRenderer: 'myDetailCellRenderer',
                components: { myDetailCellRenderer: DetailCellRenderer },
                context: { 
                    // selectedDetails: masterDetailColumns, 
                    chevKeyMap: {} 
                },  // Store multiple columns
                onRowGroupOpened: function(event) {
                    const context = event.api.getContext?.() || event.api.context;
                    const rowId = event.node?.data?.id;
                    const key = `row-${rowId}`;

                    if (!rowId || !context?.chevKeyMap) return;

                    if (event.node.expanded) {
                        context.chevKeyMap[key] = event.column?.colId || context.selectedDetail;
                    } else {
                        delete context.chevKeyMap[key];
                    }
                },
                // autoSizeStrategy: { type: 'fitGridWidth' }
            };

            gridApi = agGrid.createGrid(document.querySelector('#myGrid'), gridOptions);
        })();

        // DATA FORMATTING
        function dateFormatter(params) {
            // console.log("///////////////", params);
            if(params == null)  return null;
            if(params.value == null)  return null;
            if(params.value.length > 5){
                var dateAsString = params.value;
                var dateParts = dateAsString.split("-");
                // console.log(`${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`);
                return `${dateParts[2]}-${dateParts[1]}-${dateParts[0]}`;
            }else{
                return null;
            }
        }
        // DATE COMPARATOR FOR SORTING
        function dateComparator(date1, date2) {
            // console.log(">>>>>>>", date1, date2)
            /*var date1Number = _monthToNum(date1);
            var date2Number = _monthToNum(date2);
            //console.log(date1, date1Number)
            if (date1Number === null && date2Number === null) {
            return 0;
            }
            if (date1Number === null) {
            return -1;
            }
            if (date2Number === null) {
            return 1;
            }

            return date1Number - date2Number;*/
            return 1;
        }
	 </script>
</body>
</html>
