<?php

require("includes/check_auth_user.php");
require("includes/dbconnect.php");
include ('includes/function.php');

$zdb = $_SESSION["zdbyear_" . $dbname];
$admin = $_SESSION["admin_" . $dbname];
//$zroot = $_SESSION["zdir"];
mysqli_select_db($conn, $zdb);
$success = false;
$maindb = 'accmast';
$file = "maintype.php";
$series = $_SESSION["society_" . $dbname];
$keyfld = "accode";
$mgrpcode = '011';
$rangeFrom = $_REQUEST["rangeFrom"];
$rangeTo = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["ssearch"];
//$searchTerm = $_REQUEST["ssearch"];
$operator = $_REQUEST["soperator"];
$keycond = "and series = '$series' and grpcode != '001' and grpcode != '002' and grpcode != '010'
            and grpcode != '012' and grpcode != '051' and grpcode != '050' and `type` = 'I' and init != 'INT'";

$cond = "";
if ($operator == "=") {
    if ($_REQUEST["sfield"] == "1") {
        $cond = "AND `mancode` = '$searchTerm'";
    }
    if ($_REQUEST["sfield"] == "2") {
        $cond = "AND `name` = '$searchTerm'";
    }
    if ($_REQUEST["sfield"] == "3") {
        $cond = "AND `shortname` = '$searchTerm'";
    }
} else {
    if ($_REQUEST["sfield"] == "1") {
        $cond = "AND `mancode` LIKE '%$searchTerm%'";
    }
    if ($_REQUEST["sfield"] == "2") {
        $cond = "AND `name` LIKE '%$searchTerm%'";
    }
    if ($_REQUEST["sfield"] == "3") {
        $cond = "AND `shortname` LIKE '%$searchTerm%'";
    }
}

$sortcond = "ORDER BY `name`";
if ($_REQUEST["sortBy"] == "1") {
    $sortcond = " ORDER BY `mancode`";
}
if ($_REQUEST["sortBy"] == "2") {
    $sortcond = " ORDER BY `name`";
}
if ($_REQUEST["sortBy"] == "3") {
    $sortcond = " ORDER BY `shortname`";
}

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

$query = "SELECT `accode`,`mancode`,`name`, `shortname` FROM `$maindb` WHERE `accode` != '' $keycond $cond $sortcond $ordcond  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],
        'mancode' => $r[mancode],
        'name' => $r[name],
        'shname' => $r[shortname],
        'action' => "$file?mode=edit&series=$series&accode=$r[accode]",
    ];
    $ctr++;
}
header("Content-type: application\json");
echo json_encode($rows);
