<?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;

$barcode = $_REQUEST["barcode"];
$itemcode = $_REQUEST["itemcode"];
$file = $_REQUEST["file"];
$godown = $_REQUEST["godown"];
$godowncond = "";
if ($godown) {
    $godowncond = " and godown='$godown'";
}
if ($file == 'sale.php' || $file == 'saleret.php' || $file == 'damaged.php') {
    $rate = "rate";
} else {
    $rate = "cost";
}

if (isset($barcode) != "") {

    $party = $_REQUEST["party"];

    $query = "SELECT *, `$rate` as price FROM `product` WHERE barcode='$barcode'";
    $result = mysqli_query($conn, $query)or die(mysqli_error($conn));

    $r = mysqli_fetch_assoc($result);
    $n = mysqli_num_rows($result);

    $getm = mysqli_query($conn, "SELECT sum(qty) as tqty FROM `transacn` WHERE `barcode`='$r[barcode]' $godowncond")or die(mysqli_error($conn));
    if (!empty($getm)) {
        $m = mysqli_fetch_array($getm);
        $stkqty = $m['tqty'];
        if ($stkqty != 0) {
            $stqty = $stkqty;
        } else {
            $stqty = 0;
        }
    } else {
        $stqty = 0;
    }

//    $mrate = mysqli_query($conn, "SELECT `rate` FROM `product`  WHERE barcode='$barcode'") or die(mysqli_error($conn));
//    $frate = mysqli_fetch_array($mrate);

    $ra = $r['price'];

    $rows = array('success' => $success,
        'name' => $r['name'],
        'barcode' => $r['barcode'],
        'itemcode' => $r['prodcode'],
        'gram' => $r['gram'],
        'unit' => $r['unit'],
        'cartqty' => $r['cartqty'],
        'rate' => $ra,
        'stk' => $stqty,
        'hsncode' => $r['hsncode'],
        'mrp' => $r['mrp'],
        'gstperc' => $r['gstperc']
    );
    header("Content-type: application\json");
    echo json_encode($rows);
}