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

<style>
      table,
    td,
    tr {
        padding: 0px;
        margin: 0px;
    }
    .group-name {
        width: 40%;
    }
    .group-total {
        width: 10%;
    }
    .table-gray {
        background-color: #eee;
    }
    .table td,
    .table th {
        padding: 0px;
        margin: 0px;
    }
    .bg-darker {
        background-color: #ddd;
    }
    td .table {
        border: 0px !important;
        margin-bottom: 0rem;
    }
    table td:first-child {
        padding-left: 5px;
    }
    .table-bordered.vertical-borders td,
    .table-bordered.vertical-borders th {
        border-left: 1px solid #dee2e6;
        border-right: 1px solid #dee2e6;
    }
    .table-bordered.vertical-borders thead th {
        padding: 0.25rem;
        border-top: none;
        border-bottom: 2px solid #dee2e6;
    }
    .table-bordered.vertical-borders tfoot th {
        padding: 0.25rem;
        border-top: 2px solid #dee2e6;
        border-bottom: none;
    }
.currency{
    font-weight: normal !important;
}
.underline{
    text-decoration: underline;
}
    .form-control {
        display: block;
        width: 100%;
        height: calc(1.5rem + 1px);
        padding: 0.375rem 0.75rem;
        font-size: 1rem;
        font-weight: 400;
        line-height: 1.5;
        color: #495057;
        background-color: #fff;
        background-clip: padding-box;
        border: 1px solid #ced4da;
        border-radius: 0.25rem;
        box-shadow: inset 0 0 0 transparent;
        transition: border-color .15s ease-in-out, box-shadow .15s ease-in-out;
    }
</style>


<div class="content-wrapper">
  
    <section class="content">
        <div class="container-fluid">
            <div class="card card-primary ">
                <div class="card-header">
                    <h4 class="card-title">Balance Sheet</h4>
                </div>

                <div class="card-body">
                    <form method="post" action="" id="FilterForm">
                        <div class="row align-items-end">
                            <div class="col-2">
                                <div class="form-group">
                                    <label for="fromDate">Starting
                                        Period</label>
                                    <input type="text" class="form-control nepaliDatePicker" name="fromDate" value="2078-4-1" id="fromDate" aria-describedby="helpId_fromDate" placeholder="Starting Period">

                                </div>
                            </div>
                            <div class="col-2">
                                <div class="form-group">
                                    <label for="toDate">Ending
                                        Period</label>
                                    <input type="text" class="form-control nepaliDatePicker" name="toDate" value="2079-3-32" id="toDate" aria-describedby="helpId_toDate" placeholder="Ending Period">

                                </div>
                            </div>
                            <div class=" text-center">
                                <div class="form-group">
                                    <label for="showOB">Opening</label>
                                    <input type="checkbox" class="form-control " name="showOB" id="showOB" aria-describedby="helpId_showOB" placeholder="Show Opening Balance">

                                </div>
                            </div>
                            <div class=" text-center">
                                <div class="form-group">
                                    <label for="showClosing">Closing</label>
                                    <input type="checkbox" class="form-control " name="showClosing" id="showClosing" aria-describedby="helpId_showClosing" placeholder="Show Closing Balance">

                                </div>
                            </div>
                            <div class=" text-center">
                                <div class="form-group">
                                    <label for="showPeriod">Period</label>
                                    <input type="checkbox" class="form-control " name="showPeriod" id="showPeriod" aria-describedby="helpId_showPeriod" placeholder="Show Periodic Balance">

                                </div>
                            </div>

                            <div class="col">
                                <div class="form-group d-flex justify-content-end">

                                    <button type="submit" class="btn btn-primary mr-2">Filter</button>
                                    <button class="btn btn-success expand-all mr-2" id="exportButton">Export</button>
                                    <button type="button" class="btn btn-warning" onclick="resetForm()">Reset</button>
                                </div>
                            </div>
                        </div>
                        <small>Currently Filter Option by period are
                            not available</small>
                    </form>

                    <script>
                        function resetForm() {
                            document.getElementById("fromDate").value = "2078-4-1";
                            document.getElementById("toDate").value = "2079-3-32";
                            document.getElementById("showOB").checked = false;
                            document.getElementById("showClosing").checked = false;
                            document.getElementById("FilterForm").submit();
                        }
                    </script>

                </div>

            </div>

        </div><!-- /.container-fluid -->
    </section>
    <div class="content">
        <div class="container-fluid">

            <div class="row">
                <div class="col">
                    <div class="card card-primary card-outline">
                        <div class="card-header">
                            <h5 class="m-0"><?php echo $pageTitle; ?> </h5>
                        </div>
                        <div class="card-body">

                            <?php

                            // echo $_POST['showClosing'];
                            $ReportOptions = array(
                                'showZeroBalances' => false,
                                'showOB' => false,
                                'showClosing' => true,
                                'showPeriod' => false,
                                'AmountColWidth' => 180,
                            );
                            ?>
                            <button class="btn btn-secondary toggle-collapse mr-2" id="toggleShowAll">Toggle
                                Collapse</button>
                            <table class="table table-bordered">
                                <thead>
                                    <tr>
                                        <td class="group-name">Particulars</td>
                                        <td class="group-total" width="<?php echo $ReportOptions['AmountColWidth']; ?>">Amount</td>



                                    </tr>

                                </thead>
                                <tbody>
                                    <tr>
                                        <td colspan="2">
                                            <?php $AccountGroups = $BIBAccounts->getAccountGroupsWithBalances(2); ?>
                                            <?php $Side1Total = 0; ?>
                                            <table class="table table-bordered vertical-borders" id="TrialBalanceTable" border="0">

                                                <?php
                                                // Initialize variables for column totals
                                                $incomes_totalOpeningDr = 0;
                                                $incomes_totalOpeningCr = 0;
                                                $incomes_totalThisYearDr = 0;
                                                $incomes_totalThisYearCr = 0;
                                                $incomes_totalClosingDr = 0;
                                                $incomes_totalClosingCr = 0;
                                                ?>
                                                <?php foreach ($AccountGroups as $group) : ?>
                                                    <tr class="group-heading" data-toggle="collapse" data-target="#group_<?php echo $group->acgroup_id; ?>">
                                                        <td class="group-name"><?php echo $group->acgroup_name; ?></td>

                                                        <td class="group-total" width="<?php echo $ReportOptions['AmountColWidth']; ?>"><?php echo myCurrency(($group->posting_side == "CR") ? $group->closing_balance : 0); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="7" class="group-details">
                                                            <div id="group_<?php echo $group->acgroup_id; ?>" class="collapse">
                                                                <?php $Accountcategories = $BIBAccounts->getRootCategoriesWithBalances($group->acgroup_id); ?>
                                                                <?php $BIBAccounts->renderAccountCategoriesTableForBS($Accountcategories, $ReportOptions, false, array()); ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php
                                                    // Update column totals
                                                    $Side1Total += $group->closing_balance;
                                                    ?>
                                                <?php endforeach; ?>
                                            </table>

                                            <?php $AccountGroups = $BIBAccounts->getAccountGroupsWithBalances(5); ?>

                                            <table class="table table-bordered vertical-borders" id="TrialBalanceTable">

                                                <?php
                                                // Initialize variables for column totals
                                                $incomes_totalOpeningDr = 0;
                                                $incomes_totalOpeningCr = 0;
                                                $incomes_totalThisYearDr = 0;
                                                $incomes_totalThisYearCr = 0;
                                                $incomes_totalClosingDr = 0;
                                                $incomes_totalClosingCr = 0;
                                                ?>
                                                <?php foreach ($AccountGroups as $group) : ?>
                                                    <tr class="group-heading" data-toggle="collapse" data-target="#group_<?php echo $group->acgroup_id; ?>">
                                                        <td class="group-name"><?php echo $group->acgroup_name; ?></td>

                                                        <td class="group-total"><?php echo myCurrency(($group->posting_side == "CR") ? $group->closing_balance : 0); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="7" class="group-details">
                                                            <div id="group_<?php echo $group->acgroup_id; ?>" class="collapse">
                                                                <?php $Accountcategories = $BIBAccounts->getRootCategoriesWithBalances($group->acgroup_id); ?>
                                                                <?php $BIBAccounts->renderAccountCategoriesTableForBS($Accountcategories, $ReportOptions, false, array()); ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php
                                                    // Update column totals
                                                    $Side1Total += $group->closing_balance;
                                                    ?>
                                                <?php endforeach; ?>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <table class="table table-bordered">
                                                <tr>
                                                    <th>Total Amount</th>

                                                    <th class="cr closing-cr">
                                                        <?php echo myCurrency($Side1Total); ?>
                                                    </th>
                                                </tr>

                                            </table>

                                        </td>

                                    </tr>
                                    <tr>
                                        <td colspan="2">
                                            <?php $AccountGroups = $BIBAccounts->getAccountGroupsWithBalances(1); ?>
                                            <table class="table table-bordered vertical-borders" id="TrialBalanceTable">

                                                <?php
                                                // Initialize variables for column totals
                                                $totalOpeningDr = 0;
                                                $totalOpeningCr = 0;
                                                $totalThisYearDr = 0;
                                                $totalThisYearCr = 0;
                                                $totalClosingDr = 0;
                                                $totalClosingCr = 0;
                                                ?>
                                                <?php foreach ($AccountGroups as $group) : ?>
                                                    <tr class="group-heading" data-toggle="collapse" data-target="#group_<?php echo $group->acgroup_id; ?>">
                                                        <td class="group-name"><?php echo $group->acgroup_name; ?></td>
                                                        <td class="group-total"><?php echo myCurrency(($group->posting_side == "DR") ? $group->closing_balance : 0); ?></td>
                                                    </tr>
                                                    <tr>
                                                        <td colspan="7" class="group-details">
                                                            <div id="group_<?php echo $group->acgroup_id; ?>" class="collapse">
                                                                <?php $Accountcategories = $BIBAccounts->getRootCategoriesWithBalances($group->acgroup_id); ?>
                                                                <?php $BIBAccounts->renderAccountCategoriesTableForBS($Accountcategories, $ReportOptions, false, array()); ?>
                                                            </div>
                                                        </td>
                                                    </tr>
                                                    <?php
                                                    // Update column totals
                                                    $totalOpeningDr += ($group->posting_side == "DR") ? $group->opening_balance : 0;
                                                    $totalOpeningCr += ($group->posting_side == "CR") ? $group->opening_balance : 0;
                                                    $totalThisYearDr += ($group->posting_side == "DR") ? $group->regular_balance : 0;
                                                    $totalThisYearCr += ($group->posting_side == "CR") ? $group->regular_balance : 0;
                                                    $totalClosingDr += ($group->posting_side == "DR") ? $group->closing_balance : 0;
                                                    $totalClosingCr += ($group->posting_side == "CR") ? $group->closing_balance : 0;
                                                    ?>
                                                <?php endforeach; ?>

                                            </table>
                                        </td>
                                    </tr>

                                    <?php
                                    // pre($BIBAccounts->getAccountGroupsWithBalances(4));
                                    $TotalIncomes = $BIBAccounts->getAccountGroupsWithBalances(3)[0]->closing_balance;

                                    $TotalExpenses = $BIBAccounts->getAccountGroupsWithBalances(4)[0]->closing_balance;

                                    $PL = $TotalIncomes - $TotalExpenses;
                                    $Side1Total += $PL;
                                    ?>

                                    <tr>
                                        <td colspan="2">
                                            <table class="table table-bordered">
                                                <tr>
                                                    <td>Total Profit/Loss</td>
                                                    <td class="cr closing-cr"><?php echo myCurrency($PL); ?></td>
                                                </tr>
                                            </table>

                                        </td>

                                    </tr>


                                    <tr>
                                        <td colspan="2">
                                            <table class="table table-bordered">

                                                <tr>
                                                    <th>Total Amount</th>
                                                    <th class="dr closing-dr">

                                                        <?php echo myCurrency($totalClosingDr); ?>


                                                    </th>

                                                </tr>
                                            </table>

                                        </td>

                                    </tr>


                            </table>







                        </div>


                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<?php
function footerfunctions()
{
?>
    <script>
        $(document).ready(function() {
            document.getElementById("toggleShowAll").click();

        });
        var exportButton = document.getElementById("exportButton");
        exportButton.addEventListener("click", function() {
            exportTableToCSV("table.csv");
        });


        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");
                }
            }
        });


        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();
        }
    </script>

<?php
}