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

$file = 'purchasegst.php';

//$keyfld = "vouchno";
//$rangeFrom = $_REQUEST["rangeFrom"];
//$rangeTo = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["ssearch"];
$operator = $_REQUEST["soperator"];

$cond = "";
if ($_REQUEST["sfield"] != "") {
    if ($operator == "=") {
         if ($_REQUEST["sfield"] == "1") {
            $cond = "AND `barcode` = '$searchTerm'";
        } 
    } else {
         if ($_REQUEST["sfield"] == "1") {
            $cond = "AND `barcode`  LIKE '%$searchTerm%'";
        }
    }
}


//$sortcond = "ORDER BY `vouchno`+0";
if ($_REQUEST["sortBy"] == "1") {
    $sortcond = " ORDER BY `barcode`";
}

$ordcond = "DESC";
if ($_REQUEST["orderAs"] == "desc") {
    $ordcond = " DESC";
}else{
    $ordcond = " ASC";
}

$brand      = $_REQUEST["brand"];
$itemgrp    = $_REQUEST["itemgrp"];

if ($brand != "") {
    $grpcond = "";
    if($itemgrp !=""){
        $grpcond = " AND `itemgrp`='$itemgrp'";
    }
    
    $query = "SELECT * FROM `item` WHERE `brand`='$brand' $cond $grpcond  ORDER BY `code`  $ordcond";
    $result = mysqli_query($conn, $query)or die(mysqli_error($conn));
    

$rows = array();
$ctr = 1;
while ($r = mysqli_fetch_assoc($result)) {
    

         $rows[] = [ 'success' => $success,
            'ctr' => $ctr,
            'code' => $r[code],
            'barcode' => $r[barcode],
            'name' => $r[name],
            'brand' => $r[brand],
            'size' => $r[size],
            'colour' => $r[colour],
            'bdp' => $r[purrate],
            'vat' => $r[vat],
            'gstamt' => $r[gstamt],
            'gstperc' => $r[gstperc],
            'margperc' => $r[margperc],
            'margamt' => $r[margamt],
            'taxval' => $r[taxval],
            'miscamt' => $r[misc],
            'miscperc' => $r[miscperc],
            'cost' => $r[cost],
            'mrp' => $r[mrp]
        ];
        $ctr++;
}
header("Content-type: application\json");
echo json_encode($rows);
}