<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
mysqli_select_db($conn, $zdb);
$admin = $_SESSION["admin_" . $dbname];
$success = false;


if (isset($_REQUEST["itemname"])) {
    $itemname = $_REQUEST['itemname'];
    $colrcode = $_REQUEST['color'];

    $cond = "";
    if (!empty($itemname)) {
        $cond = " AND `code` ='$itemname' ";
    }

    $query = "SELECT `rate`, `unit`, `mrp`, `msp`, `hsncode` FROM `item` WHERE code!='' $cond";

    $result = mysqli_query($conn, $query)or die(mysqli_error($conn));

    $r = mysqli_fetch_assoc($result);
    $getm = mysqli_query($conn, "SELECT sum(qty) as tqty FROM `transacn` WHERE `itemcode`='$itemname' and color = '$colrcode'")or die(mysqli_error($conn));
//    print table($getm);
    if (!empty($getm)) {
        $m = mysqli_fetch_array($getm);
        $stkqty = $m['tqty'];
        if ($stkqty != 0) {
            $stqty = $stkqty;
        } else {
            $stqty = 0;
        }
    } else {
        $stqty = 0;
    }


    $rows = array();
    $ctr = 0;
//    $r = mysqli_fetch_assoc($result);
    $getunit = mysqli_query($conn, "SELECT `code`, `name` FROM `unit` WHERE code='$r[unit]'")or die(mysqli_error($conn));
    $fetunit = mysqli_fetch_array($getunit);

    $rows = array('success' => true,
        'rate' => "$r[rate]",
        'unit' => "$fetunit[name]",
        'mrp' => "$r[mrp]",
        'stqty' => "$stqty",
        'hsncode' => "$r[hsncode]",
        'msp' => "$r[msp]");
    header("Content-type: application\json");
    echo json_encode($rows);
}