<?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"];
$vouchdt = $_REQUEST["vouchdt"];
$file = $_REQUEST["file"];

if ($file == 'sale.php' || $file == 'crednote.php' || $file == 'damaged.php') {
    $rate = "rate";
} else {
    $rate = "cost";
}

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

    $party = $_REQUEST["party"];
    $paras = $_REQUEST["paras"];
    // if($paras != ""){
    $cond = "WHERE barcode='$barcode'";
    // }else{
    //     $cond = "WHERE code='$barcode'";
    // }
//    mysqli_query($conn, "Create temporary table `stktab` SELECT sum(stkqty) as tqty,barcode FROM `transacn` $cond group by barcode") or die(mysqli_error($conn));
    $query = "SELECT *, DATE_ADD('$vouchdt', INTERVAL bbf MONTH) AS expdate FROM `product` $cond";
    $result = mysqli_query($conn, $query) or die(mysqli_error($conn));

    $getm = mysqli_query($conn, "SELECT sum(stkqty) as tqty,barcode FROM `transacn` $cond") or die(mysqli_error($conn));
    if (!empty($getm)) {
        $m = mysqli_fetch_array($getm);
        $stkqty = $m['tqty'];
        if ($stkqty != 0) {
            if ($r['stkunit'] == '1') {
                $stqty = number_format($stkqty / 1000, 3);
            } else {
                $stqty = $stkqty;
            }
            if ($stkqty > 0) {
                $bgcolr = "background-color:#beface;";
            }
            if ($stkqty < 0) {
                $bgcolr = "background-color:lightyellow;color:red";
            }
        } else {
            $stqty = 0;
        }
    } else {
        $stqty = 0;
    }

    $r = mysqli_fetch_assoc($result);
    $n = mysqli_num_rows($result);
//    browse($r['bbf']);
//    browse($vouchdt);
//    $expdate = date("Y-m-d", strtotime("+" . $r['bbf'] . " months", strtotime($vouchdt)));
//    browse($expdate);

    $bbfmon = date("m", strtotime($r['expdate']));
    $bbfyear = date("Y", strtotime($r['expdate']));

//    $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['code'],
        'gram' => $r['gram'],
        'unit' => $r['unit'],
        'type' => $r['type'],
        'unit' => $r['stkunit'],
        'batch' => $r['batch'],
        'stkqty' => "$stkqty",
        'bbfmon' => "$bbfmon",
        'bbfyear' => "$bbfyear",
        'origin' => $r['origin']
    );
    header("Content-type: application\json");
    echo json_encode($rows);
}