<?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($product_id) && $product_id != 'All') {
    $filterReport .= " AND pp.product_id = '$product_id'";
}


// At this point, the $filterReport is ready to be passed into the method
$data = ProductionSetup::GetBalanceStockReportProducts($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 (Finish 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 s12">Select Product<br>
                            <?php
                            // Fetch suppliers from your SupplierSetup table
  							$filter = "ORDER BY name";
                            $products = ProductSetup::GetProductSetupList($filter);
                            ?>
                            <select class="form-control" required id="product_id"
                                    name="product_id">
                                <option>All</option>
                                <?php
                                if ($products) {
                                    foreach ($products as $product) {
                                        echo '<option ';
                                        if ($product->id == $product_id) {
                                            echo 'selected';
                                        }
                                        echo ' value="' .$product->id . '" >' . $product->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>Batch Date</th>
                          <th>Batch Number</th>
                          <th>Item Name</th>
                          <th style="text-align: right;">Produced Quantity</th>
                          <th style="text-align: right;">Produced Cartons</th> <!-- New column for Produced Cartons -->
                          <th style="text-align: right;">Balance Quantity</th>
                          <th style="text-align: right;">Remaining Cartons</th> <!-- New column for Remaining Cartons -->
                          <th style="text-align: right;">Cost Per Unit</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; // To track the current product
    $groupTotals = [ // To track totals for each product group
        'Produced Quantity' => 0,
        'Produced Cartons' => 0,
        'Balance Quantity' => 0,
        'Remaining Cartons' => 0,
        'Amount' => 0,
        'S.Tax Amount' => 0
    ];
    $grandTotals = [ // To track the grand totals
        'Produced Quantity' => 0,
        'Produced Cartons' => 0,
        'Balance Quantity' => 0,
        'Remaining Cartons' => 0,
        'Amount' => 0,
        'S.Tax Amount' => 0
    ];

    foreach ($data as $row) {
        if ($currentItem !== $row->{'Item Name'}) {
            // If moving to a new product group, display totals for the previous group
            if ($currentItem !== null) {
                echo "<tr style='font-weight: bold; background-color: #f2f2f2;'>
                        <td style='text-align: left;'>Total for {$currentItem}</td>
                        <td></td>
                        <td></td>
                        <td style='text-align: right;'>" . number_format($groupTotals['Produced Quantity'], 2) . "</td>
                        <td style='text-align: right;'>" . number_format($groupTotals['Produced Cartons'], 2) . "</td>
                        <td style='text-align: right;'>" . number_format($groupTotals['Balance Quantity'], 2) . "</td>
                        <td style='text-align: right;'>" . number_format($groupTotals['Remaining Cartons'], 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['S.Tax Amount'], 2) . "</td>
                      </tr>";

                // Reset group totals
                $groupTotals = [
                    'Produced Quantity' => 0,
                    'Produced Cartons' => 0,
                    'Balance Quantity' => 0,
                    'Remaining Cartons' => 0,
                    'Amount' => 0,
                    'S.Tax Amount' => 0
                ];
            }
            $currentItem = $row->{'Item Name'}; // Update the current product
        }

        // Add current row's values to group totals
        $groupTotals['Produced Quantity'] += $row->{'Produced Quantity'};
        $groupTotals['Produced Cartons'] += $row->{'Produced Cartons'};
        $groupTotals['Balance Quantity'] += $row->{'Balance Quantity'};
        $groupTotals['Remaining Cartons'] += $row->{'Remaining Cartons'};
        $groupTotals['Amount'] += $row->{'Amount'};
        $groupTotals['S.Tax Amount'] += $row->{'S.Tax Amount'};

        // Add current row's values to grand totals
        $grandTotals['Produced Quantity'] += $row->{'Produced Quantity'};
        $grandTotals['Produced Cartons'] += $row->{'Produced Cartons'};
        $grandTotals['Balance Quantity'] += $row->{'Balance Quantity'};
        $grandTotals['Remaining Cartons'] += $row->{'Remaining Cartons'};
        $grandTotals['Amount'] += $row->{'Amount'};
        $grandTotals['S.Tax Amount'] += $row->{'S.Tax Amount'};

        // Display the current row
        echo "<tr>
                <td>{$row->{'Batch Date'}}</td>
                <td>{$row->{'Batch Number'}}</td>
                <td>{$row->{'Item Name'}}</td>
                <td style='text-align: right;'>" . number_format($row->{'Produced Quantity'}, 2) . "</td>
                <td style='text-align: right;'>" . number_format($row->{'Produced Cartons'}, 2) . "</td>
                <td style='text-align: right;'>" . number_format($row->{'Balance Quantity'}, 2) . "</td>
                <td style='text-align: right;'>" . number_format($row->{'Remaining Cartons'}, 2) . "</td>
                <td style='text-align: right;'>" . number_format($row->{'Cost Per Kg'}, 2) . "</td>
                <td style='text-align: right;'>" . number_format($row->{'Amount'}, 2) . "</td>
                <td style='text-align: right;'>{$row->{'S.Tax Rate %'}}</td>
                <td style='text-align: right;'>" . number_format($row->{'S.Tax Amount'}, 2) . "</td>
              </tr>";
    }

    // Display totals for the last product group
    echo "<tr style='font-weight: bold; background-color: #f2f2f2;'>
            <td style='text-align: left;'>Total for {$currentItem}</td>
            <td></td>
            <td></td>
            <td style='text-align: right;'>" . number_format($groupTotals['Produced Quantity'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($groupTotals['Produced Cartons'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($groupTotals['Balance Quantity'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($groupTotals['Remaining Cartons'], 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['S.Tax Amount'], 2) . "</td>
          </tr>";

    // Display grand totals
    echo "<tr style='font-weight: bold; background-color: #d3d3d3;'>
            <td style='text-align: left;'>Grand Total</td>
            <td></td>
            <td></td>
            <td style='text-align: right;'>" . number_format($grandTotals['Produced Quantity'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($grandTotals['Produced Cartons'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($grandTotals['Balance Quantity'], 2) . "</td>
            <td style='text-align: right;'>" . number_format($grandTotals['Remaining Cartons'], 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['S.Tax Amount'], 2) . "</td>
          </tr>";
} else {
    echo '<tr><td colspan="11" 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/product_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, add empty cells for alignment
            row.push('""', '""', '""'); // Empty for first 3 columns
            row.push('"' + cols[3].innerText.trim().replace(/"/g, '""') + '"'); // "Total for" label
            row.push('""', '""'); // Empty cells to shift totals under correct columns
            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[2]) { // Assuming column 3 is "Item Name"
                currentItem = cols[2].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>
