<?php include("../cn.php");
include("../info.php");

// https://stackoverflow.com/questions/9541029/insert-current-date-in-datetime-format-mysql

$tag = $_REQUEST["Tag"];
$bookingno = $_REQUEST["BookingNo"];
$amount = $_POST["amount"];
// https://stackoverflow.com/questions/41177335/php-get-current-time-in-specific-time-zone#:~:text=For%20specific%20time%20zone%20select,()%20or%20time()%20function.&text=And%20to%20specify%20the%20timezone,echo%20%24now%2D%3EgetTimezone()%3B
date_default_timezone_set('Asia/Dubai');


$sql_1 = mysqli_query($connect,"select * from app_users where
Id = '".$_SESSION["userid"]."' ");
$data_1 = mysqli_fetch_assoc($sql_1);

$user="";

$sql = mysqli_query($connect, "SELECT rentedcars.*, cars.car_name AS car_title, cars.car_nameplate AS car_number, 
driver.driver_name as driver_name
FROM rentedcars 
INNER JOIN cars ON cars.car_id = rentedcars.car_id
LEFT JOIN driver ON driver.driver_id = rentedcars.driver_id
WHERE `BookingNumber`='".$bookingno."'");

$data = mysqli_fetch_assoc($sql);
$user = $data['AppUser'];

$sql1 = mysqli_query($connect, "SELECT * FROM app_users 
WHERE `Id`='".$user."'");

$customer = mysqli_fetch_assoc($sql1);

$user = $data['driver_id'];

$driver_name = $data["driver_name"];
$name = $customer["Name"];
$email = $customer["Email"];
$phone = $customer["Phone"];
$hotel = $data["customer_hotel"];
$room = $data["customer_room"];
$flight = $data["customer_flight"]; 
$car_title = $data["car_title"];
$car_number = $data["car_number"];
$pickup = $data["pickup"];
$destination = $data['Destination'];
$tripstartedat = $data['StartTime'];
$comments = $_REQUEST["Comments"];
$password = '123456';
$address = $_REQUEST["address"];
$driver = $_SESSION["driverid"];
$driveremail = $data_1["Email"];
$payment_status = $data["PaymentStatus"];

if($tag=="start")
{
    
    // $starttime = $_REQUEST["starttime"];
    // $starttime=date("Y-m-d H:i",strtotime($starttime));
    // https://www.php.net/manual/en/timezones.asia.php
    // https://stackoverflow.com/questions/3792066/convert-utc-dates-to-local-time-in-php
    // $startdatetime = $dt_utc->setTimezone(new DateTimeZone('Asia/Dubai'));
    // $startdatetime->format('Y-m-d H:i:s');
    $starttime = date('Y-m-d H:i:s');

$query = "UPDATE rentedcars SET StartTime = '$starttime',
            status = 'In-Progress' WHERE bookingnumber = '$bookingno'";

// $string = $starttime.'.......'.$query;

// $myfile = fopen("testfile.txt", "w");
// fwrite($myfile, $string);
// fclose($myfile);

if (mysqli_query($connect,$query))
{
    $response['code'] = "200";
    $response['starttime'] = $starttime;
    // $response['msg'] = "Start Logged";
} else {
  echo "Error updating Start Time" . $connect->error;
}

if($starttripemail == 1){
    if($customeremailnotification == 1 && $driveremailnotification == 1){
        $to = $email;
        $to .= ",";
        $to .= $driveremail;
    }
    elseif($customeremailnotification == 1){
        $to = $email;
    }
    elseif($driveremailnotification == 1){
        $to = $driveremail;
    }
else{
    $to;
    }
$subject = "Trip Started";
$txt = "Booking Number: $bookingno\nDriver Name: $driver_name\nCustomer Name: $name\nEmail: $email\nPhone: $phone\nHotel: $hotel\nAmount: $amount\nRoom: $room\nFlight: $flight\nCar: $car_title\nCar Number: $car_number\nPick Up Location: $pickup\nDrop Off Location: $destination";
$headers = "From: $companyemailnotificationfrom" . "\r\n" .
"CC: $companyemailnotificationcc";

mail($to,$subject,$txt,$headers);
}

} else if ($tag == "end")
{
    

    

    // $endtime = $_REQUEST["endtime"];
    // $endtime=date("Y-m-d H:i:s",strtotime($endtime));
    
    // $enddatetime = $dt_utc->setTimezone(new DateTimeZone('Asia/Dubai'));
    // $enddatetime->format('Y-m-d H:i:s');
    
    $endtime = date('Y-m-d H:i:s');
    $starttime = $fare = $chargetype = null;
    $response['msg'] = '';
    
    // https://stackoverflow.com/questions/4540684/java-round-up-any-number
    // get start time
    $sql = "SELECT * FROM rentedcars WHERE bookingnumber = '$bookingno'";
    $qry2 = mysqli_query($connect, $sql);
    
    if(mysqli_num_rows($qry2)>0)
    {
        $data = mysqli_fetch_assoc($qry2);
        $starttime = $data['StartTime'];
        $fare = $data['fare'];
        $chargetype = $data['charge_type'];
    }
    
    
    // https://www.codegrepper.com/code-examples/php/calculate+difference+between+two+datetime+in+php
    // DATE DIFFERENCE
    
    // $starttime = new DateTime($starttime);
    // $endtime = new DateTime($endtime);
    $start = strtotime($starttime);
    $end = strtotime($endtime);
    $duration ="";
    
    // date diff
    // $gap = (array) date_diff($endtime,$starttime);
    
    $totalSecondsDiff = abs($end-$start); //42600225
    $totalMinutesDiff = $totalSecondsDiff/60; //710003.75
    $totalHoursDiff   = $totalSecondsDiff/60/60;//11833.39
    $totalDaysDiff    = $totalSecondsDiff/60/60/24; //493.05
    
    
    // $myfile = fopen("testfile.txt", "w");
    // fwrite($myfile, implode(" ",$gap));
    // fclose($myfile);
    // date diff end
    
    // $starttime = strtotime($starttime);
    
    // //DateTime String
    // $starttime = $starttime->format('Y-m-d H:i:s');
    // $endtime = $endtime->format('Y-m-d H:i:s');
    if($chargetype == 'trip')
    {
        $minutes = ceil($totalMinutesDiff);
        
        $duration = $minutes;
        
        // $amount = $fare;
        
        $response['msg'] = "..Trip Ended..";
        $response['msg'] = $response['msg']."\nStarted At: $starttime";
        $response['msg'] = $response['msg']."\nEnded On: $endtime";
        $response['msg'] = $response['msg']."\n\nFare: $fare AED/Trip";
        $response['msg'] = $response['msg']."\n\nAmount: $amount";
    }
    else if($chargetype == 'min')
    {
        $minutes = ceil($totalMinutesDiff);
        
        $duration = $minutes;
        
        $amount = ceil($fare*$minutes);
        
        $response['msg'] = "..Trip Ended..";
        $response['msg'] = $response['msg']."\nStarted At: $starttime";
        $response['msg'] = $response['msg']."\nEnded On: $endtime";
        $response['msg'] = $response['msg']."\n\nMinutes: $minutes";
        $response['msg'] = $response['msg']."\n\nFare: $fare AED/Min";
        $response['msg'] = $response['msg']."\n\nAmount: $amount";
    } else if ($chargetype == 'days')
    {
        $days = ceil($totalDaysDiff);
        
        $duration = $days;
        
        $amount = ceil($fare*$days);
        
        $response['msg'] = "..Trip Ended..";
        $response['msg'] = $response['msg']."\nStarted At: $starttime";
        $response['msg'] = $response['msg']."\nEnded On: $endtime";
        $response['msg'] = $response['msg']."\n\nDays: $days";
        $response['msg'] = $response['msg']."\n\nFare: $fare AED/Min";
        $response['msg'] = $response['msg']."\n\nAmount: $amount";
    }
   /*  total_amount = '$amount',*/
   
if($payment_status == "By Hotel"){
    
    $destination = $_REQUEST["destination"];
    
        $amount = $_REQUEST["amount"];
    
$query = "UPDATE rentedcars SET EndTime = '$endtime', fare = '$amount', total_amount = '$amount', Destination = '$destination', duration='$duration',
            status = 'Completed' WHERE bookingnumber = '$bookingno'";
            
$query_da = "UPDATE driver SET driver_availability = 'yes' WHERE driver_id = $driver";
$result_da = mysqli_query($connect, $query_da);
}
else{
    $query = "UPDATE rentedcars SET EndTime = '$endtime', fare = '$amount', duration='$duration',
            status = 'Completed' WHERE bookingnumber = '$bookingno'";
}

// $string = $endtime.'.......'.$query;

// $myfile = fopen("testfile.txt", "w");
// fwrite($myfile, $string);
// fclose($myfile);

if (mysqli_query($connect, $query))
{
    $response['code'] = "200";
    // $response['msg'] = "End Logged";
} else {
    $response['code'] = "202";
    $response['msg'] = "Error updating End Time " . $connect->error;
}



if($endtripemail == 1){
    if($customeremailnotification == 1 && $driveremailnotification == 1){
        $to = $email;
        $to .= ",";
        $to .= $driveremail;
    }
    elseif($customeremailnotification == 1){
        $to = $email;
    }
    elseif($driveremailnotification == 1){
        $to = $driveremail;
    }
else{
    $to;
    }
$subject = "Trip Ended";
$txt = "Booking Number: $bookingno\nDriver Name: $driver_name\nCustomer Name: $name\nEmail: $email\nPhone: $phone\nAmount: $amount\nHotel: $hotel\nRoom: $room\nFlight: $flight\nCar: $car_title\nCar Number: $car_number\nPick Up Location: $pickup\nDrop Off Location: $destination\nTrip Started At: $starttime";
$headers = "From: $companyemailnotificationfrom" . "\r\n" .
"CC: $companyemailnotificationcc";

mail($to,$subject,$txt,$headers);
}


}

// else if ($tag == "paid")
// {
// $query = "UPDATE rentedcars SET paymentstatus = 'Paid' WHERE bookingnumber = $bookingno'";

// $myfile = fopen("testfile.txt", "w");
// fwrite($myfile, $query);
// fclose($myfile);

// if (mysqli_query($connect, $query))
// {
//   echo "End Logged";
// } else {
//   echo "Error updating End Time " . $connect->error;
// }

// }

// check if customer exists
// $customer=[];







$connect->close();

echo json_encode($response);
?>