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

$f_date=$_REQUEST['fromm'];
$t_date=$_REQUEST['too'];
$s_loc=$_REQUEST['st_loc_ids'];
$e_loc=$_REQUEST['end_loc_ids'];
$t_stat=$_REQUEST['trip_st_ids'];

$end_f_date=$_REQUEST['end_fromm'];
$end_t_date=$_REQUEST['end_too'];

$now = gmdate("YmdHis");
header('Content-Type: text/csv; charset=utf-8');  
header('Content-Disposition: attachment; filename=Vehicle-Tracking-'.$now.'.csv');  
$output = fopen("php://output", "w");  
fputcsv($output, array('SL','Start Location', 'Driver Name', 'Mobile Number', 'Vehicle Number','Vondor Name','Vehicle Model','Delivery Category','Delivery Route', 'Initial Km', 'Start Date & Time', 'End Location', 'Ending Km', 'End Date & Time','Trip Km','Trip Status'));  
$i=1;
$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";
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";
}
$sql1.=" ORDER by id DESC";
        
$statement = $pdo->prepare($sql1);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row){
    if($row['trip_status']==1) {  $t_km="Nill"; } else { $t_km=$row['complete_km']-$row['initial_km']." Km"; } 
	if($row['trip_status']==1) { $status="Trip Started"; } else if($row['trip_status']==2){ $status="In Trip"; }else if($row['trip_status']==3){ $status="Trip Completed"; }
    $d_r="";
	if($row['del_route']){
	    $d_r= "\r\nDelivery Route - ".$row['del_route']; 
	}
	$e_date = "";
	if($row['end_date'] != "0000-00-00 00:00:00"){
	    $e_date = $row['end_date'];
	}

	fputcsv($output, array($i,$row['start_location'],$row['driver_name'],$row['mobile'],$row['vehicle_number'],$row['ven_name'],$row['veh_model'],$row['del_cat'],$row['del_route'],$row['initial_km'],$row['start_date'],$row['end_location'],$row['complete_km'],$e_date,$t_km,$status));
    $i++;
}
fclose($output);
?>