<?php
include("../inc/config.php");
include("../inc/functions.php");
session_start();


$allPermissions = get_permissions($pdo,$sessionUserId);
$clientId=$_SESSION['user']['id'];
$clientType=$_SESSION['user']['role'];
$vehicle_tracking_branch_id=$_SESSION['user']['vehicle_tracking_branch_id'];


$requestData= $_REQUEST;
//$clientType=$_REQUEST['client_type'];
$del=$_REQUEST['del'];
$edit=$_REQUEST['edit'];

$f_date=$_REQUEST['from_date'];
$t_date=$_REQUEST['to_date'];

$end_f_date=$_REQUEST['end_from_date'];
$end_t_date=$_REQUEST['end_to_date'];

$s_loc=$_REQUEST['start_loc'];
$e_loc=$_REQUEST['end_loc'];
$t_stat=$_REQUEST['trip_stat'];

/*Fetch Database column Details*/
        $columns = array( 
            0 =>'id', 
            1 =>'start_location_id',
            2 =>'end_location_id',
            3 =>'driver_name',
            4 =>'mobile',
            5 =>'vehicle_no',
            6 =>'vendor_id',
            7 =>'veh_model_id',
            8 =>'del_cat_id',
            9 =>'del_route_id',
            10 =>'initial_km',
            11 =>'initial_km_proof_img',
            12 =>'complete_km',
            13 =>'complete_km_proof_img',
            14 =>'start_date',
            15 =>'end_date',
            16 =>'trip_status',
            17 =>'status'
        );
        
/*Fetch All Data Start*/    
        $sql1="SELECT tbl_vehicle_tracking.*,(SELECT location FROM tbl_barcode WHERE tbl_barcode.id=tbl_vehicle_tracking.start_location_id) as start_location,
        (SELECT location FROM tbl_barcode WHERE tbl_barcode.id=tbl_vehicle_tracking.end_location_id) as end_location,
        (SELECT vendor_name FROM tbl_vendor_list WHERE tbl_vendor_list.id=tbl_vehicle_tracking.vendor_id) as ven_name,
        (SELECT vehicle_name FROM tbl_vehicle_list WHERE tbl_vehicle_list.id=tbl_vehicle_tracking.veh_model_id) as veh_model,
        (SELECT del_cat_name FROM tbl_del_cat_list WHERE tbl_del_cat_list.id=tbl_vehicle_tracking.del_cat_id) as del_cat,
        (SELECT del_route_name FROM tbl_del_route_list WHERE tbl_del_route_list.id=tbl_vehicle_tracking.del_route_id) as del_route
        FROM `tbl_vehicle_tracking` WHERE status=1";
        
        //$f_date += " 23:59:00";
        //$t_date += " 23:59:00";
        
        if($f_date !='' && $t_date !=''){
            $sql1.=" AND start_date BETWEEN '".$f_date."' AND '".$t_date."'";
        }
        
        if($end_f_date !='' && $end_t_date !=''){
            $sql1.=" AND end_date BETWEEN '".$end_f_date."' AND '".$end_t_date."'";
        }
        
        if($s_loc != 0){
            $sql1.=" AND start_location_id=$s_loc";
        }
        if($e_loc != 0){
            $sql1.=" AND end_location_id=$e_loc";
        }
        if($t_stat != 0){
            $sql1.=" AND trip_status=$t_stat";
        }
        
        if($clientId!=1 && $clientType=="Admin"){
            $sql1.=" AND (start_location_id=$vehicle_tracking_branch_id or end_location_id=$vehicle_tracking_branch_id or end_location_id=0)";
        }
        
        $sql1.=" ORDER by id DESC";
        
        $statement = $pdo->prepare($sql1);
        $statement->execute();
        $result = $statement->fetchAll(PDO::FETCH_ASSOC);
        $totalData = $statement->rowCount();
        $totalFiltered = $totalData;
		
/*Fetch All Data End*/       
        
/*Fetch Filter Data Start*/    
        $sql="SELECT tbl_vehicle_tracking.*,(SELECT location FROM tbl_barcode WHERE tbl_barcode.id=tbl_vehicle_tracking.start_location_id) as start_location,
        (SELECT location FROM tbl_barcode WHERE tbl_barcode.id=tbl_vehicle_tracking.end_location_id) as end_location,
        (SELECT vendor_name FROM tbl_vendor_list WHERE tbl_vendor_list.id=tbl_vehicle_tracking.vendor_id) as ven_name,
        (SELECT vehicle_name FROM tbl_vehicle_list WHERE tbl_vehicle_list.id=tbl_vehicle_tracking.veh_model_id) as veh_model,
        (SELECT del_cat_name FROM tbl_del_cat_list WHERE tbl_del_cat_list.id=tbl_vehicle_tracking.del_cat_id) as del_cat,
        (SELECT del_route_name FROM tbl_del_route_list WHERE tbl_del_route_list.id=tbl_vehicle_tracking.del_route_id) as del_route
        FROM `tbl_vehicle_tracking` WHERE status=1";
        
        if($f_date !='' && $t_date !=''){
            $sql.=" AND start_date BETWEEN '".$f_date."' AND '".$t_date."'";
        }
        if($end_f_date !='' && $end_t_date !=''){
            $sql.=" AND end_date BETWEEN '".$end_f_date."' AND '".$end_t_date."'";
        }
        if($s_loc != 0){
            $sql.=" AND start_location_id=$s_loc";
        }
        if($e_loc != 0){
            $sql.=" AND end_location_id=$e_loc";
        }
        if($t_stat != 0){
            $sql.=" AND trip_status=$t_stat";
        }
        if($clientId!=1 && $clientType=="Admin"){
            $sql.=" AND (start_location_id=$vehicle_tracking_branch_id or end_location_id=$vehicle_tracking_branch_id or end_location_id=0)";
        }
        
        if( !empty($requestData['search']['value']) )
        {   
        	$sql.=" AND ( driver_name LIKE '%".$requestData['search']['value']."%' ";    
        	$sql.=" OR mobile LIKE '%".$requestData['search']['value']."%' ";
        	$sql.=" OR vehicle_no LIKE '%".$requestData['search']['value']."%' )";
        }
        
        $statement = $pdo->prepare($sql);
        $statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);
        $totalFiltered = $statement->rowCount();
        
/*Fetch Filter Data End*/       
        

 $sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]."   ".$requestData['order'][0]['dir']."  LIMIT ".$requestData['start']." ,".$requestData['length']."   ";
//  $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc  */	
$statement = $pdo->prepare($sql);
        $statement->execute();
		$query = $statement->fetchAll(PDO::FETCH_ASSOC);

$data = array();
$i=$requestData['start']+1;
//$i = 1;
foreach( $query as $row ) {  // preparing an array
	$nestedData=array();

 	$nestedData[] = $i;
 	//$action = "";
 	$action = "<a href='view-vehicle-tracking.php?id=".$row['id']."' class='btn btn-primary btn-xs' style='background-color: black;color: white;'>View</a>&nbsp;";
 	 if($allPermissions['vehicle_tracking']['update']=="1")
 	{ 	
 	    $action .="<a href='vehicle-tracking-edit.php?id=".$row['id']."' class='btn btn-primary btn-xs'>Edit</a>&nbsp;";
 	} 
 	if($row['trip_status']<=2 && $allPermissions['vehicle_tracking']['update']=="1") {
 	    $action .="<a href='vehicle-tracking-edit.php?flag=1&id=".$row['id']."' class='btn btn-success btn-xs'>End Trip</a>&nbsp;";
 	}
 	if($allPermissions['vehicle_tracking']['delete']=="1")
 	{ 	
 	    $action .=" <a href='#' class='btn btn-danger btn-xs' data-href='vehicle-tracking-delete.php?id=".$row['id']."' data-toggle='modal' data-target='#confirm-delete'>Delete</a>";
     	//$nestedData[]=$action;
 	}
 	
 	$nestedData[]=$action;
 	
 	$nestedData[] = $row["start_location"];
	$nestedData[] = $row["driver_name"];
	$nestedData[] = $row["mobile"];
	$d_r="";
	if($row['del_route']){
	    $d_r= $row['del_route']; 
	}
	
	$nestedData[] = $row['vehicle_number']."<br>".$row['ven_name']."<br>".$row['veh_model']."<br>".$row['del_cat']."<br>".$d_r;
	$nestedData[] = $row["initial_km"]." Km";
	
	if($row['initial_km_proof_img']){
	    $action1 = "<a  onclick='window.open('vehicle-api/Proof/".$row['initial_km_proof_img']."');' href='vehicle-api/Proof/".$row['initial_km_proof_img']."'  target='_blank' class='btn btn-primary btn-xs'>View Proof</a>";
	}
	$nestedData[]= $action1;
	
	$nestedData[] = $row["start_date"];
	$nestedData[] = $row["end_location"];
	$nestedData[] = $row["complete_km"];
	$action2 ="";
	if($row['complete_km_proof_img']){
	    $action2 = "<a  onclick='window.open('vehicle-api/Proof/".$row['complete_km_proof_img']."');' href='vehicle-api/Proof/".$row['complete_km_proof_img']."'  target='_blank' class='btn btn-primary btn-xs'>View Proof</a>";
	}
	$nestedData[]= $action2;
	$e_date="";
	if($row['end_date'] != "0000-00-00 00:00:00"){
	    $e_date = $row['end_date'];
	}
	$nestedData[] = $e_date;
	
	if($row['trip_status']<=2) {
	    $action3 = "<a href='#' class='btn btn-primary btn-xs'>Nill</a>";
	}else {
	    $val = $row['complete_km']-$row['initial_km'];
	    $action3 ="<a href='#' class='btn btn-success btn-xs'>".$val." 'Km'</a>";
	}
	$nestedData[] = $action3;
	
	if($row['trip_status']==1) {
	    $action4 = "<a href='#' class='btn btn-primary btn-xs'>Trip Started</a>";
	}else if($row['trip_status']==2) {
	    $action4 ="<a href='#' class='btn btn-primary btn-xs'>Trip Ongoing</a>";
	}else{
	    $val = $row['complete_km']-$row['initial_km'];
	    $action4 ="<a href='#' class='btn btn-success btn-xs'>Trip Completed</a>";
	}
	$nestedData[] = $action4;
	
	//$totalFiltered = $i;
	$data[] = $nestedData;
	$i++;
	
}
        //$totalData = $i;
        
        $json_data = array(
			"draw"            => intval( $requestData['draw'] ),   // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw. 
			"recordsTotal"    => intval( $totalData ),  // total number of records
			"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
			"data"            => $data   // total data array
			);

echo json_encode($json_data);  // send data as json format

?>