<?php
include("../../classes/manager.class.php");
$m = new Manager();
$output = '';
$datefrom = isset($_GET['datefrom']) ? date('Y-m-d', strtotime($_GET['datefrom'])) : date('Y-m-d', strtotime('-30 days'));
$dateto = isset($_GET['dateto']) ? date('Y-m-d', strtotime($_GET['dateto'])) : date('Y-m-d');
$ingredient_id = isset($_GET['ingredient_id']) ? $_GET['ingredient_id'] : 'All';

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

$data = ProductionSetup::GetWastageReport($datefrom, $dateto, $ingredient_id);
$datefromDisplay = date('d-m-Y', strtotime($datefrom));
$datetoDisplay = date('d-m-Y', strtotime($dateto));
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('../includes/inc_head.php'); ?>
</head>
<body>
<div id="container">
    <?php include('../includes/inc_top.php'); ?>
    <div class="row">
        <div class="col s12 m12">
            <h3>Ingredient Wastage Report</h3>
          <script>
                $(function () {
                    $('#datepicker').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true,
                    });
                });
            </script>
            <form method="get" id="searchfrm">
                <div class="row">
                    <div class="input-field col s4">
                        <label for="datepicker">Date From</label><br>
                        <input type="text" name="datefrom" id="datepicker" value="<?= $datefromDisplay ?>" class="datepicker" required>
                    </div>
                    <div class="input-field col s4">
                        <label for="datepicker1">Date To</label><br>
                        <input type="text" name="dateto" id="datepicker1" value="<?= $datetoDisplay ?>" class="datepicker" required>
                    </div>
                    <div class="input-field col s4">
                        <label for="ingredient_id">Ingredient</label><br>
                        <select name="ingredient_id" id="ingredient_id" class="browser-default">
                            <option value="All">All</option>
                            <?php
                            $ingredients = IngSetup::GetIngSetupList(" WHERE status = 'active' ORDER BY name");
                            if ($ingredients) {
                                foreach ($ingredients as $ing) {
                                    $selected = ($ingredient_id == $ing->id) ? 'selected' : '';
                                    echo "<option value='{$ing->id}' {$selected}>{$ing->name}</option>";
                                }
                            }
                            ?>
                        </select>
                    </div>
                </div>
                <div class="row">
                    <div class="input-field col s12">
                        <button type="submit" class="btn waves-effect waves-light">Search</button>
                        <?php if (!empty($data)) { ?>
                            <button onclick="exportTableToCSV('ingredient-wastage-report-<?= date('d-m-Y-h-i-a') ?>.csv')" class="btn waves-effect waves-light" style="margin-left: 15px;">Export CSV</button>
                            <button id="print" class="btn waves-effect waves-light" style="margin-left: 15px;">Print</button>
                        <?php } ?>
                    </div>
                </div>
            </form>

            <hr>
            <?php if (!empty($data)) { ?>
                <div id="floatThead" class="adv-table section">
                    <table class="striped demo1 bordered">
                        <thead>
                <tr style="border: 1px solid #666;">
                    <th>S.No</th>
                    <th>Ingredient Name</th>    
                  <th>Total Consumed</th>
                <!--  <th>Wastage %</th> -->
                  <th>Total Wastage (KG)</th>
                </tr>
            </thead>
            <tbody>
    <?php
    $counter = 1;
    $grandTotalWastage = 0;
    $grandTotalConsumed = 0;

    foreach ($data as $row) {
        $grandTotalWastage += $row->total_wastage;
        $grandTotalConsumed += $row->total_consumed;
    ?>
        <tr style="border: 1px solid #666;">
            <td><?= $counter++ ?></td>
            <td><?= $row->ingredient_name ?></td>
            <td><?= number_format($row->total_consumed, 3) ?></td>
         <!--  <td>13%</td> -->
            <td><?= number_format($row->total_wastage, 3) ?></td>
        </tr>
    <?php } ?>
    <tr>
        
   <!--   <th style="border: 1px solid #000;"></th> -->
      <th style="text-align: right; border: 1px solid #000;">Total</th>
        <th style="border: 1px solid #000;"><?= number_format($grandTotalConsumed, 3) ?></th>
       <th style="border: 1px solid #000;"></th>
        <th style="border: 1px solid #000;"><?= number_format($grandTotalWastage, 3) ?></th>
    </tr>
</tbody>
                    </table>
                </div>
            <?php } else { ?>
                <div class="card-panel yellow lighten-4">
                    <strong>No data found for selected filters.</strong>
                </div>
            <?php } ?>
        </div>
    </div>
</div>
<?php include('../includes/inc_footer.php'); ?>
<?php include('../includes/inc_js.php'); ?>
<script>
    $(function () {
        $('.datepicker').pickadate({
            format: 'dd-mm-yyyy',
            selectMonths: true,
            selectYears: true
        });

        $('#print').on('click', function (e) {
            e.preventDefault();
            $('#searchfrm').prop('target', '_blank');
            $('#searchfrm').prop('action', "<?=PROJECT_ADMIN_URL?>report/print/ingredient_wastage_report.php?").submit();
            setTimeout(function () {
                $('#searchfrm').prop('target', "");
                $('#searchfrm').prop('action', "");
            }, 2000);
        });

        $('table.demo1').floatThead({
            position: 'fixed',
            scrollingTop: 65
        });
        $('table.demo1 thead').css('background', '#ECEFF1');
    });

    function exportTableToCSV(filename) {
        var csv = [];
        var rows = document.querySelectorAll("table.demo1 tr");

        for (var i = 0; i < rows.length; i++) {
            var row = [], cols = rows[i].querySelectorAll("td, th");
            for (var j = 0; j < cols.length; j++) {
                var cellValue = cols[j].innerText.trim().replace(/"/g, '""');
                row.push('"' + cellValue + '"');
            }
            csv.push(row.join(","));
        }
        downloadCSV(csv.join("\n"), filename);
    }

    function downloadCSV(csv, filename) {
        var csvFile = new Blob([csv], { type: "text/csv" });
        var downloadLink = document.createElement("a");
        downloadLink.download = filename;
        downloadLink.href = window.URL.createObjectURL(csvFile);
        downloadLink.style.display = "none";
        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
    }
</script>
</body>
</html>
