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

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

global $db;
extract($_REQUEST);

// Default date range
if (!isset($datefrom) || $datefrom == "") {
    $datefrom = date('Y-m-d', strtotime("-90 days"));
} else {
    $datefrom = date("Y-m-d", strtotime($datefrom));
}

if (!isset($dateto) || $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));

$supplier_id = isset($_GET['supplier_id']) ? $_GET['supplier_id'] : "All";

// Filter like your purchase view
$filter = " WHERE DATE_FORMAT(isa.adjustment_date,'%Y-%m-%d') >= '$qryDate'
            AND DATE_FORMAT(isa.adjustment_date,'%Y-%m-%d') <= '$qryTo' ";

if (!empty($supplier_id) && $supplier_id !== "All") {
    $supplier_id = (int)$supplier_id;
    $filter .= " AND p.supplier_id = '$supplier_id' ";
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <?php include('includes/inc_head.php'); ?>
    <style>
        table { font-size:18px; }
    </style>
</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 Stock Adjustment</h3>
            </div>
            <hr>

            <script>
                $(function () {
                    $('#datepicker1').pickadate({
                        format: 'dd-mm-yyyy',
                        selectMonths: true,
                        selectYears: true
                    });
                    $('#datepicker2').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 l4">Date From<br>
                            <input type="text" name="datefrom" id="datepicker1"
                                   placeholder="Date From"
                                   value="<?= $datefrom ?>" class="datepicker form-control"/>
                            <input type="hidden" name="view" id="view" class="form-control" value="1"/>
                        </td>

                        <td class="col l4"> Date To<br>
                            <input type="text" name="dateto" id="datepicker2"
                                   placeholder="Date To"
                                   value="<?= $dateto ?>" class="datepicker form-control"/>
                        </td>

                        <td class="col s4">Supplier<br>
                            <?php
                            // Same supplier dropdown pattern as your purchase view
                            $suppliers = SupplierSetup::GetSupplierSetupList(); // change if your class name differs
                            ?>
                            <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 l4">&nbsp;<br>
                            <button type="submit" class="btn waves-effect waves-light" style="float:left;">
                                Search
                            </button>
                        </td>
                    </tr>
                </table>
            </form>

            <hr>

            <a class="btn waves-effect waves-light" style="float:right;margin-left:5px;"
               href="ingredient_stock_adjustment_setup.php">
                Add <i class="mdi-content-add-box"></i>
            </a>
            <div class="clearfix"></div>

            <br/>

            <div class="table-datatables">
                <table id="data-table-tandard" class="responsive-table display">
                    <thead>
                    <tr>
                        <th>Code</th>
                        <th>Date</th>
                        <th>Ingredient</th>
                        <th>Purchase Code</th>
                        <th>Supplier</th>
                        <th style="text-align:right;">Deduct Qty</th>
                        <th style="text-align:right;">Before Rem</th>
                        <th style="text-align:right;">After Rem</th>
                        <th>Reason</th>
                        <th>Status</th>
                    </tr>
                    </thead>

                    <tfoot>
                    <tr>
                        <th>Code</th>
                        <th>Date</th>
                        <th>Ingredient</th>
                        <th>Purchase Code</th>
                        <th>Supplier</th>
                        <th style="text-align:right;">Deduct Qty</th>
                        <th style="text-align:right;">Before Rem</th>
                        <th style="text-align:right;">After Rem</th>
                        <th>Reason</th>
                        <th>Status</th>
                    </tr>
                    </tfoot>

                    <tbody>
                    <?php
                    $query = "
                        SELECT
                            isa.code,
                            isa.adjustment_date,
                            isa.deduct_qty,
                            isa.before_remaining_qty,
                            isa.after_remaining_qty,
                            isa.reason,
                            isa.status,

                            p.code AS purchase_code,
                            sup.name AS supplier_name,

                            ing.name AS ingredient_name,
                            ing.description AS ingredient_desc

                        FROM ingredient_stock_adjustment isa
                        LEFT JOIN purchase p ON p.id = isa.purchase_id
                        LEFT JOIN supplier_setup sup ON sup.id = p.supplier_id
                        LEFT JOIN ingredients ing ON ing.id = isa.ingredient_id
                        $filter
                        ORDER BY isa.id DESC
                    ";

                    $rows = $db->fetch_all_array($query);

                    if ($rows) {
                        foreach ($rows as $r) {
                            ?>
                            <tr>
                                <td><?= htmlspecialchars($r->code ?? '') ?></td>
                                <td><?= !empty($r->adjustment_date) ? date('d-m-Y', strtotime($r->adjustment_date)) : '' ?></td>
                                <td><?= htmlspecialchars(($r->ingredient_name ?? '') . ' - ' . ($r->ingredient_desc ?? '')) ?></td>
                                <td><?= htmlspecialchars($r->purchase_code ?? '') ?></td>
                                <td><?= htmlspecialchars($r->supplier_name ?? '') ?></td>
                                <td style="text-align:right;"><?= number_format((float)($r->deduct_qty ?? 0), 6) ?></td>
                                <td style="text-align:right;"><?= number_format((float)($r->before_remaining_qty ?? 0), 6) ?></td>
                                <td style="text-align:right;"><?= number_format((float)($r->after_remaining_qty ?? 0), 6) ?></td>
                                <td><?= htmlspecialchars($r->reason ?? '') ?></td>
                                <td><?= htmlspecialchars($r->status ?? '') ?></td>
                            </tr>
                            <?php
                        }
                    }
                    ?>
                    </tbody>
                </table>
            </div>

        </div>
    </div>
</div>

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

<script type="application/javascript">
    $(document).ready(function () {
        if ($.fn.DataTable.isDataTable('#data-table-tandard')) {
            $('#data-table-tandard').DataTable().destroy();
        }
        $('#data-table-tandard').DataTable({
            "ordering": false
        });
    });
</script>

</body>
</html>
