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

// include('connection.php');
include("../head-tag.php");

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

$conn = $connect;

date_default_timezone_set('Asia/Dubai');
// check if customer exists

$name = $_REQUEST["name"];
$hotel = $_REQUEST["Hotel"];
$room = $_REQUEST["Room"];
$flight = $_REQUEST["Flight"];
$amount = $_REQUEST["Amount"];
$comments = $_REQUEST["Comments"];
$email = $_REQUEST["email"];
$password = '123456';
$phone = $_REQUEST["phone"];
$address = $_REQUEST["address"];
$driver = $_SESSION["driverid"];
$useremail = $data_1["Email"];


// email related variables
$booknowemail = 1;
$customeremailnotification = 1;
$useremailnotification = 1;
$companyemailnotifcaiton = 0;

if($booknowemail == 1){
    if($customeremailnotification == 1 && $useremailnotification == 1){
        $to = "$email";
        $to .= ",";
        $to .= "$useremail";
        
    }
    elseif($customeremailnotification == 1){
        $to = "$email";

    }
    elseif($useremailnotification == 1){
        $to = "$useremail";

    }
else{
    $to;
    }

$subject = "E Booking";
$txt = "Name: $name\nPhone: $phone\nRoom: $room\nFlight: $flight\nAmount: $amount\nComments: $comments\nCustomer Email: $email";
$headers = "From: $companyemailnotifcaiton" . "\r\n" .
"CC: $companyemailnotifcaiton";

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

}
$raw = 0;
$appuser =0;

function email_exists($conn1, $email1)
{
    $sql = "SELECT * FROM app_users WHERE `email` ='$email1'";
    
    
    $raw = mysqli_query($conn1, $sql);

    if (mysqli_num_rows($raw) > 0) {
        $raw = mysqli_fetch_assoc($raw);
        return true;
    } else {
        return false;
    }
}

function clean($string)
{
    return preg_replace("/[^A-Za-z\-0-9.]/i", "", $string); // Removes special chars.
}


if ($_POST) {
    //hash code for email verification
    // https://code.tutsplus.com/tutorials/how-to-implement-email-verification-for-new-members--net-3824
    $hash = md5(rand(0, 1000));

    $picture = "default.png";

    if (!email_exists($conn, $email) || $email==""){

        // $stmt = "INSERT INTO app_users ( `Name`, `Email`, `Password`, `Phone`, `Image`, `address`,`ehash`) 
        //                 VALUES ('$name', '$email', '$password', '$phone', '$picture', '$address', '$hash')";
        
        $stmt = "INSERT INTO app_users ( `Name`, `Email`, `Password`, `Phone`, `address`,`ehash`) 
                        VALUES ('$name', '$email', '$password', '$phone', '$address', '$hash')";

        $result = mysqli_query($conn, $stmt); // $result = mysqli_query($conn,$stmt);
        $result1;
        $appuser = $conn->insert_id;

        //uploading image
        
        // https://stackoverflow.com/questions/54066507/sending-image-to-server-with-android-image-cropper-returns-null-with-getcroppedi
        

        // $myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
        // fwrite($myfile, $stmt);
        // fclose($myfile);
        
        if (!$result) {
            $response["code"] = "202";
            $response["msg"] = "Email is already in Use";
            //$response['msg'] = $stmt->error;
        } else {
            $response["code"] = "200";
                        // $response["msg"] =
//                 "You account has been created. ...Kindly Verify your Email from the Link. Please login now with your username/email address and password.";
// include $verifymail;
//
        }
    }


if ($email!="")
{
$sql = "SELECT * FROM app_users WHERE `email` ='$email'";

$raw = mysqli_query($connect, $sql);
$raw = mysqli_fetch_assoc($raw);
$appuser =$raw['Id'];
}
else
{
$sql = "SELECT max(Id) as Id FROM app_users";

$raw = mysqli_query($connect, $sql);
$raw = mysqli_fetch_assoc($raw);
$appuser =$raw['Id'];
}



// $driver = $_REQUEST["driver"];
$car_id = $_REQUEST["car"];
$charge_type = "trip";
// $charge_type = $_REQUEST['radio1'];
// $driver_id = $_POST['driver_id_from_dropdown'];
// $rent_start_date = date('Y-m-d', strtotime($_POST['rent_start_date']));
// $rent_end_date = date('Y-m-d', strtotime($_POST['rent_end_date']));
$rent_start_date = date('Y-m-d H:i:s');
$pickup = $_REQUEST["Pickup"];
$destination = $_REQUEST["Dropoff"];
$return_status = "NR"; // not returned
$status = "Pending";
$amount = $_REQUEST['Amount'];
$hotel = $_REQUEST['Hotel'];
$room = $_REQUEST['Room'];
$flight = $_REQUEST['Flight'];
$comments = $_REQUEST['Comments'];
$user_id = $_SESSION["userid"];
$vouchernumber = $_REQUEST["VoucherNumber"];



// $type = "route";
// $amount = $_REQUEST["amount"];
$bookingdate = date('Y-m-d H:i:s');
// $rd = str_replace("/","-",$_REQUEST["reservation_date"]);
$journeydate = $rent_start_date;
$status = "Pending";
$paymentstatus = $_REQUEST["pay_option"];
$hotelname = $_REQUEST["select_hotel"];
$paymentmethod = "Cash";
// $notes = $_REQUEST["notes"];
$user = $_REQUEST["user"];

    $car_name =0;
    $car_nameplate =0;
    // $client_name =0;
    // $client_phone =0;
    


    // function dateDiff($start, $end) {
    //     $start_ts = strtotime($start);
    //     $end_ts = strtotime($end);
    //     $diff = $end_ts - $start_ts;
    //     return round($diff / 86400);
    // }
    
    // $err_date = dateDiff("$rent_start_date", "$rent_end_date");

    $sql0 = "SELECT * FROM cars WHERE car_id = '$car_id'";
    $result0 = mysqli_query($connect,$sql0);

    if (mysqli_num_rows($result0) > 0) {
        while($row0 = mysqli_fetch_assoc($result0)) {

                if ($charge_type=="min")
                {
                    $fare = $row0["ac_price"];
                }
                else if ($charge_type=="days")
                {
                $fare = $row0["ac_price_per_day"];
            }
            else if ($charge_type=="trip") {
                $fare = $amount;
                $charge_type = "trip";
            }
        }
    }


// $driver_sql = mysqli_query($conn,"select * from drivers where Id = '$driver'");
// $driver_data = mysqli_fetch_assoc($driver_sql);
// $driver_name = $driver_data["Name"];

// $car_sql = mysqli_query($conn,"select * from cars where Id = '$car'");
// $car_data = mysqli_fetch_assoc($car_sql);
// $car_name = $car_data["Title"];

// $p_sql = mysqli_query($conn,"select * from emirates where Id = '$pickup'");
// $p_data = mysqli_fetch_assoc($p_sql);
// $pickup_name = $p_data["Title"];


// $d_sql = mysqli_query($conn,"select * from emirates where Id = '$destination'");
// $d_data = mysqli_fetch_assoc($d_sql);
// $destination_name = $d_data["Title"];

// mysqli_query($conn, "INSERT INTO `booking`(`Name`, `Email`, `Phone`, `Driver`,`Car`, `JourneyDate`,
// `Type`, `PickUp`, `Destination`, `Days`, `Notes`, `Amount`, `PaymentMethod`,
// `PaymentStatus`, `Status`, `BookingDate`, `User`) VALUES(
//  '$name','$email','$phone','$driver','$car','$journeydate','$type','$pickup','$destination'
//  ,'$days','$notes','$amount','$payment_method','$payment_status','$status','$bookingdate','$user')");
$sql1 = "INSERT INTO rentedcars(`car_id`,`booking_date`, `Name`,
    `rent_start_date`,`charge_type`,`pickup`,`Destination`,`PaymentStatus`,`hotel_name`,`user_id`,`voucher_number`,`status`,`appuser`,`return_status`,`bookingsource`,`customer_hotel`,`customer_room`,`customer_flight`,`comments`,`fare`,`total_amount`
    ) 
    VALUES(" . $car_id . ",'" . $bookingdate ."','" .$name."',
    '" . $rent_start_date ."','" . $charge_type . "','" . $pickup . "','" . $destination . "','" . $paymentstatus . "','" . $hotelname . "','" . $user_id . "','" . $voucher_number . "','" . $status . "','" . $appuser . "','" . $return_status . "','User','" . $hotel . "','" . $room . "','" . $flight . "','" . $comments . "'," . $fare . "," . $amount . ")";
    
$myfile = fopen("testfile.txt", "w");
fwrite($myfile, $sql1);
fclose($myfile);

    // echo($sql1."<br/>");
    $result1 = mysqli_query($conn,$sql1);
    $id = mysqli_insert_id($conn);

    $booking_number = date("Ymd").$id;
    mysqli_query($conn, "UPDATE rentedcars set bookingnumber = '$booking_number' WHERE id = '$id'");
 
 
// include $bookingconfirmmail;

if($_SESSION['username']=="user")
    header("location:../../user/booking-detail.php?id=".$id);
else
    header("location:../booking.php");
}
?>