<?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;
$fseries = $_SESSION["series_" . $dbname];

// mysqli_query($conn, "Create temporary table `stkdb` SELECT sum(qty) as tqty,itemcode FROM `transacn` $keycond group by itemcode,series")or die(mysqli_error($conn));

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

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

    $query = "SELECT * FROM `product` WHERE code!='' $cond";

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

    $rows = array();
    $ctr = 0;
    $r = mysqli_fetch_assoc($result);
   
    $stqty = 0;

    // $getm = mysqli_query($conn, "SELECT tqty FROM `stkdb` WHERE itemcode = '$r[code]'")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;
    // }

    $rows = array('success' => true,
        'cost' => "$r[cost]",
        'rate' => "$r[rate]",
        'cartqty' => "$r[cartqty]",
        'loosepairs' => "$r[loosepairs]",
        'stkqty' => "$stqty");
    header("Content-type: application\json");
    echo json_encode($rows);
}