<?php
$this->load->library("NewAcc");
$Acc = new NewAcc();

?>

<div class="content-wrapper">
   
    <div class="container-fluid">
        <style>
            td,tr{
                margin: 0;
                padding: 0;
            }
            .particulars {
                text-align: center;
            }

            .particulars-names {
                text-align: left;
            }

            .openingDr {
                text-align: center;
            }

            .openingCr {
                text-align: center;
            }

            .closingDr {
                text-align: center;
            }

            .closingCr {
                text-align: center;
            }

            .collapsing {
                transition: height 0.3s ease;
                overflow: hidden;
            }

            .table-responsive {
                overflow-x: visible;
            }

            .nested-table {
                width: 100%;
            }

          

            .hide {
                display: none;
            }
        </style>
        <script src="https://unpkg.com/xlsx/dist/xlsx.full.min.js"></script>


        <button id="toggleShowAll">Toggle Show All</button>
        <button id="toggleColumns">Toggle Opening Balance Columns</button>
        <button id="exportButton">Export</button>
        <button id="exportButtonXLS">Export</button>

        <script>


        </script>
        <table class="table table-bordered" id="myTrialBalance">
            <thead>
                <tr class="bg-dark text-white">
                    <th rowspan="2" class="particulars">Particulars</th>
                    <th class="openingDr col-4" colspan="2">Opening Balance</th>
                    <th class="closingDr col-4" colspan="2">Closing Balance</th>
                </tr>
                <tr class="bg-dark text-white">
                    <th class="openingDr col-1">Debit</th>
                    <th class="openingCr col-1">Credit</th>
                    <th class="closingDr col-1">Debit</th>
                    <th class="closingCr col-1">Credit</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($Acc->getAccountGroups() as $AccountGroup) : ?>


                    
                        <tr class="bg-gray" data-toggle="collapse" data-target="#group-<?php echo $AccountGroup->acgroup_id; ?>" aria-expanded="false" aria-controls="group-<?php echo $AccountGroup->acgroup_id; ?>">
                            <td class="particulars-names"><?php echo $AccountGroup->acgroup_name; ?></td>
                            <td class="openingDr col-1"><?php echo myCurrency($AccountGroup->openingdr); ?></td>
                            <td class="openingCr col-1"><?php echo myCurrency($AccountGroup->openingcr); ?></td>
                            <td class="closingDr col-1"><?php echo myCurrency($AccountGroup->dr); ?></td>
                            <td class="closingCr col-1"><?php echo myCurrency($AccountGroup->cr); ?></td>
                        </tr>
                        <tr id="group-<?php echo $AccountGroup->acgroup_id; ?>" class="collapse">
                            <td colspan="5">
                                <table class="nested-table">
                                    <?php
                                    foreach ($Acc->getAccountCategories($AccountGroup->acgroup_id, "onlyParents") as $ParentCategory) {
                                        generateNestedTable($ParentCategory, "group-" . $AccountGroup->acgroup_id);
                                    }
                                    ?>
                                </table>
                            </td>
                        </tr>
                    
                <?php endforeach; ?>
            </tbody>
        </table>


        <script>
            // Toggle Show/Hide OpeningDr and OpeningCr columns
            var exportButton = document.getElementById("exportButton");
            exportButton.addEventListener("click", function() {
                exportTableToCSV("table.csv");
            });
            // var exportButton = document.getElementById("exportButtonXLS");
            // exportButton.addEventListener("click", function() {
            //     exportTableToXLS("table.xls");
            // });
            var exportButton = document.getElementById("exportButtonXLS");
            exportButton.addEventListener("click", function() {
                exportTableToXLS("table.xls");
            });

            document.getElementById("toggleShowAll").addEventListener("click", function() {
                var nestedRows = document.getElementsByClassName("collapse");
                for (var i = 0; i < nestedRows.length; i++) {
                    if (nestedRows[i].classList.contains("show")) {
                        nestedRows[i].classList.remove("show");
                    } else {
                        nestedRows[i].classList.add("show");
                    }
                }
            });



            var toggleButton = document.getElementById("toggleColumns");
            toggleButton.addEventListener("click", function() {

                var openingDrCells = document.querySelectorAll(".openingDr");
                var openingCrCells = document.querySelectorAll(".openingCr");
                var particularCells = document.querySelectorAll(".particulars-names");
                // var openingBalanceHeaders = document.querySelectorAll(".openingDr, .openingCr");
                for (var i = 0; i < openingDrCells.length; i++) {
                    openingDrCells[i].classList.toggle("hide");
                }
                for (var j = 0; j < openingCrCells.length; j++) {
                    openingCrCells[j].classList.toggle("hide");
                }

                for (var i = 0; i < particularCells.length; i++) {
                    particularCells[i].classList.toggle("col-10");
                }
                for (var i = 0; i < openingBalanceHeaders.length; i++) {
                    openingBalanceHeaders[i].classList.toggle("hide");
                }
            });



            function exportTableToCSV(filename) {
                var csv = [];
                var rows = document.querySelectorAll("table tr:not(.hide)");

                for (var i = 0; i < rows.length; i++) {
                    var row = [];
                    var cols = rows[i].querySelectorAll("td:not(.hide), th:not(.hide)");

                    // Check if the parent row is collapsed or hidden
                    var parentRow = rows[i].closest(".collapse");
                    var isParentCollapsed = parentRow && (!parentRow.classList.contains("show"));

                    if (isParentCollapsed) {
                        continue; // Skip child table rows if parent is collapsed
                    }

                    for (var j = 0; j < cols.length; j++) {
                        var cellValue = cols[j].innerText.replace(/,/g, ""); // Remove commas from the cell value
                        row.push(cellValue);
                    }

                    csv.push(row.join(","));
                }

                // Create a CSV file
                var csvContent = "data:text/csv;charset=utf-8," + csv.join("\n");
                var encodedUri = encodeURI(csvContent);
                var link = document.createElement("a");
                link.setAttribute("href", encodedUri);
                link.setAttribute("download", filename);
                document.body.appendChild(link);
                link.click();
            }

          


            function exportTableToXLS(filename) {
                var table = document.getElementById("myTrialBalance");

                // Create a new workbook
                var workbook = XLSX.utils.book_new();

                // Convert the visible columns and rows of the main table to a worksheet
                var mainWorksheet = XLSX.utils.table_to_sheet(table, {
                    display: true,
                });

                // Hide hidden and collapsed columns
                var cols = table.querySelectorAll("th:not(.hide), td:not(.hide)");
                cols.forEach(function(cell) {
                    var columnIndex = XLSX.utils.decode_cell(cell.getAttribute("data-sheets-column-index")).c;
                    var isHidden = cell.classList.contains("hide") || cell.parentElement.classList.contains("hide");
                    if (isHidden) {
                        XLSX.utils.sheet_set_hidden(mainWorksheet, columnIndex, true);
                    }
                });

                // Append the main worksheet to the workbook
                XLSX.utils.book_append_sheet(workbook, mainWorksheet, "Sheet1");

                // Process child tables
                var childTables = table.querySelectorAll(".nested-table");
                childTables.forEach(function(childTable) {
                    // Check if the parent row is collapsed or hidden
                    var parentRow = childTable.closest(".collapse");
                    var isParentCollapsed = parentRow && !parentRow.classList.contains("show");
                    if (isParentCollapsed) {
                        return; // Skip child table if parent is collapsed
                    }

                    // Convert the visible columns and rows of the child table to a worksheet
                    var childWorksheet = XLSX.utils.table_to_sheet(childTable, {
                        display: true,
                    });

                    // Hide hidden columns
                    var childCols = childTable.querySelectorAll("th:not(.hide), td:not(.hide)");
                    childCols.forEach(function(cell) {
                        var columnIndex = XLSX.utils.decode_cell(cell.getAttribute("data-sheets-column-index")).c;
                        var isHidden = cell.classList.contains("hide");
                        if (isHidden) {
                            XLSX.utils.sheet_set_hidden(childWorksheet, columnIndex, true);
                        }
                    });

                    // Append the child worksheet to the workbook
                    XLSX.utils.book_append_sheet(workbook, childWorksheet, "Sheet1");
                });

                // Convert workbook to binary XLS format
                var xlsContent = XLSX.write(workbook, {
                    type: "binary",
                    bookType: "xls",
                });

                // Convert binary content to ArrayBuffer
                var buffer = new ArrayBuffer(xlsContent.length);
                var view = new Uint8Array(buffer);
                for (var i = 0; i < xlsContent.length; i++) {
                    view[i] = xlsContent.charCodeAt(i) & 0xff;
                }

                // Create Blob from ArrayBuffer
                var blob = new Blob([buffer], {
                    type: "application/octet-stream"
                });

                // Create a download link for the XLS file
                var link = document.createElement("a");
                link.href = window.URL.createObjectURL(blob);
                link.download = filename;

                // Trigger the download
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
        </script>

    </div>
</div>

<?php
function generateNestedTable($parentCategory, $parentRowID = "")
{
    $CI = &get_instance();
    $CI->load->library("NewAcc");
    $Acc = new NewAcc();

    $childCategories = $Acc->getChildCategories($parentCategory->accategory_id);

    if (empty($childCategories)) {
        // No child categories, generate a single row
?>
        <tr class="bg-gray" data-toggle="collapse" data-target="#parents-<?php echo $parentCategory->accategory_id; ?>" aria-expanded="false" aria-controls="parents-<?php echo $parentCategory->accategory_id; ?>">
            <td class="particulars-names col-8"><?php echo $parentCategory->accategory_name; ?> AAA</td>
            <td class="openingDr col-1"><?php echo myCurrency($parentCategory->openingdr); ?></td>
            <td class="openingCr col-1"><?php echo myCurrency($parentCategory->openingcr); ?></td>
            <td class="closingDr col-1"><?php echo myCurrency($parentCategory->dr); ?></td>
            <td class="closingCr col-1"><?php echo myCurrency($parentCategory->cr); ?></td>
        </tr>
        <tr id="parents-<?php echo $parentCategory->accategory_id; ?>" class="collapse">
            <td colspan="5">
                <table class="nested-table">
                    <?php foreach ($Acc->getAccountsByCategory($parentCategory->accategory_id) as $Accounts) { ?>
                        <tr>
                            <td class="particulars-names col-8"><?php echo $Accounts->account_name; ?>  </td>
                            <td class="openingDr col-1"><?php echo myCurrency($Accounts->openingdr); ?></td>
                            <td class="openingCr col-1"><?php echo myCurrency($Accounts->openingcr); ?></td>
                            <td class="closingDr col-1"><?php echo myCurrency($Accounts->dr); ?></td>
                            <td class="closingCr col-1"><?php echo myCurrency($Accounts->cr); ?></td>
                        </tr>
                    <?php } ?>

                </table>
            </td>
        </tr>
    <?php
    } else {
        // Generate parent category row with collapse toggle
    ?>
        <tr class="bg-primary" data-toggle="collapse" data-target="#parents-<?php echo $parentCategory->accategory_id; ?>" aria-expanded="false" aria-controls="parents-<?php echo $parentCategory->accategory_id; ?>">
            <td class="particulars-names col-8"><?php echo $parentCategory->accategory_name; ?> </td>
            <td class="openingDr col-1"><?php echo myCurrency($parentCategory->openingdr); ?></td>
            <td class="openingCr col-1"><?php echo myCurrency($parentCategory->openingcr); ?></td>
            <td class="closingDr col-1"><?php echo myCurrency($parentCategory->dr); ?></td>
            <td class="closingCr col-1"><?php echo myCurrency($parentCategory->cr); ?></td>
        </tr>
        <tr id="parents-<?php echo $parentCategory->accategory_id; ?>" class="collapse">
            <td colspan="5">
                <table class="nested-table">
                    <?php foreach ($childCategories as $childCategory) : ?>
                        <?php generateNestedTable($childCategory); ?>
                    <?php endforeach; ?>
                </table>
            </td>
        </tr>
<?php
    }
}