<?php
include("../../db.php");
header('Content-Type: application/json');

$session = $_REQUEST['session'];

$status = 0;
$data   = array();
$grandTotal = 0;

if ($session != ''){

    $result = $db->getRows("SELECT id,head,name,quantity,unit,price,amount,location FROM inventory /*WHERE session = '$session'*/");

    if (count($result) > 0) {
        $status = 1;

        $tempArray = array();
        foreach ($result as $item) {
            $resultCount = $db->getVal("SELECT SUM(num_item) FROM faculty_inventory_receipt WHERE inventory_id = '$item[id]' /*AND session = '$session'*/");
            $sold = $db->getVal("SELECT SUM(num_item) FROM inventory_receipt WHERE inventory_id = '$item[id]' /*AND session = '$session'*/");

            $totalQty = 0;
            if ($resultCount > 0){
                $totalQty += $resultCount;
            }

            if ($sold > 0){
                $totalQty += $sold;
            }

            $remainingTemp = $item['quantity'] - $totalQty;
            $item['remaining'] = $remainingTemp;
            $item['allotted_amount'] = $item['price'] * $remainingTemp;

            $grandTotal += $item['price'] * $remainingTemp;

            $item['allotted'] = $totalQty;
            $tempArray[] = $item;
        }

        $data = $tempArray;
    }

}

$headList = array();
$headArray = $db->getRows("SELECT * FROM inventory_names WHERE head_type = 'Head'");
foreach ($headArray as $row) {
    $headList[] = $row['name'];
}

echo json_encode(array("status" => $status, "data" => $data, "head_list" => $headList, "grand_total" => $grandTotal));