<?php
include("../classes/manager.class.php");

$m = new Manager();

if (!isset($_SESSION['sess_userid'])) {
    exit();
}

global $db;

if (!isset($_REQUEST['id'])) exit();
$ingredient_id = (int)$_REQUEST['id'];
if ($ingredient_id <= 0) exit();

/*
  NOTE:
  - If your supplier table name differs, replace supplier_setup accordingly.
*/
$query = "
    SELECT
        s.purchase_id,
        p.code AS purchase_code,
        p.create_date AS receiving_date,
        p.purchase_invoice_no,
        sup.name AS supplier_name,
        SUM(s.remaining_qty) AS remaining_qty
    FROM ingredient_stock s
    INNER JOIN purchase p ON p.id = s.purchase_id
    LEFT JOIN supplier_setup sup ON sup.id = p.supplier_id
    WHERE s.ingredient_id = '$ingredient_id'
    GROUP BY s.purchase_id
    HAVING SUM(s.remaining_qty) > 0
    ORDER BY p.create_date ASC, s.purchase_id ASC
";

$rows = $db->fetch_all_array($query);
if (!$rows) exit();

foreach ($rows as $r) {
    $pid = (int)$r->purchase_id;
    $rem = (float)$r->remaining_qty;
    $label = $r->purchase_code . " | " . date('d-m-Y', strtotime($r->receiving_date)) . " | " . $r->supplier_name . " | Rem: " . number_format($rem, 6);

    echo '<option value="' . $pid . '">' . htmlspecialchars($label) . '</option>';
}
