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

$keyfld = "paxid";
$rangeFrom = $_REQUEST["rangeFrom"];
$rangeTo = $_REQUEST["rangeTo"];
$searchTerm = $_REQUEST["isearch"];
$operator = $_REQUEST["ioperator"];

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

$sortcond = "ORDER BY `name`";
if ($_REQUEST["sortBy"] == "1") {
    $sortcond = " ORDER BY `name`";
} else if ($_REQUEST["sortBy"] == "2") {
    $sortcond = " ORDER BY `surname`";
} else if ($_REQUEST["sortBy"] == "2") {
    $sortcond = " ORDER BY `mobile`";
}

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

// $query = "SELECT name,fname,surname,midname,accode,mobile,concat(add1, add2,add3) as address,email,city,pin
//           FROM `accmast`  WHERE grpcode = '010' and accode != '' $cond $sortcond $ordcond LIMIT $rangeFrom, $rangeTo";
$query = "SELECT * FROM `pax`  WHERE paxid != '' $cond group by mobile,concat(surname,name,midname)  $sortcond $ordcond LIMIT $rangeFrom, $rangeTo";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));

// print "SELECT * FROM `pax`  WHERE paxid != ''  $cond GROUP BY mobile,concat(surname,name,midname) $sortcond $ordcond LIMIT $rangeFrom, $rangeTo";

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

    if ($r['surname']  ==  "") {
        $fullname = strtoupper($r['name'] . ' ' . $r['midname']);
    } else {
        $fullname = strtoupper($r['surname']  . ' ' . $r['name']  . ' ' . $r['midname']);
    }

    $rows[] = [
        'success' => true,
        'value' => $ctr,
        'keyfld' => $keyfld,
        'fullname' => $fullname,
        'name' => $r['name'],
        'suffix' => $r['suffix'],
        'midname' => $r['midname'],
        'surname' => $r['surname'],
        'gender' => $r['gender'],
        'accode' => $r['accode'],
        'mobile' => $r['mobile'],
        'city' => $r['city'],
        'pin' => $r['pin'],
        'email' => $r['email'],
        'address' => $r['address'],
        'aadhaarno' => $r['aadhaarno'],
        'panno' => $r['panno'],
    ];
    $ctr++;
}
header("Content-type: application\json");
echo json_encode($rows);
