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

$keyfld = "vouchno";
$party = $_REQUEST["party"];
$rangeFrom = $_REQUEST["rangeFrom"];
$rangeTo = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["isearch"];
$operator = $_REQUEST["ioperator"];
$datams = $_REQUEST["datams"];

$cond = "";
if ($operator == "=") {
    if ($_REQUEST["ifield"] == "1") {
        $cond = "AND `hsncode` = '$searchTerm'";
    } else if ($_REQUEST["ifield"] == "2") {
        $cond = "AND `barcode` = '$searchTerm'";
    } else if ($_REQUEST["ifield"] == "3") {
        $cond = "AND `prodcode` = '$searchTerm'";
    } else if ($_REQUEST["ifield"] == "4") {
        $cond = "AND `gram` = '$searchTerm'";
    } else if ($_REQUEST["ifield"] == "5") {
        $cond = "AND `unit` = '$searchTerm'";
    }
} else {
    if ($_REQUEST["ifield"] == "1") {
        $cond = "AND `hsncode` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["ifield"] == "2") {
        $cond = "AND `barcode` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["ifield"] == "3") {
        $cond = "AND `prodcode` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["ifield"] == "4") {
        $cond = "AND `gram` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["ifield"] == "5") {
        $cond = "AND `unit` LIKE '%$searchTerm%'";
    }
}

$sortcond = "ORDER BY `hsncode`+0";
if ($_REQUEST["sortBy"] == "1") {
    $sortcond = " ORDER BY `hsncode`+0";
} else if ($_REQUEST["sortBy"] == "2") {
    $sortcond = " ORDER BY `barcode`";
} else if ($_REQUEST["sortBy"] == "3") {
    $sortcond = " ORDER BY `prodcode`";
} else if ($_REQUEST["sortBy"] == "4") {
    $sortcond = " ORDER BY `gram`";
} else if ($_REQUEST["sortBy"] == "5") {
    $sortcond = " ORDER BY `unit`";
}

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

if ($datams == "M") {
    $maindb = "matsup";
} elseif ($datams == "S") {
    $maindb = "manservice";
}

$query = "SELECT * FROM `$maindb` WHERE code != '' $cond $sortcond $ordcond LIMIT $rangeFrom, $rangeTo";
$result = mysqli_query($conn, $query)or die(mysqli_error($conn));

$rows = array();
$ctr = 0;
$d1 = $d2 = $d3 = $d4 = 0;
while ($r = mysqli_fetch_assoc($result)) {
    $ra = $r['price'];


    $rows[] = ['success' => true,
        'value' => $ctr,
        'keyfld' => $keyfld,
        'file' => $file,
        'hsncode' => $r['hsncode'],
        'descrip1' => $r['descrip1'],
        'descrip2' => $r['descrip2']
    ];
    $ctr++;
}
header("Content-type: application\json");
echo json_encode($rows);
