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

$maindb      = "dept";

$file       = "department.php";

$keyfld     = "vouchno";
$rangeFrom  = $_REQUEST["rangeFrom"];
$rangeTo    = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["dsearch"];
$searchTerm = $_REQUEST["dsearch"];
$operator   = $_REQUEST["doperator"];

$cond = "";
if ($operator == "=") {
    if ($_REQUEST["dfield"] == "1") {
        $cond = "AND `code` = '$searchTerm'";
    } else if ($_REQUEST["dfield"] == "2") {
        $cond = "AND `name` = '$searchTerm'";
    } else if ($_REQUEST["dfield"] == "3") {
        $cond = "AND `add1` = '$searchTerm'";
    } else if ($_REQUEST["dfield"] == "4") {
        $cond = "AND `contno` = '$searchTerm'";
    } else if ($_REQUEST["dfield"] == "5") {
        $cond = "AND `incharge` = '$searchTerm'";
    } 
} else {
    if ($_REQUEST["dfield"] == "1") {
        $cond = "AND `code` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["dfield"] == "2") {
        $cond = "AND `name` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["dfield"] == "3") {
        $cond = "AND `add1` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["dfield"] == "4") {
        $cond = "AND `contno` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["dfield"] == "5") {
        $cond = "AND `incharge` LIKE '%$searchTerm%'";
    } 
}

$query = "SELECT  `id`, `code`, `name`, `add1`, `contno`, `incharge` FROM `$maindb` WHERE id != '' $cond ORDER BY `id` DESC LIMIT $rangeFrom, $rangeTo";
$result = mysqli_query($conn, $query)or die(mysqli_error($conn));

$rows = array();
$ctr = 0;
while ($r = mysqli_fetch_assoc($result)) {
    $rows[] = [ 'success'   => true,
                'value'     => $ctr,
                'keyfld'    => $keyfld,
                
                'code'      => $r['code'],
                'name'      => $r['name'],
                'add1'      => $r['add1'],
                'contno'    => $r['contno'],
                'incharge'  => $r['incharge'],
                'action'    => "$file?mode=edit&id=$r[id]",
        ];
    $ctr++;
}
header("Content-type: application\json");
echo json_encode($rows);
