<?php
include('includes/config/config.php');
include('includes/auth/auth.php');
include('includes/functions.php');
include('access.php');
include('log_entry.php');
error_reporting(E_ERROR | E_PARSE);
?>
<?php
begin();
// Connect to mysqli database
$page = 1; // The current page
$sortname = 'usage_date'; // Sort column
$sortorder = 'desc'; // Sort order
$qtype = ''; // Search column
$query = ''; // Search string
$searchSql = "";          // Get posted data
if (isset($_POST['page'])) {
	$page = mysqli_real_escape_string($conn, $_POST['page']);
}
if (isset($_POST['sortname'])) {
	$sortname = mysqli_real_escape_string($conn, $_POST['sortname']);
}
if (isset($_POST['sortorder'])) {
	$sortorder = mysqli_real_escape_string($conn, $_POST['sortorder']);
}
if (isset($_POST['qtype'])) {
	$qtype = mysqli_real_escape_string($conn, $_POST['qtype']);
}
if (isset($_POST['query'])) {
	$query = mysqli_real_escape_string($conn, $_POST['query']);
}
if (isset($_POST['rp'])) {
	$rp = mysqli_real_escape_string($conn, $_POST['rp']);
}

$hasReadAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'R');
$hasWriteAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'W');
$hasExecuteAccess = isAccessible($_SESSION['RoleId'], $menu_key, 'E');
if ($qtype == 'ambulance_driver') {
	$get_id = "select s.staff_id from staff_master s left join staff_category_master sc on sc.id=s.staff_category where sc.category_name IN ('DRIVER','driver') and s.staff_name like upper('%" . trim($query) . "%')";
	$result_get = mysqli_query($conn, $get_id);
	$row_get = mysqli_fetch_assoc($result_get);
	$driver_id = $row_get['staff_id'];

	$searchSql =  " where driver_id= $driver_id";
} else if ($qtype == 'ambulance_date') {

	$searchSql = ($qtype != '' && $query != '') ? "where usage_date = STR_TO_DATE('" . trim($query) . "','%d/%m/%Y')" : '';
} else if ($qtype == 'ambulance_date_between') {
	$dates = explode("-", $query);
	$searchSql = " where usage_date between str_to_date('" . trim($dates[0]) . "','%d/%m/%Y') and  str_to_date('" . trim($dates[1]) . "','%d/%m/%Y') ";
} else if ($qtype == 'ambulance_from') {
	$searchSql = ($qtype != '' && $query != '') ? "where upper($qtype) like upper('%" . trim($query) . "%')" : '';
} else if ($qtype == 'ambulance_to') {
	$searchSql = ($qtype != '' && $query != '') ? "where upper($qtype) like upper('%" . trim($query) . "%')" : '';
} else if ($qtype == 'ambulance_used') {
	$get_id = "select id from patient_master where upper(patient_name) like upper('%" . trim($query) . "%')";
	$result_get = mysqli_query($conn, $get_id);
	$row_get = mysqli_fetch_assoc($result_get);
	$patient_id = $row_get['id'];

	$searchSql =  " where patient_id= $patient_id";
} else if ($qtype == 'ambulance_duty') {
	$get_id = "select duty_id from duty_type_master where upper(duty) like upper('%" . trim($query) . "%')";
	$result_get = mysqli_query($conn, $get_id);
	$row_get = mysqli_fetch_assoc($result_get);
	$duty_id = $row_get['duty_id'];

	$searchSql =  " where duty_type= $duty_id";
} else if ($qtype == 'ambulance_number') {
	$get_id = "select id from ambulance_details_new where ambulance_number = '" . trim($query) . "'";
	$result_get = mysqli_query($conn, $get_id);
	$row_get = mysqli_fetch_assoc($result_get);
	$ambulance_id = $row_get['id'];

	$searchSql = " where ambulance_id= $ambulance_id";
} else {
	$searchSql = ($qtype != '' && $query != '') ? "where upper($qtype) like upper('%" . trim($query) . "%')" : '';
}
//echo $searchSql;
//echo $qtype."  ".$query;
//echo ($qtype != '' && $query != '');

// Setup sort and search SQL using posted data
$sortSql = "order by $sortname $sortorder";


//echo "h".$searchSql;
//$searchSql = preg_replace ( '/and/', 'where', $searchSql, 1 );
// Get total count of records
$sql = "SELECT count(*) from ambulance_usage_details $searchSql";
error_log("nnnnnnnnnnn" . $sql);
//echo $sql;
$result = mysqli_query($conn, $sql);
rollback();
$row = mysqli_fetch_array($result);
$total = $row[0];
error_log("TOTAL " . $total);
if (!isset($rp)) {
	$rp = 10;
}
// Setup paging SQL
// $rp=1;
$pageStart = ($page - 1) * $rp;
$limitSql = "limit $pageStart, $rp";
// Return JSON data
$data = array();
$data['page'] = $page;
$data['total'] = $total;
$data['rows'] = array();
//$sql_ambulance = "SELECT *  FROM ambulance_details    $searchSql $sortSql $limitSql";
$sql_ambulance = "SELECT * FROM ambulance_usage_details $searchSql $sortSql $limitSql";
$sql_export = $sql_ambulance;
//echo $sql_ambulance;
$results_ambulance = mysqli_query($conn, $sql_ambulance);
error_log("nnnnnnnnnnn" . $sql_ambulance);
rollback();
$count = ($page - 1) * $rp + 1;
// echo $sql_ailment;
// echo $access_level;

while ($row1 = mysqli_fetch_assoc($results_ambulance)) {
	//     error_log("Row " . $row1);
	$ambulance_id = $row1['ambulance_usage_id'];

	// echo $Department_id;
	$view_link = "";
	$edit_link = "";
	$delete_link = "";
	$links = "";
	if ($hasReadAccess) {
		// echo "shubham";
		//$view_link = "<a  href=\"#\"class=\"green\"  onclick=\"open_ambulance_form('".$ambulance_id."','V');\"><i class=\"ace-icon fa fa-search-plus bigger-130\"></i></a>";
	}

	if ($hasWriteAccess) {
		$edit_link = "<a href=\"#\" class=\"blue\" onclick=\"open_ambulance_form('" . $ambulance_id . "','E');\"><i class=\"ace-icon fa fa-pencil bigger-130\"></i></a>";
	}
	if ($hasExecuteAccess) {
		$delete_link = "<a href=\"#\" class=\"blue\" onclick=\"delete_ambulance_form('" . $ambulance_id . "');\"><i class=\"ace-icon fa fa-trash-o bigger-130\"></i></a>";
	}
	$space = "&nbsp;&nbsp;&nbsp;";
	$links = $assign_link . $space . $view_link . $space . $edit_link . $space . $delete_link;
	//$waste_category_name = getTableFieldValue ( 'waste_category', 'waste_category_name', 'waste_category_id', $row1['waste_category'] );
	//$ohc_type_name = getTableFieldValue ( 'ohc_type ', 'ohc_type_name', 'ohc_type_id ', $row1['ohc_type_id '] );
	$client_id = getFieldFromTable('client_id', 'patient_master', 'id', $row1['patient_id']);
	$location_id = getFieldFromTable('client_location_id', 'patient_master', 'id', $row1['patient_id']);
	
	
	$paramedic_ids = $row1['paramedic_id'];
    $paramedic_ids_array = array();
    $paramedic_ids_array = explode(",", $paramedic_ids);
    $paramedics = "";
    for ($i = 0; $i < count($paramedic_ids_array); $i++) {
        if ($i == 0) {
            if (is_numeric($paramedic_ids_array[$i])) {
                $paramedics = getTableFieldValue('staff_master', 'staff_name', 'staff_id', $paramedic_ids_array[$i]);
            } else {
                $paramedics = $paramedic_ids_array[$i];
            }
        } else {
            if (is_numeric($paramedic_ids_array[$i])) {
                $paramedics = $paramedics . "," . getTableFieldValue('staff_master', 'staff_name', 'staff_id', $paramedic_ids_array[$i]);
            } else {
                $paramedics = $paramedics . "," . $paramedic_ids_array[$i];
            }
        }
    }
   
	$data['rows'][] = array(
		'id' => $row1['ambulance_usage_id'],
		'cell' => array(
			$count++,
			$links,

			date_format(date_create($row1['usage_date']), "d-m-Y"),
			getTableFieldValue('ambulance_details_new', 'ambulance_number', 'id', $row1['ambulance_id']),
			getTableFieldValue('staff_master', 'staff_name', 'staff_id', $row1['driver_id']),
			$paramedics,
			getTableFieldValue('patient_master', 'patient_name', 'id', $row1['patient_id']),
			getFieldFromTable('client_name', 'client_master', 'id', $client_id),
			getFieldFromTable('client_location', 'client_location', 'client_location_id', $location_id),
			getTableFieldValue('duty_type_master', "CONCAT(duty,' ( ' , duty_code , ' ) ')", 'duty_id', $row1['duty_type']),
			$row1['ambulance_from'],
			$row1['ambulance_to'],
		)
	);
}

commit();
$data['rows'][] = array(
	'id' => $row['filterkey'],
	'cell' => array('', "<input type=hidden name='filterkey' id='filterkey' value=\"" . base64_encode($sql_export) . "\">", "<input type=hidden name=paramlist id=paramlist value=\"" . ($qtype . ':' . $sql_export) . "\">", '',  '', '', '', '', '', '',  '', '', '', '', '', '', '', '', '', '')
);
echo json_encode($data);
?>