<?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];
$fseries = $_SESSION["society_" . $dbname];
$success = false;

$file = "bankrecp.php";

$keyfld = "vouchno";
$rangeFrom = $_REQUEST["rangeFrom"];
$rangeTo = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["crsearch"];
$operator = $_REQUEST["croperator"];

$cond = "";
if ($operator == "=") {
    if ($_REQUEST["crfield"] == "1") {
        $cond = "AND `vouchno` = '$searchTerm'";
    } elseif ($_REQUEST["crfield"] == "2") {
        $cond = "AND `bankcode` = '$searchTerm'";
    } else if ($_REQUEST["crfield"] == "3") {
        $cond = "AND `chqdate` = '$searchTerm'";
    } else if ($_REQUEST["crfield"] == "4") {
        $cond = "AND `drawbank` = '$searchTerm'";
    } else if ($_REQUEST["crfield"] == "5") {
        $cond = "AND `accode` = '$searchTerm'";
    } 
} else {
    if ($_REQUEST["crfield"] == "1") {
        $cond = "AND `vouchno` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["crfield"] == "2") {
        $cond = "AND `bankcode` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["crfield"] == "3") {
        $cond = "AND `chqdate` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["crfield"] == "4") {
        $cond = "AND `drawbank` LIKE '%$searchTerm%'";
    } else if ($_REQUEST["crfield"] == "5") {
        $cond = "AND `accode` LIKE '%$searchTerm%'";
    } 
}

$query = "SELECT a.`name`, b.vouchno, b.`accode`, b.`bankcode`, b.`chqdate`, b.`drawbank`, FROM "
        . "`accmast` a, `bankrecp` b WHERE a.`accode` = b.`accode` and a.series = '$fseries' and a.series = b.series $cond ORDER BY `vouchno` DESC LIMIT $rangeFrom, $rangeTo";
$result = mysqli_query($conn, $query)or die(mysqli_error($conn));

$rows = array();
$ctr = 0;
while ($r = mysqli_fetch_assoc($result)) {
    $gbank = mysqli_query($conn, "SELECT `name` AS bankname FROM `accmast` WHERE  `name`= $r[bankcode] AND `grpcode`='002'") or die(mysqli_error($conn));
    $bank = mysqli_fetch_array($gbank);

    $rows[] = [ 'success' => true,
        'value' => $ctr,
        'keyfld' => $keyfld,
        'vouchno' => $r[vouchno],
        'bankcode' => $bank[bankcode],
        'chqdate' => $r[chqdate],
        'drawbank' => $r[drawbank],
        'accode' => $r[accode],
        'action' => "$file?mode=edit&accode=$r[vouchno]",
    ];
    $ctr++;
}

header("Content-type: application\json");
echo json_encode($rows);
