<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$supplier_id = "";
$ingredient_id = "";

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

$filterReport = "";

// Apply supplier filter if specified
if (isset($supplier_id) && $supplier_id != 'All') {
    $filterReport .= " AND p.supplier_id = '$supplier_id'";
}

// Apply ingredient filter if specified
if (isset($ingredient_id) && $ingredient_id != 'All') {
    $filterReport .= " AND i.ingredient_id = '$ingredient_id'";
}
// At this point, the $filterReport is ready to be passed into the method
$data = IngredientStock::GetBalanceStockReport($filterReport);

?>
<!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>Balance Stock Report (Raw Material)</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" style="display:none;">Date From<br>
                          <input type="text" name="datefrom" id="datepicker"
                                 placeholder="Date From"
                                 value="<?= $datefrom ?>" class="form-control" style="display:none;"/>
                          <input type="hidden" name="view" id="view" class="form-control"/>
                      </td>
                      <td class="col s6" style="display:none;">Date To<br>
                          <input type="text" name="dateto" id="datepicker1"
                                 placeholder="Date To"
                                 value="<?= $dateto ?>" class="form-control" style="display:none;"/>
                      </td>
                  </tr>

                    <tr>
                        <td class="col s6">Supplier<br>
                            <?php
                            // Fetch suppliers from your SupplierSetup table
                            $suppliers = SupplierSetup::GetSupplierSetupList();
                            ?>
                            <select class="form-control" required id="supplier_id"
                                    name="supplier_id">
                                <option>All</option>
                                <?php
                                if ($suppliers) {
                                    foreach ($suppliers as $supplier) {
                                        echo '<option ';
                                        if ($supplier->id == $supplier_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $supplier->id . '" >' . $supplier->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </td>
                        <td class="col s6">Ingredient<br>
                            <?php
                            // Fetch ingredients from your IngredientSetup table
                            $ingredients = IngSetup::GetIngSetupList();
                            ?>
                            <select class="form-control" required id="ingredient_id"
                                    name="ingredient_id">
                                <option>All</option>
                                <?php
                                if ($ingredients) {
                                    foreach ($ingredients as $ingredient) {
                                        echo '<option ';
                                        if ($ingredient->id == $ingredient_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' . $ingredient->id . '" >' . $ingredient->name . '</option>';
                                    }
                                }
                                ?>
                            </select><br/>
                        </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 style="border: 1px solid #666;">
                            <th>Receiving Date</th>
                            <th>Reference Number</th>
                            <th>Supplier</th>
                            <th>Item Name</th>
                            <th style="text-align: right;">Receiving Quantity</th>
                            <th style="text-align: right;">Balance Quantity</th>
                            <th style="text-align: right;">Price Per Kg</th>
                            <th style="text-align: right;">Amount</th>
                            <th style="text-align: right;">Sales Tax %</th>
                            <th style="text-align: right;">Sales Tax Amount</th>
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                        if ($data) {
                            $currentItem = null;
                            $groupTotals = [
                                'receiving_quantity' => 0,
                                'balance_quantity' => 0,
                                'amount' => 0,
                                'sales_tax_amount' => 0
                            ];

                            $grandTotals = [
                                'receiving_quantity' => 0,
                                'balance_quantity' => 0,
                                'amount' => 0,
                                'sales_tax_amount' => 0
                            ];

                            foreach ($data as $row) {
                                if ($supplier_id == 'All' && $ingredient_id == 'All') {
                                    // For "All" supplier and ingredient, group by item name
                                    if ($currentItem !== $row->item_name) {
                                        if ($currentItem !== null) {
                                            // Print totals for the previous group
                                            echo "<tr style='font-weight: bold; background-color: #f2f2f2;'>
                                                    <td></td> <!-- Empty cell for 1st column -->
                                                    <td></td> <!-- Empty cell for 2nd column -->
                                                    <td></td> <!-- Empty cell for 3rd column -->
                                                    <td style='text-align: left;'>Total for {$currentItem}</td> <!-- Total label in the 4th column -->
                                                    <td style='text-align: right;'>" . number_format($groupTotals['receiving_quantity'], 2) . "</td>
                                                    <td style='text-align: right;'>" . number_format($groupTotals['balance_quantity'], 2) . "</td>
                                                    <td></td>
                                                    <td style='text-align: right;'>" . number_format($groupTotals['amount'], 2) . "</td>
                                                    <td></td>
                                                    <td style='text-align: right;'>" . number_format($groupTotals['sales_tax_amount'], 2) . "</td>
                                                  </tr>";

                                            // Reset the totals for the new group
                                            $groupTotals = [
                                                'receiving_quantity' => 0,
                                                'balance_quantity' => 0,
                                                'amount' => 0,
                                                'sales_tax_amount' => 0
                                            ];
                                        }
                                        $currentItem = $row->item_name;
                                    }
                                }

                                // Calculate amount and sales tax
                                $amount = $row->price_per_kg * $row->balance_quantity;
                                $salesTaxAmount = ($amount * $row->s_tax_rate) / 100;

                                // Display row data
                                echo "<tr>
                                        <td>" . date('d-m-Y', strtotime($row->receiving_date)) . "</td>
                                        <td>{$row->purchase_invoice_no}</td>
                                        <td>{$row->supplier_name}</td>
                                        <td>{$row->item_name}</td>
                                        <td style='text-align: right;'>" . number_format($row->receiving_quantity, 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($row->balance_quantity, 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($row->price_per_kg, 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($amount, 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($row->s_tax_rate, 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($salesTaxAmount, 2) . "</td>
                                      </tr>";

                                // Update group and grand totals
                                $groupTotals['receiving_quantity'] += $row->receiving_quantity;
                                $groupTotals['balance_quantity'] += $row->balance_quantity;
                                $groupTotals['amount'] += $amount;
                                $groupTotals['sales_tax_amount'] += $salesTaxAmount;

                                $grandTotals['receiving_quantity'] += $row->receiving_quantity;
                                $grandTotals['balance_quantity'] += $row->balance_quantity;
                                $grandTotals['amount'] += $amount;
                                $grandTotals['sales_tax_amount'] += $salesTaxAmount;
                            }

                            // Print totals for the last group if 'All'
                            if ($supplier_id == 'All' && $ingredient_id == 'All') {
                                echo "<tr style='font-weight: bold; background-color: #f2f2f2;'>
                                        <td></td> <!-- Empty cell for 1st column -->
                                        <td></td> <!-- Empty cell for 2nd column -->
                                        <td></td> <!-- Empty cell for 3rd column -->
    									<td style='text-align: left;'>Total for {$currentItem}</td> <!-- Total label in the 4th column -->
                                        <td style='text-align: right;'>" . number_format($groupTotals['receiving_quantity'], 2) . "</td>
                                        <td style='text-align: right;'>" . number_format($groupTotals['balance_quantity'], 2) . "</td>
                                        <td></td>
                                        <td style='text-align: right;'>" . number_format($groupTotals['amount'], 2) . "</td>
                                        <td></td>
                                        <td style='text-align: right;'>" . number_format($groupTotals['sales_tax_amount'], 2) . "</td>
                                      </tr>";
                            }

                            // Grand totals
                            echo "<tr style='font-weight: bold; background-color: #d3d3d3;'>
                                    <td></td> <!-- Empty cell for 1st column -->
                                    <td></td> <!-- Empty cell for 2nd column -->
                                    <td></td> <!-- Empty cell for 3rd column -->
    								<td style='text-align: left;'>Grand Total </td> <!-- Total label in the 4th column -->
                                    <td style='text-align: right;'>" . number_format($grandTotals['receiving_quantity'], 2) . "</td>
                                    <td style='text-align: right;'>" . number_format($grandTotals['balance_quantity'], 2) . "</td>
                                    <td></td>
                                    <td style='text-align: right;'>" . number_format($grandTotals['amount'], 2) . "</td>
                                    <td></td>
                                    <td style='text-align: right;'>" . number_format($grandTotals['sales_tax_amount'], 2) . "</td>
                                  </tr>";
                        } else {
                            echo '<tr><td colspan="10" style="text-align: center;">No data available for the selected filters.</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/balance_stock_report.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");

        // Variable to track if the current row is a total row
        var currentItem = "";

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

            if (cols.length > 0 && cols[3] && cols[3].innerText.trim().startsWith("Total for")) {
                // This is the total row, place "Total for" in the 4th column
                row.push('""', '""', '""'); // Empty for first 3 columns
                row.push('"' + cols[3].innerText.trim().replace(/"/g, '""') + '"'); // "Total for" in 4th column
                for (var j = 4; j < cols.length; j++) {
                    var totalCellValue = cols[j].innerText.trim().replace(/"/g, '""');
                    row.push('"' + totalCellValue + '"'); // Add total values to the respective columns
                }
            } else {
                // For normal rows, include all columns as usual
                for (var j = 0; j < cols.length; j++) {
                    var cellValue = cols[j].innerText.trim().replace(/"/g, '""');
                    row.push('"' + cellValue + '"');
                }
                // Track the current item name (assuming it's in column 3 - "Item Name")
                if (cols[3]) {
                    currentItem = cols[3].innerText.trim();
                }
            }

            // 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>
