<?php
include("../../classes/manager.class.php");
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$customer_id = "";
$product_id = "";
$grandTotalOpening = 0;

if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);

if ($datefrom == "") {
    $datefrom = date('d-m-Y', strtotime("-30 days"));
} else {
    $datefrom = date("d-m-Y", strtotime($datefrom));
}
if ($dateto == "") {
    $dateto = date('d-m-Y');
} else {
    $dateto = date("d-m-Y", strtotime($dateto));
}


$dateFromFormatted = date('Y-m-d', strtotime($datefrom));
$dateToFormatted = date('Y-m-d', strtotime($dateto));



// Apply all filter if specified
$supplier_id = isset($supplier_id) ? $supplier_id : 'All';
$category_id = isset($category_id) ? $category_id : 'All';
$payment_type = isset($payment_type) ? $payment_type : 'All';

$filter = "WHERE date BETWEEN '$dateFromFormatted' AND '$dateToFormatted'";
if ($supplier_id != 'All') {
    $filter .= " AND supplier_id = '$supplier_id'";
}
if ($category_id != 'All') {
    $filter .= " AND category_id = '$category_id'";
}
if ($payment_type != 'All') {
    $filter .= " AND payment_type = '$payment_type'";
}

// At this point, the $filterReport is ready to be passed into the method
$data = ExpenseTaxSetup::GetExpenseTaxSetupList($filter);
$categories = ExpenseTaxCategorySetup::GetExpenseTaxCategorySetupList("ORDER BY parent_id, id");
$categoryMap = [];
foreach ($categories as $cat) {
    $categoryMap[$cat->id] = $cat;
}

$grouped = [];
foreach ($data as $row) {
    $parentId = isset($categoryMap[$row->category_id]) ? $categoryMap[$row->category_id]->parent_id : 0;
    $subId = $row->category_id;
    $grouped[$parentId][$subId][] = $row;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<!-- Start Page Loading -->
<div id="loader-wrapper">
    <div id="loader"></div>
    <div class="loader-section section-left"></div>
    <div class="loader-section section-right"></div>
</div>
<!-- End Page Loading -->
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <div class="">
                <h3>Summary Expense Report</h3>
            </div>
            <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                });
            </script>
            <form action="" method="get" name="search"
                  id="searchfrm">
                <table class="table" >
                    <tr>
                        <td class="col s6">Date From<br>
                            <input type="text" name="datefrom" id="datepicker"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control"/>
                        </td>
                        <td class="col s6"> Date To<br>
                            <input type="text" name="dateto" id="datepicker1"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="form-control"/>
                        </td>
                    </tr>
                    <tr>
                        <td class="col s4">Supplier<br>
                            <select name="supplier_id" class="form-control">
                                <option value="All">All</option>
                                <?php foreach (SupplierSetup::GetSupplierSetupList() as $s) { ?>
                                    <option value="<?= $s->id ?>" <?= $supplier_id == $s->id ? 'selected' : '' ?>><?= $s->name ?></option>
                                <?php } ?>
                            </select>
                        </td>
                        <td class="col s4">Category<br>
                            <select name="category_id" class="form-control">
                                <option value="All">All</option>
                                <?php foreach ($categories as $cat) {
                                    if ($cat->parent_id != 0) {
                                        echo "<option value='$cat->id'";
                                        if ($cat->id == $category_id) echo " selected";
                                        echo ">$cat->name</option>";
                                    }
                                } ?>
                            </select>
                        </td>
                      <td class="col s4">Payment Type<br>
                            <select name="payment_type" class="form-control">
                                <option value="All">All</option>
                                <option value="cash" <?= $payment_type == 'cash' ? 'selected' : '' ?>>Cash</option>
                                <option value="cheque" <?= $payment_type == 'cheque' ? 'selected' : '' ?>>Cheque</option>
                            </select>
                        </td>
                    </tr>
                    
                    <tr>
                        <td colspan="2" class="col s12">
                            <button type="submit" class="btn waves-effect waves-light"
                                    style="float:left;">
                                Search
                            </button>
                            <?php if (isset($_GET['view'])) { ?>
                                <button
    onclick="exportTableToCSV('balance_stock_report_data-<?= date('d-m-Y-h-i-a') ?>.csv')"
    class="btn waves-effect waves-light"
    style="float:left; margin-left: 15px;">
    Export CSV
</button>

                                <button
                                    id="print"
                                    class="btn waves-effect waves-light"
                                    style="float:left; margin-left: 15px;">
                                    Print
                                </button>
                            <?php } ?>
                        </td>
                    </tr>
                </table>
            </form>
            <hr>
            <?php
            if (isset($_GET['view'])) {
                ?>
                <div id="floatThead" class="section">
                   <table class="striped demo1 bordered" id="balanceStockReport">
                        <thead>
                          <tr>
                            <th>Category</th>
                            <th>Sub-Category</th>
                        <!--    <th style='text-align:right;'>No. of Carton</th> -->
                        <!--    <th style='text-align:right;'>Avg. Rate</th> -->
                            <th style='text-align:right;'>Total Amount</th>
                        </tr>
                        </thead>

 <tbody>
<?php
$grandTotal = 0;

// Sort parent categories by category name
uksort($grouped, function ($a, $b) use ($categoryMap) {
    $nameA = isset($categoryMap[$a]) ? $categoryMap[$a]->name : '';
    $nameB = isset($categoryMap[$b]) ? $categoryMap[$b]->name : '';
    return strcmp($nameA, $nameB);
});

foreach ($grouped as $parentId => $subcats) {
    $parentName = isset($categoryMap[$parentId]) ? $categoryMap[$parentId]->name : 'Uncategorized';
    $parentTotal = 0;
    echo "<tr><td colspan='5' style='font-weight:bold;'>$parentName</td></tr>";

    // Sort subcategories alphabetically
    uksort($subcats, function ($a, $b) use ($categoryMap) {
        $nameA = isset($categoryMap[$a]) ? $categoryMap[$a]->name : '';
        $nameB = isset($categoryMap[$b]) ? $categoryMap[$b]->name : '';
        return strcmp($nameA, $nameB);
    });

    foreach ($subcats as $subId => $entries) {
        $subName = isset($categoryMap[$subId]) ? $categoryMap[$subId]->name : 'Unknown';

        $totalCartons = array_sum(array_map(function ($e) { return $e->carton; }, $entries));
        $averageRate = count($entries) ? array_sum(array_map(function ($e) { return $e->rate; }, $entries)) / count($entries) : 0;
        $subTotal = array_sum(array_map(function ($e) { return $e->amount; }, $entries));

        echo "<tr>
            <td></td>
            <td>$subName</td>
            <td></td>
            <td></td>
            <td style='text-align:right;'>" . number_format($subTotal, 2) . "</td>
        </tr>";

        $parentTotal += $subTotal;
    }

    echo "<tr style='font-weight:bold;'><td colspan='4' style='text-align:right;'>Sub Total --- $parentName</td><td style='text-align:right;'>" . number_format($parentTotal, 2) . "</td></tr>";
    $grandTotal += $parentTotal;
}

echo "<tr style='font-weight:bold; background:#ccc;'><td colspan='4' style='text-align:right;'>Grand Total</td><td style='text-align:right;'>" . number_format($grandTotal, 2) . "</td></tr>";
?>
</tbody>





            
            	   </table>
                </div>
                <?php
            } // close view
            ?>
        </div>
    </div>
</div>

<?php include('../includes/inc_footer.php'); ?>

<script type="text/javascript" src="<?= PROJECT_URL ?>js/download.js"></script>
<?php include('../includes/inc_js.php'); ?>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead.min.js"></script>
<script type="text/javascript" src="<?= PROJECT_URL ?>js/plugins/floatThead/jquery.floatThead-slim.min.js"></script>
<script type="application/javascript">
    $(document).ready(function () {
        $("#print").on("click", function (e) {
            var fewSeconds = 2;
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/tax_expense_report_summary.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, fewSeconds * 1000);
        });
        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });
</script>
  <script type="text/javascript">
    function exportTableToCSV(filename) {
        var csv = [];
        var rows = document.querySelectorAll("table.demo1 tr");

        // Loop through each row in the table
        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");

            // Loop through each column in the row
            for (var j = 0; j < cols.length; j++) {
                // Clean and escape double quotes for CSV compatibility
                var cellValue = cols[j].innerText.trim().replace(/"/g, '""');
                row.push('"' + cellValue + '"');
            }

            // Push the row into the CSV array
            csv.push(row.join(","));
        }

        // Create CSV file and trigger download
        downloadCSV(csv.join("\n"), filename);
    }

    function downloadCSV(csv, filename) {
        var csvFile;
        var downloadLink;

        // Create a Blob from the CSV data
        csvFile = new Blob([csv], {type: "text/csv"});

        // Create a link element for download
        downloadLink = document.createElement("a");

        // Set the download filename
        downloadLink.download = filename;

        // Create a link to the CSV file
        downloadLink.href = window.URL.createObjectURL(csvFile);

        // Hide the download link
        downloadLink.style.display = "none";

        // Append the link to the body
        document.body.appendChild(downloadLink);

        // Automatically click the link to trigger the download
        downloadLink.click();

        // Remove the link from the document after download
        document.body.removeChild(downloadLink);
    }
</script>
  
</body>
</html>
