<?php
include("../../classes/manager.class.php");
//ini_set('display_errors', 1);
//error_reporting(E_ALL);
$m = new Manager();
$output = '';
$datefrom = "";
$dateto = "";
$cat_name = "";
$productQtyTotal = 0;
if (!isset($_SESSION['sess_userid'])) {
    header("Location: " . PROJECT_ADMIN_URL);
    exit();
}
extract($_REQUEST);


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

$qryDate = date("Y-m-d", strtotime($datefrom));
$qryTo = date("Y-m-d", strtotime($dateto));
$filterReport = "WHERE DATE_FORMAT(bt.reserved_on,'%Y-%m-%d')>='$qryDate' and DATE_FORMAT(bt.reserved_on,'%Y-%m-%d')<='$qryTo'";


?>
<!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>Ingredient Usage 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>
                   
                    <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('ingredient-usage-report-<?= 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">
                        <thead>
                        <tr style="border: 1px solid #666;">
                            <th>S.No</th>
                            <th>Ingredients</th>
                            <th style="text-align: right;">Used Quantity</th>
                          	<th style="text-align: right;">Value Exclusive STax</th>
                          	<th style="text-align: right;">Sales Tax Amount</th>                          
                          	<th style="text-align: right;">Cost Including STax</th>
                         
                        </tr>
                        </thead>
                        <tbody>
                        <?php
                      
              			$ingredientReport = IngredientStock::GetIngredientUsageReport($filterReport);
              			
              			// Initialize totals
                            $totalUsedQuantity = 0;
                            $totalValueExclusiveSTax = 0;
                            $totalSalesTaxAmount = 0;
                            $totalCostIncludingSTax = 0;
            
                        if ($ingredientReport) {
                            $counter = 0;
                          
                            foreach ($ingredientReport as $row) {
                                $counter++;
                              
                              // Add to totals
                                $totalUsedQuantity += $row->total_used_quantity;
                                $totalValueExclusiveSTax += $row->total_price;
                                $totalSalesTaxAmount += ($row->total_price_after_tax - $row->total_price);
                                $totalCostIncludingSTax += $row->total_price_after_tax;
                              
                                ?>
                                <tr style="border: 1px solid #666;">
                                    
                                   
                                    <td><?php echo $counter; ?></td>
                                    <td><?php echo $row->ingredient_name; ?></td>
                                    <td style="text-align: right;"><?php echo number_format($row->total_used_quantity, 2); ?></td>
                                   <td style="text-align: right;"><?php echo number_format($row->total_price, 2); ?></td>
                                 
                                   <td style="text-align: right;"><?php echo number_format(($row->total_price_after_tax - $row->total_price), 2); ?></td>
                                   <td style="text-align: right;"><?php echo number_format($row->total_price_after_tax, 2); ?></td>
                                  
                                </tr>
                                <?php
                            }
                        } ?>
                        
                  
                        </tbody>
                      <tfoot>
                      <tr style="border: 1px solid #666; font-weight: bold;">
                          <td colspan="2" style="text-align: right;">Totals:</td>
                          <td style="text-align: right;"><?php echo number_format($totalUsedQuantity, 2); ?></td>
                          <td style="text-align: right;"><?php echo number_format($totalValueExclusiveSTax, 2); ?></td>
                          <td style="text-align: right;"><?php echo number_format($totalSalesTaxAmount, 2); ?></td>
                          <td style="text-align: right;"><?php echo number_format($totalCostIncludingSTax, 2); ?></td>
                      </tr>
                      </tfoot>
                    </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/ingredientusage.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');

        $('#customer_name').material_select();

        $('#customer_name').on('contentChanged', function () {
            $(this).material_select();
        });

        $('#cat_name').on("change", function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersMulti.php?id=' + $(this).val(), function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        });

        $('#e9').on("change", function () {
            $('body.container').block({message: 'Loading...'});
            $.get('getFilterCustomersMulti.php?id=' + $(this).val(), function (data) {
                $("#customer_name").empty();
                $("#customer_name").append(data);
                $('body.container').unblock();
                $('#customer_name').trigger('contentChanged');
            });
        });
        <?php if(empty($cat_name) || $cat_name[0] == "All"){ ?>
        $("#e9 option").eq(0).attr("selected", true);
        <?php }else{?>
        var selectedOptions=[
            '<?=$cat_nameString?>'
        ];
        $.each(selectedOptions, function(i,e){
            //alert($("#e9 :selected").eq(i).val());
            $("#e9 option[value='" + e + "']").prop("selected", true);
        });
        <?php }?>
    });
</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>