<?php
include("../classes/manager.class.php");
$m = new Manager();
if (!isset($_SESSION['sess_userid'])) {
    echo json_encode(['status' => false, 'msg' => 'Session expired']);
    exit();
}

global $db;

$ingredient_id = isset($_GET['ingredient_id']) ? (int)$_GET['ingredient_id'] : 0;
$purchase_id   = isset($_GET['purchase_id']) ? (int)$_GET['purchase_id'] : 0;

if ($ingredient_id <= 0 || $purchase_id <= 0) {
    echo json_encode(['status' => false, 'msg' => 'Invalid parameters']);
    exit();
}

// Totals from ingredient_stock (your source of truth)
$totalsQ = "
    SELECT
        COALESCE(SUM(reserved_qty),0) AS used_qty,
        COALESCE(SUM(remaining_qty),0) AS remaining_qty
    FROM ingredient_stock
    WHERE ingredient_id = '$ingredient_id'
      AND purchase_id   = '$purchase_id'
";
$totals = $db->query_first($totalsQ);

// Purchased qty + purchase meta
$metaQ = "
    SELECT
        p.create_date AS purchase_date,
        p.code AS purchase_code,
        p.purchase_invoice_no,
        sup.name AS supplier_name,
        pi.qty AS purchased_qty
    FROM purchase_items pi
    INNER JOIN purchase p ON p.id = pi.purchase_id
    LEFT JOIN supplier_setup sup ON sup.id = p.supplier_id
    WHERE pi.purchase_id = '$purchase_id'
      AND pi.ing_id      = '$ingredient_id'
    LIMIT 1
";
$meta = $db->query_first($metaQ);

if (!$meta) {
    echo json_encode(['status' => false, 'msg' => 'Purchase item not found for this ingredient']);
    exit();
}

$used_qty      = isset($totals->used_qty) ? (float)$totals->used_qty : 0.0;
$remaining_qty = isset($totals->remaining_qty) ? (float)$totals->remaining_qty : 0.0;
$purchased_qty = isset($meta->purchased_qty) ? (float)$meta->purchased_qty : 0.0;

// Consumed can be treated as used, but show both-style
$consumed_qty = $purchased_qty - $remaining_qty;
if ($consumed_qty < 0) $consumed_qty = 0;

echo json_encode([
    'status' => true,

    'purchase_date' => !empty($meta->purchase_date) ? date('d-m-Y', strtotime($meta->purchase_date)) : '-',
    'supplier_name' => $meta->supplier_name,
    'purchase_code' => $meta->purchase_code,
    'purchase_invoice_no' => $meta->purchase_invoice_no,

    'purchased_qty' => number_format($purchased_qty, 6, '.', ''),
    'used_qty' => number_format($used_qty, 6, '.', ''),
    'remaining_qty' => number_format($remaining_qty, 6, '.', ''),
    'remaining_qty_raw' => $remaining_qty, // for max attribute
    'consumed_qty' => number_format($consumed_qty, 6, '.', ''),
]);
