<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarOwner;
use App\Models\CarOwnerCar;
use App\Models\PreBooking;
use App\Models\PreBookingType;
use App\Models\CwoPreBookingType;
use App\Models\BodyType;
use App\Models\WashCategoryBodyType;
// use App\Models\WashTypeToPrebooking;
use App\Models\WashTypeToWash;
use App\Models\OptionalExtra;
use App\Models\CleanerWash;
use App\Models\CarWashOwner;
use App\Models\CurrencyMaster;
use App\Models\Loyalty;
use App\Models\WashDetail;
use App\Models\User;
use App\Models\LoyaltyScore;
use App\Models\LoyaltyPointToZar;
use App\Models\WashCategoryLoyaltyPoint;
use App\Models\LoyaltyScoreUsageLog;
use App\Models\LoyaltyScoreAddLog;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Config;
use Hash;
use Auth;

class CoPreBookingController extends Controller
{
    public function __construct()
    {
    }

    public function index()
    {
    }

    public function add_withoutNewLoyaltyPoints(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_type' => 'required',
                'co_id' => 'required',
                'name' => 'required',
                'isd_code' => 'required',
                'phone_no' => 'required',
                'date' => 'required',
                'time' => 'required',
                'address' => 'required',
                'car_id' => 'required',
                'body_type_id' => 'required',
                'cwo_id' => 'required',
                'wash_types' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_type = $request->input('prebooking_type');
        $co_id = $request->input('co_id');
        $name = $request->input('name');
        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $date = $request->input('date');
        $time = $request->input('time');
        $address = $request->input('address');
        $car_id = $request->input('car_id');
        $body_type_id = $request->input('body_type_id');
        $cwo_id = $request->input('cwo_id');
        if($date != ''){
            $date = date("Y-m-d", strtotime($date));
        }
        if($time != ''){
            $time = date("H:i:s", strtotime($time));
        }
        $dt = Carbon::now();

        $is_free_wash = $request->input('is_free_wash');
        $free_wash_type_id = $request->input('free_wash_type_id');
        $loyalty_type = $request->input('loyalty_type'); // 1 or 2 (1=Free Wash, 2=Price Discount)
        // $no_of_paid_wash = $request->input('no_of_paid_wash'); 
        $discount_value_in_percentage = $request->input('discount_value_in_percentage');  
        if($discount_value_in_percentage == ''){
            $discount_value_in_percentage = 0;
        }

        $dob = $request->input('dob');
        if($dob != '') {
            $dob = date("Y-m-d", strtotime($dob)); 
        } else {
            $dob = NULL;
        }

        if($body_type_id != ''){
            $getBodyType = BodyType::where('id', $body_type_id)->select('name')->first();
            $body_type = $getBodyType->name;
        } else {
            $body_type_id = 0;
            $body_type = '';
        }

        $lat = $request->input('lat');
        $long = $request->input('long');

        $wash_types = $request->input('wash_types');
        $amount = 0; 
        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $amount = $amount + $getPrice->price;
                    } else {
                        $amount = $amount + 0;
                    }
                } // foreach ends
            } // if ends
        }
        $total_amount = $amount;*/
        if($is_free_wash == 'true'){ // true starts
            // echo "1";exit;
            $is_free_wash = 1;  
            // $amount = 0;  
            /*** free wash id logic starts ***/
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){  // if starts
                    if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                        if($loyalty_type == 1){ // if loyalty_type = 1 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $amount = $amount + 0;    
                                } else {
                                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                    if($getPrice != ''){
                                        $amount = $amount + $getPrice->price;
                                    } else {
                                        $amount = $amount + 0;
                                    }
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 1 ends
                        if($loyalty_type == 2){ // if loyalty_type = 2 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 2 ends
                    } else { //*** if loyalty_type is blank in old version stick to free_wash_type_id
                        foreach ($wash_type_id_array as $e) {
                            // echo $e['wash_type_id'];exit;
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $amount = $amount + 0;    
                            } else {
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                            }
                            
                        } // foreach ends
                    } // if loyalty type exists check ends
                } // if ends
            }
            /*** free wash id logic ends ***/
        } // true ends
        if($is_free_wash == 'false'){
            // echo "0";exit;
            $is_free_wash = 0; 
            /*if($getPrice != ''){
                $amount = $getPrice->price;
            } else {
                $amount = 0;
            }*/

            /*wash category add starts*/
            // $wash_types = $request->input('wash_types');
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){
                    foreach ($wash_type_id_array as $e) {
                        $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                        if($getPrice != ''){
                            $amount = $amount + $getPrice->price;
                        } else {
                            $amount = $amount + 0;
                        }
                    }
                }
            }
            /*wash category add ends*/
        }
        $dt = Carbon::now(); 
        $total_amount = $amount;

        /*insert into pre_bookings table starts*/
        $data = PreBooking::create([
            'prebooking_type'=> $prebooking_type,
            'co_id'=> $co_id,
            'name'=> $name,
            'isd_code'=> $isd_code,
            'phone_no'=> $phone_no,
            'dob'=> $dob,
            'date'=> $date,
            'time'=> $time,
            'date_time'=> $date . ' ' . $time,
            'address'=> $address,
            'lat'=> $lat,
            'long'=> $long,
            'car_id'=> $car_id,
            'body_type_id'=> $body_type_id,
            'body_type'=> $body_type,
            'cwo_id'=> $cwo_id,
            'amount'=> $amount,
            'total_amount'=> $total_amount,
            'is_free_wash'=> $is_free_wash,
            'discount'=> $discount_value_in_percentage,
            'status'=> 6,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        $prebooking_id = $data->id;
        /*insert into pre_bookings table ends*/

        /*extra add starts*/
        $extras = $request->input('extras');
        // echo $extras;exit;
        if($extras != ''){
            $extra_array=json_decode($extras, true);
            if($extra_array != ""){
                // $extra_price = 0;
                foreach ($extra_array as $e) {
                    // $extra_json = json_encode($e);
                    // $extra_price = $extra_price + $e['price'];
                    $total_amount = $total_amount + $e['price'];
                    $addOptionalExtra = OptionalExtra::create([
                        'prebooking_id'=> $prebooking_id,
                        'optional_extra'=> $e['optional_extra'],
                        'price'=> $e['price'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
                // $total_amount = $amount + $extra_price;
            }
        }
        /*extra add ends*/

        /*if loyalty type 2 exists starts*/
        if($loyalty_type != ""){
            if($loyalty_type == 2){
                $discount_amount = ($discount_value_in_percentage/100) * $total_amount;
                $total_amount = $total_amount - $discount_amount;
            }
        }
        /*if loyalty type 2 exists ends*/

        $record_prebooking = PreBooking::find($prebooking_id);
        $record_prebooking->total_amount = $total_amount;
        $record_prebooking->save();

        /*cleaner add starts*/
        $cleaners = $request->input('cleaners');
        if($cleaners != ''){
            $cleaner_array=json_decode($cleaners, true);
            if($cleaner_array != ""){
                foreach ($cleaner_array as $e) {
                    $assignCleaner = CleanerWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'cleaner_id'=> $e['cleaner_id'],
                        'description'=> $e['description'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }
        /*cleaner add ends*/

        /*wash category add starts*/
        $wash_types = $request->input('wash_types');
        if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($is_free_wash == 1){ // if it is a free wash starts
                        if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                            if($loyalty_type == 1){ // if loyalty_type = 1 starts
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $wash_type_price = 0;
                                } else {
                                    if($getPrice != ''){
                                        $wash_type_price = $getPrice->price;
                                    } else {
                                        $wash_type_price = 0;
                                    }    
                                }
                            } // if loyalty_type = 1 ends
                            if($loyalty_type == 2){ // if loyalty_type = 2 starts
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }
                            } // if loyalty_type = 2 ends
                        } else {  //*** if loyalty_type is blank in old version stick to free_wash_type_id
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $wash_type_price = 0;
                            } else {
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }    
                            }
                        }
                        
                    } // if it is a free wash ends
                    if($is_free_wash == 0){ // if it is not a free wash starts
                        if($getPrice != ''){
                            $wash_type_price = $getPrice->price;
                        } else {
                            $wash_type_price = 0;
                        }
                    } // if it is not a free wash ends
                    
                    $assignWashType = WashTypeToWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }
        /*wash category add ends*/

        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $wash_type_price = $getPrice->price;
                    } else {
                        $wash_type_price = 0;
                    }
                    $assignWashType = WashTypeToPrebooking::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                } // foreach ends
            } // if ends
        }*/

        $getCwo = CarWashOwner::where('id', $cwo_id)->select('cwo_company', 'cwo_email', 'currency_id')->first();
        $cwo_company = $getCwo->cwo_company;
        $cwo_email = $getCwo->cwo_email;
        if($getCwo->currency_id != 0){
            $getCurrency = CurrencyMaster::findorfail($getCwo->currency_id);
            $currency = $getCurrency->symbol;
        } else {
            $currency = 'R';
        }

        $getCar = CarOwnerCar::where('id', $car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;

        $getCo = CarOwner::where('id', $co_id)->select('co_fname', 'co_lname', 'email', 'fcm_token')->first();
        if($name != '') {
            $co_name = $name;
        } else {
            $co_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $co_email = $getCo->email;
        $fcm_token = $getCo->fcm_token;

        $getCwoUser = User::select('id', 'email', 'fcm_token')->where('cwo_id', $cwo_id)->where('is_active', 1)->get();
        // print_r($getCwoUser->toArray());exit;

        /*send mail to CWO starts*/
        // if($cwo_email != ''){
            $subject_cwo = 'Autoclick App - Car Pre Booking';
            // $message_body_cwo = '<html>
            //                     <head>
            //                     <title>Autoclick Car Pre Booking</title>
            //                     </head>
            //                     <body>
            //                         <p>Hi ' . $cwo_company . '</p>
            //                         <p>A Pre booking has been added. Following are the Details.</p>
            //                         <p>Car Registration No.: ' . $car_registration_no . '</p>
            //                         <p>Body Type: ' . $body_type . '</p>
            //                         <p>Name: ' . $name . '</p>
            //                         <p>Phone: +' . $isd_code . $phone_no . '</p>
            //                         <p>Date: ' . $date . '</p>
            //                         <p>Time: ' . $time . '</p>
            //                         <p>Adrees: ' . $address . '</p>
            //                         <p>Total Amount: ' . $currency . $total_amount . '</p>
            //                         <p>Please go to your CWO App and accept/decline the booking.</p>
            //                         <p>Regards</p>
            //                         <p>AUTOCLICK</p>
            //                         <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
            //                     </body>
            //                 </html>';
            $message_body_cwo = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $cwo_company . '</p>
                                    <p>You have received a new car wash booking request from a client. Please log in to the app to accept or decline under My Bookings.</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';               
            // echo $message_body_cwo;exit;
            if($getCwoUser != ''){
                foreach($getCwoUser as $u){
                    if($u->email != ''){                
                        $email_cwo = sendMail(array($cwo_company, $u->email), $message_body_cwo, $subject_cwo);
                        // print_r($email_cwo);exit;
                    }
                }
            }
        // }
        /*send mail to CWO ends*/

        /*send mail to CO starts*/
        if($co_email != ''){
            $subject_co = 'Autoclick App - Car Pre Booking';
            $message_body_co = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $co_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been added at  ' . $cwo_company . '.  Following are the Details.</p>
                                    <p>CWO Company: ' . $cwo_company . '</p>
                                    <p>Car Registration No.: ' . $car_registration_no . '</p>
                                    <p>Body Type: ' . $body_type . '</p>
                                    <p>Name: ' . $name . '</p>
                                    <p>Phone: +' . $isd_code . $phone_no . '</p>
                                    <p>Date: ' . $date . '</p>
                                    <p>Time: ' . $time . '</p>
                                    <p>Adrees: ' . $address . '</p>
                                    <p>Total Amount: ' . $currency . $total_amount . '</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body_co;exit;
            $email_co = sendMail(array($co_name, $co_email), $message_body_co, $subject_co);
            // print_r($email_co);exit;
        }
        /*send mail to CO ends*/

        /*push starts*/
        if($getCwoUser != ''){
            $notification_title = 'Autoclick Car Pre Booking';
            // $notification_body = 'Pre-booking for a car ' . $car_registration_no . ' has been added at ' . $cwo_company;
            $notification_body = 'You have received a new car wash booking request from a client. Please log in to the app to accept or decline under My Bookings.';
            // echo $notification_title . ' ->' . $notification_body;exit;
            foreach($getCwoUser as $u){
                if($u->fcm_token != ''){
                    $data=array("request_type" => "notification");
                    sendFcmNotificationForCwo($u->fcm_token, $notification_title, $notification_body, $data);
                }
            }
        }
        /*push ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre-booking has been added successfully. We will contact you shortly.',
            'prebooking_id' => $prebooking_id
        ]);

    }

    public function add(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_type' => 'required',
                'co_id' => 'required',
                'name' => 'required',
                'isd_code' => 'required',
                'phone_no' => 'required',
                'date' => 'required',
                'time' => 'required',
                'address' => 'required',
                'car_id' => 'required',
                'body_type_id' => 'required',
                'cwo_id' => 'required',
                'wash_types' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_type = $request->input('prebooking_type');
        $co_id = $request->input('co_id');
        $name = $request->input('name');
        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $date = $request->input('date');
        $time = $request->input('time');
        $address = $request->input('address');
        $car_id = $request->input('car_id');
        $body_type_id = $request->input('body_type_id');
        $cwo_id = $request->input('cwo_id');
        if($date != ''){
            $date = date("Y-m-d", strtotime($date));
        }
        if($time != ''){
            $time = date("H:i:s", strtotime($time));
        }
        $dt = Carbon::now();

        $is_free_wash = $request->input('is_free_wash');
        $free_wash_type_id = $request->input('free_wash_type_id');
        $loyalty_type = $request->input('loyalty_type'); // 1 or 2 (1=Free Wash, 2=Price Discount)
        // $no_of_paid_wash = $request->input('no_of_paid_wash'); 
        $discount_value_in_percentage = $request->input('discount_value_in_percentage');  
        if($discount_value_in_percentage == ''){
            $discount_value_in_percentage = 0;
        }

        $dob = $request->input('dob');
        if($dob != '') {
            $dob = date("Y-m-d", strtotime($dob)); 
        } else {
            $dob = NULL;
        }

        if($body_type_id != ''){
            $getBodyType = BodyType::where('id', $body_type_id)->select('name')->first();
            $body_type = $getBodyType->name;
        } else {
            $body_type_id = 0;
            $body_type = '';
        }

        $lat = $request->input('lat');
        $long = $request->input('long');

        $wash_types = $request->input('wash_types');
        $amount = 0; 
        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $amount = $amount + $getPrice->price;
                    } else {
                        $amount = $amount + 0;
                    }
                } // foreach ends
            } // if ends
        }
        $total_amount = $amount;*/
        if($is_free_wash == 'true'){ // true starts
            // echo "1";exit;
            $is_free_wash = 1;  
            // $amount = 0;  
            /*** free wash id logic starts ***/
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){  // if starts
                    if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                        if($loyalty_type == 1){ // if loyalty_type = 1 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $amount = $amount + 0;    
                                } else {
                                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                    if($getPrice != ''){
                                        $amount = $amount + $getPrice->price;
                                    } else {
                                        $amount = $amount + 0;
                                    }
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 1 ends
                        if($loyalty_type == 2){ // if loyalty_type = 2 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 2 ends
                    } else { //*** if loyalty_type is blank in old version stick to free_wash_type_id
                        foreach ($wash_type_id_array as $e) {
                            // echo $e['wash_type_id'];exit;
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $amount = $amount + 0;    
                            } else {
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                            }
                            
                        } // foreach ends
                    } // if loyalty type exists check ends
                } // if ends
            }
            /*** free wash id logic ends ***/
        } // true ends
        if($is_free_wash == 'false'){
            // echo "0";exit;
            $is_free_wash = 0; 
            /*if($getPrice != ''){
                $amount = $getPrice->price;
            } else {
                $amount = 0;
            }*/

            /*wash category add starts*/
            // $wash_types = $request->input('wash_types');
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){
                    foreach ($wash_type_id_array as $e) {
                        $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                        if($getPrice != ''){
                            $amount = $amount + $getPrice->price;
                        } else {
                            $amount = $amount + 0;
                        }
                    }
                }
            }
            /*wash category add ends*/
        }
        $dt = Carbon::now(); 
        $total_amount = $amount;

        /*insert into pre_bookings table starts*/
        $data = PreBooking::create([
            'prebooking_type'=> $prebooking_type,
            'co_id'=> $co_id,
            'name'=> $name,
            'isd_code'=> $isd_code,
            'phone_no'=> $phone_no,
            'dob'=> $dob,
            'date'=> $date,
            'time'=> $time,
            'date_time'=> $date . ' ' . $time,
            'address'=> $address,
            'lat'=> $lat,
            'long'=> $long,
            'car_id'=> $car_id,
            'body_type_id'=> $body_type_id,
            'body_type'=> $body_type,
            'cwo_id'=> $cwo_id,
            'amount'=> $amount,
            'total_amount'=> $total_amount,
            'is_free_wash'=> $is_free_wash,
            'discount'=> $discount_value_in_percentage,
            'status'=> 6,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        $prebooking_id = $data->id;
        /*insert into pre_bookings table ends*/

        /*extra add starts*/
        $extras = $request->input('extras');
        // echo $extras;exit;
        if($extras != ''){
            $extra_array=json_decode($extras, true);
            if($extra_array != ""){
                // $extra_price = 0;
                foreach ($extra_array as $e) {
                    // $extra_json = json_encode($e);
                    // $extra_price = $extra_price + $e['price'];
                    $total_amount = $total_amount + $e['price'];
                    $addOptionalExtra = OptionalExtra::create([
                        'prebooking_id'=> $prebooking_id,
                        'optional_extra'=> $e['optional_extra'],
                        'price'=> $e['price'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
                // $total_amount = $amount + $extra_price;
            }
        }
        /*extra add ends*/

        /*if loyalty type 2 exists starts*/
        if($loyalty_type != ""){
            if($loyalty_type == 2){
                $discount_amount = ($discount_value_in_percentage/100) * $total_amount;
                $total_amount = $total_amount - $discount_amount;
            }
        }
        /*if loyalty type 2 exists ends*/

        $record_prebooking = PreBooking::find($prebooking_id);
        $record_prebooking->total_amount = $total_amount;
        $record_prebooking->save();

        if($is_free_wash == 1){ 
            $record_prebooking->loyalty_type = $loyalty_type;
            $record_prebooking->save();
        }

        /*cleaner add starts*/
        $cleaners = $request->input('cleaners');
        if($cleaners != ''){
            $cleaner_array=json_decode($cleaners, true);
            if($cleaner_array != ""){
                foreach ($cleaner_array as $e) {
                    $assignCleaner = CleanerWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'cleaner_id'=> $e['cleaner_id'],
                        'description'=> $e['description'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }
        /*cleaner add ends*/

        /*wash category add starts*/
        $wash_types = $request->input('wash_types');
        if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($is_free_wash == 1){ // if it is a free wash starts
                        if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                            if($loyalty_type == 1){ // if loyalty_type = 1 starts
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $wash_type_price = 0;
                                } else {
                                    if($getPrice != ''){
                                        $wash_type_price = $getPrice->price;
                                    } else {
                                        $wash_type_price = 0;
                                    }    
                                }
                            } // if loyalty_type = 1 ends
                            if($loyalty_type == 2){ // if loyalty_type = 2 starts
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }
                            } // if loyalty_type = 2 ends
                        } else {  //*** if loyalty_type is blank in old version stick to free_wash_type_id
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $wash_type_price = 0;
                            } else {
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }    
                            }
                        }
                        
                    } // if it is a free wash ends
                    if($is_free_wash == 0){ // if it is not a free wash starts
                        if($getPrice != ''){
                            $wash_type_price = $getPrice->price;
                        } else {
                            $wash_type_price = 0;
                        }
                    } // if it is not a free wash ends
                    
                    $assignWashType = WashTypeToWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }
        /*wash category add ends*/

        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $wash_type_price = $getPrice->price;
                    } else {
                        $wash_type_price = 0;
                    }
                    $assignWashType = WashTypeToPrebooking::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                } // foreach ends
            } // if ends
        }*/

        /*if new loyalty system exists starts*/
        $is_new_loyalty = $request->input('is_new_loyalty');
        if($is_new_loyalty != '') { // is_new_loyalty starts
            // echo $is_new_loyalty;exit;
            if($loyalty_type == 3) { // if loyalty type 3 starts
                // echo $loyalty_type;exit;
                $total_loyalty_points =  $request->input('total_loyalty_points');            
                $used_loyalty_point =  $request->input('used_loyalty_point');            
                $used_zar_value =  $request->input('used_zar_value');   
                // echo $total_loyalty_points . ' -> ' . $used_loyalty_point . '-> ' . $used_zar_value . '<br>';
                if($total_loyalty_points != '' && $used_loyalty_point != '' && $used_zar_value != '') {
                    if($used_loyalty_point != 'undefined'){
                        if($used_loyalty_point > 0) {
                            $remaining_loyalty_point =  $total_loyalty_points - $used_loyalty_point; 
                            // echo 'remaining-> ' . $remaining_loyalty_point;
                            $total_amount = $total_amount - $used_zar_value;
                            //update wash_deatils srtarts
                            $record_prebooking->used_loyalty_point = $used_loyalty_point;
                            $record_prebooking->used_loyalty_to_zar = $used_zar_value;
                            $record_prebooking->total_amount = $total_amount;
                            $record_prebooking->loyalty_type = $loyalty_type;
                            if($total_amount == 0){
                                $record_prebooking->payment_status = 1;
                                $record_prebooking->payment_details = 'Loyalty Points';
                            }
                            $record_prebooking->save();
                            //update wash_deatils ends

                            // loyalty_score_usage_logs starts
                            LoyaltyScoreUsageLog::create([
                                'prebooking_id'=> $prebooking_id,
                                'cwo_id'=> $cwo_id,
                                'co_id'=> $co_id,
                                'isd_code'=> $isd_code,
                                'phone'=> $phone_no,
                                'available_total_loyalty_point'=> $total_loyalty_points,
                                'used_loyalty_point'=> $used_loyalty_point,
                                'remaining_loyalty_point'=> $remaining_loyalty_point,
                                'used_date'=> date('Y-m-d'),
                                'created_at'=>$dt->toDayDateTimeString(),
                                'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                            // loyalty_score_usage_logs ends 
                            // loyalty_scores data starts
                            $loyaltyData = LoyaltyScore::where('cwo_id', $cwo_id)
                                                ->where('isd_code', $isd_code)
                                                ->where('phone', $phone_no)
                                                ->first();
                            // echo "<pre>";print_r($loyaltyData);exit;
                            if($loyaltyData != ""){
                                // echo "loyalty row exists";exit;
                                // echo $remaining_loyalty_point;exit;
                                $loyaltyData->update([
                                    'loyalty_point'=> $remaining_loyalty_point,
                                    'updated_at'=>$dt->toDayDateTimeString()
                                ]);
                            } else {
                                // echo "loyalty row does not exist";exit;
                                LoyaltyScore::create([
                                    'cwo_id'=> $cwo_id,
                                    'co_id'=> $co_id,
                                    'isd_code'=> $isd_code,
                                    'phone'=> $phone_no,
                                    'loyalty_point'=> $remaining_loyalty_point,
                                    'created_at'=>$dt->toDayDateTimeString(),
                                    'updated_at'=>$dt->toDayDateTimeString()
                                ]);
                            }
                            // loyalty_scores data ends
                            // loyalty_score_add_logs starts
                            // LoyaltyScoreAddLog::create([
                            //     'wash_id'=> $wash_id,
                            //     'cwo_id'=> $cwo_id,
                            //     'co_id'=> $co_id,
                            //     'isd_code'=> $isd_code,
                            //     'phone'=> $phone_no,
                            //     'available_total_loyalty_point'=> $total_loyalty_points,
                            //     'added_loyalty_point'=> $used_loyalty_point,
                            //     'total_loyalty_point'=> '',
                            //     'wash_entry_date'=> $today,
                            //     'created_at'=>$dt->toDayDateTimeString(),
                            //     'updated_at'=>$dt->toDayDateTimeString()
                            // ]);
                            // loyalty_score_add_logs ends  
                        }
                    }
                }        
            } // if loyalty type 3 ends
            // exit;

            if($wash_types != ''){
                $lpCount = 0;
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){
                    foreach ($wash_type_id_array as $e) {
                        $getLoyaltyPoints = WashCategoryLoyaltyPoint::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                        if($getLoyaltyPoints != ''){ // if loyalty points earn starts
                            $lpCount = $lpCount + $getLoyaltyPoints->loyalty_point;
                        } // if loyalty points earn ends
                    } // foreach ends
                    $getLoyaltyData = LoyaltyScore::where('cwo_id', $cwo_id)
                                    ->where('isd_code', $isd_code)
                                    ->where('phone', $phone_no)
                                    ->first();
                    if($getLoyaltyData != ""){
                        $existingLoyaltyPoint = $getLoyaltyData->loyalty_point;
                        $finalLoyaltyPoint = $existingLoyaltyPoint + $lpCount;
                        $getLoyaltyData->update([
                            'loyalty_point'=> $finalLoyaltyPoint,
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    } else {
                        $existingLoyaltyPoint = 0;
                        $finalLoyaltyPoint = $lpCount;
                        LoyaltyScore::create([
                            'cwo_id'=> $cwo_id,
                            'co_id'=> $co_id,
                            'isd_code'=> $isd_code,
                            'phone'=> $phone_no,
                            'loyalty_point'=> $finalLoyaltyPoint,
                            'created_at'=>$dt->toDayDateTimeString(),
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    } 
                    // loyalty_score_add_logs starts
                    if($lpCount > 0) {
                        LoyaltyScoreAddLog::create([
                            'prebooking_id'=> $prebooking_id,
                            'cwo_id'=> $cwo_id,
                            'co_id'=> $co_id,
                            'isd_code'=> $isd_code,
                            'phone'=> $phone_no,
                            'available_total_loyalty_point'=> $existingLoyaltyPoint,
                            'added_loyalty_point'=> $lpCount,
                            'total_loyalty_point'=> $finalLoyaltyPoint,
                            'wash_entry_date'=> date('Y-m-d'),
                            'created_at'=>$dt->toDayDateTimeString(),
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    }
                    // loyalty_score_add_logs ends 
                } // if ends
            }                        
        } // is_new_loyalty ends
        /*if new loyalty system exists ends*/
        // exit;

        $getCwo = CarWashOwner::where('id', $cwo_id)->select('cwo_company', 'cwo_email', 'currency_id')->first();
        $cwo_company = $getCwo->cwo_company;
        $cwo_email = $getCwo->cwo_email;
        if($getCwo->currency_id != 0){
            $getCurrency = CurrencyMaster::findorfail($getCwo->currency_id);
            $currency = $getCurrency->symbol;
        } else {
            $currency = 'R';
        }

        $getCar = CarOwnerCar::where('id', $car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;

        $getCo = CarOwner::where('id', $co_id)->select('co_fname', 'co_lname', 'email', 'fcm_token')->first();
        if($name != '') {
            $co_name = $name;
        } else {
            $co_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $co_email = $getCo->email;
        $fcm_token = $getCo->fcm_token;

        $getCwoUser = User::select('id', 'email', 'fcm_token')->where('cwo_id', $cwo_id)->where('is_active', 1)->get();
        // print_r($getCwoUser->toArray());exit;
        // exit;
        /*send mail to CWO starts*/
        // if($cwo_email != ''){
            $subject_cwo = 'Autoclick App - Car Pre Booking';
            // $message_body_cwo = '<html>
            //                     <head>
            //                     <title>Autoclick Car Pre Booking</title>
            //                     </head>
            //                     <body>
            //                         <p>Hi ' . $cwo_company . '</p>
            //                         <p>A Pre booking has been added. Following are the Details.</p>
            //                         <p>Car Registration No.: ' . $car_registration_no . '</p>
            //                         <p>Body Type: ' . $body_type . '</p>
            //                         <p>Name: ' . $name . '</p>
            //                         <p>Phone: +' . $isd_code . $phone_no . '</p>
            //                         <p>Date: ' . $date . '</p>
            //                         <p>Time: ' . $time . '</p>
            //                         <p>Adrees: ' . $address . '</p>
            //                         <p>Total Amount: ' . $currency . $total_amount . '</p>
            //                         <p>Please go to your CWO App and accept/decline the booking.</p>
            //                         <p>Regards</p>
            //                         <p>AUTOCLICK</p>
            //                         <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
            //                     </body>
            //                 </html>';
            $message_body_cwo = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $cwo_company . '</p>
                                    <p>You have received a new car wash booking request from a client. Please log in to the app to accept or decline under My Bookings.</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';               
            // echo $message_body_cwo;exit;
            if($getCwoUser != ''){
                foreach($getCwoUser as $u){
                    if($u->email != ''){                
                        $email_cwo = sendMail(array($cwo_company, $u->email), $message_body_cwo, $subject_cwo);
                        // print_r($email_cwo);exit;
                    }
                }
            }
        // }
        /*send mail to CWO ends*/

        /*send mail to CO starts*/
        if($co_email != ''){
            $subject_co = 'Autoclick App - Car Pre Booking';
            $message_body_co = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $co_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been added at  ' . $cwo_company . '.  Following are the Details.</p>
                                    <p>CWO Company: ' . $cwo_company . '</p>
                                    <p>Car Registration No.: ' . $car_registration_no . '</p>
                                    <p>Body Type: ' . $body_type . '</p>
                                    <p>Name: ' . $name . '</p>
                                    <p>Phone: +' . $isd_code . $phone_no . '</p>
                                    <p>Date: ' . $date . '</p>
                                    <p>Time: ' . $time . '</p>
                                    <p>Adrees: ' . $address . '</p>
                                    <p>Total Amount: ' . $currency . $total_amount . '</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body_co;exit;
            $email_co = sendMail(array($co_name, $co_email), $message_body_co, $subject_co);
            // print_r($email_co);exit;
        }
        /*send mail to CO ends*/

        /*push starts*/
        if($getCwoUser != ''){
            $notification_title = 'Autoclick Car Pre Booking';
            // $notification_body = 'Pre-booking for a car ' . $car_registration_no . ' has been added at ' . $cwo_company;
            $notification_body = 'You have received a new car wash booking request from a client. Please log in to the app to accept or decline under My Bookings.';
            // echo $notification_title . ' ->' . $notification_body;exit;
            foreach($getCwoUser as $u){
                if($u->fcm_token != ''){
                    $data=array("request_type" => "notification");
                    sendFcmNotificationForCwo($u->fcm_token, $notification_title, $notification_body, $data);
                }
            }
        }
        /*push ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre-booking has been added successfully. We will contact you shortly.',
            'prebooking_id' => $prebooking_id
        ]);

    }

    public function list_withoutNewLoyaltyPoints(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $co_id = $request->input('co_id');

        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;


        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'pre_bookings.discount', 'currency_masters.symbol', 'cwo_master.cwo_company', 'cwo_master.address as cwo_address', 'cwo_master.cwo_isd', 'cwo_master.cwo_phone', 'cwo_master.cwo_email', 'pre_booking_types.type', 'co_car.make', 'co_car.car_model', 'co_car.vehicle_color', 'pre_bookings.is_free_wash', 'cwo_master.lat', 'cwo_master.long', 'pre_bookings.cwo_id', 'pre_bookings.prebooking_type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            // ->where('pre_bookings.co_id', $cwo_id)
            ->where(function($query) use ($co_phone, $co_id) {
                $query->where('pre_bookings.co_id', $co_id)
                    ->orWhere('pre_bookings.phone_no', $co_phone);
            });
        // $data = $data->orderBy('pre_bookings.id', 'desc');
        $data = $data->orderBy('pre_bookings.date_time', 'desc');
        $dataCount = $data->count();
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['prebooking_type_id'] = $d->prebooking_type;
                $dataDisplay['prebooking_type'] = $d->type;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone_no'] = $d->phone_no;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }
                $dataDisplay['date_time'] = $d->date_time;
                $dataDisplay['address'] = $d->address;
                $dataDisplay['body_type_id'] = $d->body_type_id;
                $dataDisplay['body_type'] = $d->body_type;
                $dataDisplay['amount'] = $d->amount;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['discount_value_in_percentage'] = $d->discount;
                if($d->is_free_wash == 1) {
                    $dataDisplay['is_free_wash'] = true;
                }
                if($d->is_free_wash == 0) {
                    $dataDisplay['is_free_wash'] = false;
                }
                $dataDisplay['status_id'] = $d->status;
                if($d->status == 0) {
                    $dataDisplay['status'] = 'In-Queue';
                }
                if($d->status == 1) {
                    $dataDisplay['status'] = 'In Wash Bay';
                }
                if($d->status == 2) {
                    $dataDisplay['status'] = 'Finishing Bay';
                }
                if($d->status == 3) {
                    $dataDisplay['status'] = 'Car Wash Completed';
                }
                if($d->status == 4) {
                    $dataDisplay['status'] = 'Wash Cancelled';
                }
                if($d->status == 5) {
                    $dataDisplay['status'] = 'Keys Collected';
                }
                if($d->status == 6) {
                    $dataDisplay['status'] = 'Pending';
                }
                if($d->status == 7) {
                    $dataDisplay['status'] = 'Confirmed';
                }
                if($d->status == 8) {
                    $dataDisplay['status'] = 'Declined';
                }
                $dataDisplay['car_id'] = $d->car_id;
                $dataDisplay['car_registration_no'] = $d->car_registration_no;
                $dataDisplay['make'] = $d->make;
                $dataDisplay['car_model'] = $d->car_model;
                $dataDisplay['vehicle_color'] = $d->vehicle_color;
                $dataDisplay['co_id'] = $d->co_id;
                if($d->symbol != '') {
                    $dataDisplay['currency'] = $d->symbol;
                } else {
                    $dataDisplay['currency'] = 'R';
                }
                $dataDisplay['cwo_id'] = $d->cwo_id;
                $dataDisplay['cwo_company'] = $d->cwo_company;
                $dataDisplay['cwo_address'] = $d->cwo_address;
                $dataDisplay['cwo_isd'] = $d->cwo_isd;
                $dataDisplay['cwo_phone'] = $d->cwo_phone;
                $dataDisplay['cwo_email'] = $d->cwo_email;
                $dataDisplay['lat'] = $d->lat;
                $dataDisplay['long'] = $d->long;

                $wash_types = WashTypeToWash::select('wash_type_to_washes.wash_type_id', 'wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $d->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
                $dataDisplay['wash_types'] = $wash_types;

                $optionalExtra = OptionalExtra::where('prebooking_id', $d->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
                $dataDisplay['extras'] = $optionalExtra;

                $dataArray[] = $dataDisplay;
            }
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'preBookingCount' => $dataCount,
            'preBookingList' => $dataArray
        ]);
    }

    public function list(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $co_id = $request->input('co_id');

        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;


        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'pre_bookings.discount', 'currency_masters.symbol', 'cwo_master.cwo_company', 'cwo_master.address as cwo_address', 'cwo_master.cwo_isd', 'cwo_master.cwo_phone', 'cwo_master.cwo_email', 'pre_booking_types.type', 'co_car.make', 'co_car.car_model', 'co_car.vehicle_color', 'pre_bookings.is_free_wash', 'cwo_master.lat', 'cwo_master.long', 'pre_bookings.cwo_id', 'pre_bookings.prebooking_type', 'pre_bookings.used_loyalty_point', 'pre_bookings.used_loyalty_to_zar', 'pre_bookings.loyalty_type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            // ->where('pre_bookings.co_id', $cwo_id)
            ->where(function($query) use ($co_phone, $co_id) {
                $query->where('pre_bookings.co_id', $co_id)
                    ->orWhere('pre_bookings.phone_no', $co_phone);
            });
        // $data = $data->orderBy('pre_bookings.id', 'desc');
        $data = $data->orderBy('pre_bookings.date_time', 'desc');
        $dataCount = $data->count();
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['prebooking_type_id'] = $d->prebooking_type;
                $dataDisplay['prebooking_type'] = $d->type;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone_no'] = $d->phone_no;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }
                $dataDisplay['date_time'] = $d->date_time;
                $dataDisplay['address'] = $d->address;
                $dataDisplay['body_type_id'] = $d->body_type_id;
                $dataDisplay['body_type'] = $d->body_type;
                $dataDisplay['amount'] = $d->amount;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['discount_value_in_percentage'] = $d->discount;
                if($d->is_free_wash == 1) {
                    $dataDisplay['is_free_wash'] = true;
                }
                if($d->is_free_wash == 0) {
                    $dataDisplay['is_free_wash'] = false;
                }
                $dataDisplay['status_id'] = $d->status;
                if($d->status == 0) {
                    $dataDisplay['status'] = 'In-Queue';
                }
                if($d->status == 1) {
                    $dataDisplay['status'] = 'In Wash Bay';
                }
                if($d->status == 2) {
                    $dataDisplay['status'] = 'Finishing Bay';
                }
                if($d->status == 3) {
                    $dataDisplay['status'] = 'Car Wash Completed';
                }
                if($d->status == 4) {
                    $dataDisplay['status'] = 'Wash Cancelled';
                }
                if($d->status == 5) {
                    $dataDisplay['status'] = 'Keys Collected';
                }
                if($d->status == 6) {
                    $dataDisplay['status'] = 'Pending';
                }
                if($d->status == 7) {
                    $dataDisplay['status'] = 'Confirmed';
                }
                if($d->status == 8) {
                    $dataDisplay['status'] = 'Declined';
                }
                $dataDisplay['car_id'] = $d->car_id;
                $dataDisplay['car_registration_no'] = $d->car_registration_no;
                $dataDisplay['make'] = $d->make;
                $dataDisplay['car_model'] = $d->car_model;
                $dataDisplay['vehicle_color'] = $d->vehicle_color;
                $dataDisplay['co_id'] = $d->co_id;
                if($d->symbol != '') {
                    $dataDisplay['currency'] = $d->symbol;
                } else {
                    $dataDisplay['currency'] = 'R';
                }
                $dataDisplay['cwo_id'] = $d->cwo_id;
                $dataDisplay['cwo_company'] = $d->cwo_company;
                $dataDisplay['cwo_address'] = $d->cwo_address;
                $dataDisplay['cwo_isd'] = $d->cwo_isd;
                $dataDisplay['cwo_phone'] = $d->cwo_phone;
                $dataDisplay['cwo_email'] = $d->cwo_email;
                $dataDisplay['lat'] = $d->lat;
                $dataDisplay['long'] = $d->long;

                $wash_types = WashTypeToWash::select('wash_type_to_washes.wash_type_id', 'wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $d->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
                $dataDisplay['wash_types'] = $wash_types;

                $optionalExtra = OptionalExtra::where('prebooking_id', $d->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
                $dataDisplay['extras'] = $optionalExtra;

                $dataDisplay['used_loyalty_point'] = $d->used_loyalty_point;
                $dataDisplay['used_loyalty_to_zar'] = $d->used_loyalty_to_zar;
                $dataDisplay['loyalty_type'] = $d->loyalty_type;
                if($d->loyalty_type == null) {
                    $dataDisplay['loyalty_type'] = '';
                }

                $dataArray[] = $dataDisplay;
            }
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'preBookingCount' => $dataCount,
            'preBookingList' => $dataArray
        ]);
    }

    public function prebookingTypes(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'cwo_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $cwo_id = $request->input('cwo_id');

        $cwo_detail = CarWashOwner::select('allow_prebooking')->where('id', $cwo_id)->first();
        $allow_prebooking = $cwo_detail->allow_prebooking;
        $dataArray = [];
        if($allow_prebooking == 1) {
            $prebookingTypes = CwoPreBookingType::select('cwo_pre_booking_types.prebooking_type_id', 'pre_booking_types.type')
                            ->join('pre_booking_types', 'pre_booking_types.id', 'cwo_pre_booking_types.prebooking_type_id')
                            ->orderBy('pre_booking_types.id', 'asc')
                            ->where('cwo_pre_booking_types.cwo_id', $cwo_id)
                            ->get();
            $dataArray = $prebookingTypes;                
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'allow_prebooking' => $allow_prebooking,
            'preBookingType' => $dataArray
        ]);
    }

    public function getCars(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required',
            ],
            [
                'co_id.required' => 'Please enter car owner id',
            ]
        );
        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $co_id = $request->input('co_id');
        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;

        /*$dataC = CarOwnerCar::select('wash_details.car_id', 'co_car.id as car_id')
        ->distinct()
        ->join('co_master','co_master.id','=','co_car.co_id')
        ->leftJoin('wash_details','wash_details.car_id','=','co_car.id')
        ->where('co_car.is_display', 1)
        ->where(function($query) use ($co_phone, $co_id) {
            $query->where('wash_details.driver_phone', $co_phone)
                ->orWhere('co_car.co_id', $co_id);
        })
        ->get()
        ->count();
        // echo $dataC;*/

        $data = CarOwnerCar::select('wash_details.car_id', 'co_car.id as car_id')
        ->distinct()
        ->join('co_master','co_master.id','=','co_car.co_id')
        ->leftJoin('wash_details','wash_details.car_id','=','co_car.id')
        // ->where('co_car.is_display', 1)
        ->where(function($query) use ($co_phone, $co_id) {
            $query->where('wash_details.driver_phone', $co_phone)
                ->orWhere('co_car.co_id', $co_id);
        })
        ->orderBy('co_car.wash_status_update_datetime', 'desc');
        $data = $data->get();
        // print_r($data->toArray());exit;

        $dataDisplay=[];
        $dataArray = [];
        if($data != ''){
            foreach ($data as $d) {
                $carDetails = CarOwnerCar::findorfail($d->car_id);
                $dataDisplay['car_id'] = $d->car_id;
                $dataDisplay['car_registration_no'] = $carDetails->car_registration_no;
                $dataDisplay['body_type_id'] = $carDetails->body_type_id;
                if($carDetails->body_type_id > 0){
                    $getBodyType = BodyType::where('id', $carDetails->body_type_id)->select('name')->first();
                    $dataDisplay['body_type'] = $getBodyType->name;
                } else {
                    $dataDisplay['body_type'] = '';
                }
                
                $dataDisplay['make'] = $carDetails->make;
                $dataDisplay['car_model'] = $carDetails->car_model;
                $dataDisplay['vehicle_color'] = $carDetails->vehicle_color;

                $dataArray[] = $dataDisplay;
            }
        }

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            // 'count' => $dataC,
            'carList' => $dataArray
        ]);

    }

    public function getLoyalty_withoutNewLoyaltyPoints(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'isd_code' => 'required',
                'phone_no' => 'required',
                'cwo_id' => 'required',
            ]
        );
        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $cwo_id = $request->input('cwo_id');

        $is_free_wash = false;
        $loyalty_name = '';
        $no_of_paid_wash = '';
        $loyalty_type = '';
        $loyalty_type_text = '';
        $discount_value_in_percentage = '';
        $getLoyalty = Loyalty::where('cwo_id', $cwo_id)->where('is_active', 1)->first();
        if($getLoyalty != ''){
            $no_of_paid_wash = $getLoyalty->no_of_paid_wash;
            $loyalty_name = $getLoyalty->loyalty_name;
            $loyalty_type = $getLoyalty->loyalty_type;
            if($loyalty_type == 1){
                $loyalty_type_text = "Free Wash";
            }
            if($loyalty_type == 2){
                $loyalty_type_text = "Price Discount";
            }
            $discount_value_in_percentage = $getLoyalty->discount_value;
            $getWash = WashDetail::where('driver_isd_code', $isd_code)
                                    ->where('driver_phone', $phone_no)
                                    ->where('cwo_id', $cwo_id)
                                    // ->where('is_free_wash', 0)
                                    // ->where('status', 3)
                                    ->where('is_loyalty_utilized', 0)
                                    ->where(function($query) {
                                        $query->where('status', 3)
                                            ->orWhere('status', 5);
                                        });
            $getWashCount = $getWash->count();
            if($getWashCount >= $no_of_paid_wash){
                $is_free_wash = true;    
            }
        }

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'is_free_wash' => $is_free_wash,
            'loyalty_name' => $loyalty_name,
            'loyalty_type' => $loyalty_type,
            'loyalty_type_text' => $loyalty_type_text,
            'no_of_paid_wash' => $no_of_paid_wash,
            'discount_value_in_percentage' => $discount_value_in_percentage
        ]);

    }

    public function getLoyalty(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'isd_code' => 'required',
                'phone_no' => 'required',
                'cwo_id' => 'required',
            ]
        );
        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $cwo_id = $request->input('cwo_id');
        $is_new_loyalty = $request->input('is_new_loyalty');
        $prebooking_id = $request->input('prebooking_id');
        $todayDate = date('Y-m-d');

        $is_free_wash = false;
        $loyalty_name = '';
        $no_of_paid_wash = '';
        $loyalty_type = '';
        $loyalty_type_text = '';
        $discount_value_in_percentage = '';
        if($is_new_loyalty != '') { // if new loyalty system exists
            $getLoyalty = Loyalty::where('cwo_id', $cwo_id)
                        ->where('is_active', 1)
                        ->whereDate('start_date', '<=', $todayDate)
                        ->whereDate('end_date', '>=', $todayDate)
                        ->first();
        } else {
            $getLoyalty = Loyalty::where('cwo_id', $cwo_id)->where('is_active', 1)->first();
        }
        if($getLoyalty != ''){
            $no_of_paid_wash = $getLoyalty->no_of_paid_wash;
            $loyalty_name = $getLoyalty->loyalty_name;
            $loyalty_type = $getLoyalty->loyalty_type;
            if($loyalty_type == 1){
                $loyalty_type_text = "Free Wash";
            }
            if($loyalty_type == 2){
                $loyalty_type_text = "Price Discount";
            }
            // if($is_new_loyalty != '') { // if new loyalty system exists
            if($loyalty_type == 3){
                $loyalty_type_text = "Loyalty Points";
            }
            // }
            $discount_value_in_percentage = $getLoyalty->discount_value;
            if($is_new_loyalty != '') { // if new loyalty system exists
                $nc = 0;
                $getWash = WashDetail::where('driver_isd_code', $isd_code)
                                        ->where('driver_phone', $phone_no)
                                        ->where('cwo_id', $cwo_id)
                                        // ->where('is_free_wash', 0)
                                        // ->where('status', 3)
                                        ->where('is_loyalty_utilized', 0)
                                        ->where(function($query) {
                                            $query->where('status', 3)
                                                ->orWhere('status', 5);
                                        });
                $getWash = $getWash->get();                        
                // echo "<pre>";print_r($getWash->toArray());
                if($getWash != '') {
                    foreach($getWash as $g) {
                        $getWashTypes = WashTypeToWash::select('wash_type_to_washes.wash_id', 'wash_type_to_washes.wash_type_id','wash_categories.eligible_for_free_wash')
                            ->join('wash_categories','wash_categories.id','=','wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.wash_id', $g->id)
                            ->get();
                        // echo "<pre>";print_r($getWashTypes->toArray());
                        if($getWashTypes != '') {
                            foreach($getWashTypes as $wc) {
                                if($wc->eligible_for_free_wash == 1) {
                                    // echo $wc->wash_id . "<br>";
                                    $nc++;
                                    break;    
                                }
                            }    
                        }
                    }
                }
                // echo $nc;
                $getWashCount = $nc;
                // exit; 
            } else {
                $getWash = WashDetail::where('driver_isd_code', $isd_code)
                                    ->where('driver_phone', $phone_no)
                                    ->where('cwo_id', $cwo_id)
                                    // ->where('is_free_wash', 0)
                                    // ->where('status', 3)
                                    ->where('is_loyalty_utilized', 0)
                                    ->where(function($query) {
                                        $query->where('status', 3)
                                            ->orWhere('status', 5);
                                        });
                $getWashCount = $getWash->count();
            }
            
            if($getWashCount >= $no_of_paid_wash){
                $is_free_wash = true;    
            }
            if($loyalty_type == 3){
                $is_free_wash = false;
            }
        }

        /*get total loyalty and loyalty to zar starts*/
        $getLoyaltyScore = LoyaltyScore::where('cwo_id', $cwo_id)
                        ->where('isd_code', $isd_code)
                        ->where('phone', $phone_no)
                        ->select('loyalty_point')
                        ->first();
        // echo "<pre>";print_r($getLoyaltyScore);exit;
        if($getLoyaltyScore != ''){
            $loyalty_point = $getLoyaltyScore->loyalty_point;
        } else {
            $loyalty_point = 0;
        } 

        if($is_new_loyalty != '') { // if new loyalty system exists
            // echo $prebooking_id;exit;
            if($prebooking_id != '') {
                // echo "1";exit;
                if($prebooking_id != 'null') {
                    // echo "2";exit;
                    if($prebooking_id != 0) {
                        // echo "3";exit;
                        $getUsed = LoyaltyScoreUsageLog::where('prebooking_id', $prebooking_id)->first();
                        if($getUsed != '') {
                            $used_loyalty_point = $getUsed->used_loyalty_point;
                            $loyalty_point = $loyalty_point + $used_loyalty_point;
                        } 
                    }   
                }
            }
        }

        if($is_new_loyalty != '') { // if new loyalty system exists
            if($prebooking_id != '') {
                if($prebooking_id != 'null') {
                    if($prebooking_id != 0) {
                        $getAdded = LoyaltyScoreAddLog::where('prebooking_id', $prebooking_id)->first();
                        if($getAdded != '') {
                            $added_loyalty_point = $getAdded->added_loyalty_point;
                            $loyalty_point = $loyalty_point - $added_loyalty_point;
                        }
                    }
                }
            }
        }

        $getLoyaltyToZar = LoyaltyPointToZar::where('cwo_id', $cwo_id)->select('loyalty_point', 'zar_value')->first();
        if($getLoyaltyToZar != ''){
            $cwo_loyalty_point = $getLoyaltyToZar->loyalty_point;
            $zar_value = $getLoyaltyToZar->zar_value;
            $loyalty_to_zar = $zar_value / $cwo_loyalty_point;
        } else {
            $loyalty_to_zar = '';
        }
        /*get total loyalty and loyalty to zar starts*/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'is_free_wash' => $is_free_wash,
            'loyalty_name' => $loyalty_name,
            'loyalty_type' => $loyalty_type,
            'loyalty_type_text' => $loyalty_type_text,
            'no_of_paid_wash' => $no_of_paid_wash,
            'discount_value_in_percentage' => $discount_value_in_percentage,
            'total_loyalty_points' => $loyalty_point,
            'loyalty_to_zar' => $loyalty_to_zar
        ]);

    }

    public function detail_withoutNewLoyaltyPoints(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');

        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'currency_masters.symbol', 'pre_booking_types.type', 'pre_bookings.discount', 'co_car.make', 'co_car.car_model', 'co_car.vehicle_color', 'pre_bookings.is_free_wash', 'pre_bookings.cwo_id', 'pre_bookings.lat', 'pre_bookings.long')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('pre_bookings.id', $prebooking_id)
            ->first();
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        if($data != '') {
            $dataDisplay['id'] = $data->id;
            $dataDisplay['prebooking_type'] = $data->type;
            $dataDisplay['name'] = $data->name;
            $dataDisplay['isd_code'] = $data->isd_code;
            $dataDisplay['phone_no'] = $data->phone_no;
            if($data->date != '') {
                $dataDisplay['date']  = date("d/m/Y", strtotime($data->date));
            } else {
                $dataDisplay['date']  = '';
            }
            if($data->time != '') {
                $dataDisplay['time']  = date("h:i a", strtotime($data->time));
            } else {
                $dataDisplay['time']  = '';
            }
            $dataDisplay['date_time'] = $data->date_time;
            $dataDisplay['address'] = $data->address;
            if($data->lat == null) {
                $dataDisplay['lat'] = '';
            } else {
                $dataDisplay['lat'] = $data->lat;
            }
            if($data->long == null) {
                $dataDisplay['long'] = '';
            } else {
                $dataDisplay['long'] = $data->long;
            }
            $dataDisplay['body_type_id'] = $data->body_type_id;
            $dataDisplay['body_type'] = $data->body_type;
            $dataDisplay['amount'] = $data->amount;
            $dataDisplay['total_amount'] = $data->total_amount;
            $dataDisplay['discount_value_in_percentage'] = $data->discount;
            if($data->is_free_wash == 1) {
                $dataDisplay['is_free_wash'] = true;
            }
            if($data->is_free_wash == 0) {
                $dataDisplay['is_free_wash'] = false;
            }
            $dataDisplay['status_id'] = $data->status;
            if($data->status == 0) {
                $dataDisplay['status'] = 'In-Queue';
            }
            if($data->status == 1) {
                $dataDisplay['status'] = 'In Wash Bay';
            }
            if($data->status == 2) {
                $dataDisplay['status'] = 'Finishing Bay';
            }
            if($data->status == 3) {
                $dataDisplay['status'] = 'Car Wash Completed';
            }
            if($data->status == 4) {
                $dataDisplay['status'] = 'Wash Cancelled';
            }
            if($data->status == 5) {
                $dataDisplay['status'] = 'Keys Collected';
            }
            if($data->status == 6) {
                $dataDisplay['status'] = 'Pending';
            }
            if($data->status == 7) {
                $dataDisplay['status'] = 'Confirmed';
            }
            if($data->status == 8) {
                $dataDisplay['status'] = 'Declined';
            }
            $dataDisplay['car_id'] = $data->car_id;
            $dataDisplay['car_registration_no'] = $data->car_registration_no;
            $dataDisplay['make'] = $data->make;
            $dataDisplay['car_model'] = $data->car_model;
            $dataDisplay['vehicle_color'] = $data->vehicle_color;
            $dataDisplay['co_id'] = $data->co_id;
            if($data->symbol != '') {
                $dataDisplay['currency'] = $data->symbol;
            } else {
                $dataDisplay['currency'] = 'R';
            }
            $dataDisplay['cwo_id'] = $data->cwo_id;
            $wash_types = WashTypeToWash::select('wash_type_to_washes.wash_type_id', 'wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $data->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
            $dataDisplay['wash_types'] = $wash_types;

            $optionalExtra = OptionalExtra::where('prebooking_id', $data->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
            $dataDisplay['extras'] = $optionalExtra;
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'detail' => $dataDisplay
        ]);
    }

    public function detail(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');

        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.name', 'pre_bookings.isd_code', 'pre_bookings.phone_no', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.address', 'pre_bookings.body_type_id', 'pre_bookings.body_type', 'pre_bookings.amount', 'pre_bookings.total_amount', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'pre_bookings.co_id', 'currency_masters.symbol', 'pre_booking_types.type', 'pre_bookings.discount', 'co_car.make', 'co_car.car_model', 'co_car.vehicle_color', 'pre_bookings.is_free_wash', 'pre_bookings.cwo_id', 'pre_bookings.lat', 'pre_bookings.long', 'pre_bookings.used_loyalty_point', 'pre_bookings.used_loyalty_to_zar', 'pre_bookings.loyalty_type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('pre_bookings.id', $prebooking_id)
            ->first();
        // echo "<pre>";print_r($data->toArray());exit;   

        $dataDisplay=[];
        if($data != '') {
            $dataDisplay['id'] = $data->id;
            $dataDisplay['prebooking_type'] = $data->type;
            $dataDisplay['name'] = $data->name;
            $dataDisplay['isd_code'] = $data->isd_code;
            $dataDisplay['phone_no'] = $data->phone_no;
            if($data->date != '') {
                $dataDisplay['date']  = date("d/m/Y", strtotime($data->date));
            } else {
                $dataDisplay['date']  = '';
            }
            if($data->time != '') {
                $dataDisplay['time']  = date("h:i a", strtotime($data->time));
            } else {
                $dataDisplay['time']  = '';
            }
            $dataDisplay['date_time'] = $data->date_time;
            $dataDisplay['address'] = $data->address;
            if($data->lat == null) {
                $dataDisplay['lat'] = '';
            } else {
                $dataDisplay['lat'] = $data->lat;
            }
            if($data->long == null) {
                $dataDisplay['long'] = '';
            } else {
                $dataDisplay['long'] = $data->long;
            }
            $dataDisplay['body_type_id'] = $data->body_type_id;
            $dataDisplay['body_type'] = $data->body_type;
            $dataDisplay['amount'] = $data->amount;
            $dataDisplay['total_amount'] = $data->total_amount;
            $dataDisplay['discount_value_in_percentage'] = $data->discount;
            if($data->is_free_wash == 1) {
                $dataDisplay['is_free_wash'] = true;
            }
            if($data->is_free_wash == 0) {
                $dataDisplay['is_free_wash'] = false;
            }
            $dataDisplay['status_id'] = $data->status;
            if($data->status == 0) {
                $dataDisplay['status'] = 'In-Queue';
            }
            if($data->status == 1) {
                $dataDisplay['status'] = 'In Wash Bay';
            }
            if($data->status == 2) {
                $dataDisplay['status'] = 'Finishing Bay';
            }
            if($data->status == 3) {
                $dataDisplay['status'] = 'Car Wash Completed';
            }
            if($data->status == 4) {
                $dataDisplay['status'] = 'Wash Cancelled';
            }
            if($data->status == 5) {
                $dataDisplay['status'] = 'Keys Collected';
            }
            if($data->status == 6) {
                $dataDisplay['status'] = 'Pending';
            }
            if($data->status == 7) {
                $dataDisplay['status'] = 'Confirmed';
            }
            if($data->status == 8) {
                $dataDisplay['status'] = 'Declined';
            }
            $dataDisplay['car_id'] = $data->car_id;
            $dataDisplay['car_registration_no'] = $data->car_registration_no;
            $dataDisplay['make'] = $data->make;
            $dataDisplay['car_model'] = $data->car_model;
            $dataDisplay['vehicle_color'] = $data->vehicle_color;
            $dataDisplay['co_id'] = $data->co_id;
            if($data->symbol != '') {
                $dataDisplay['currency'] = $data->symbol;
            } else {
                $dataDisplay['currency'] = 'R';
            }
            $dataDisplay['cwo_id'] = $data->cwo_id;
            $wash_types = WashTypeToWash::select('wash_type_to_washes.wash_type_id', 'wash_categories.wash_name', 'wash_type_to_washes.price')
                            ->join('wash_categories', 'wash_categories.id', '=', 'wash_type_to_washes.wash_type_id')
                            ->where('wash_type_to_washes.prebooking_id', $data->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
            $dataDisplay['wash_types'] = $wash_types;

            $optionalExtra = OptionalExtra::where('prebooking_id', $data->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
            $dataDisplay['extras'] = $optionalExtra;

            $dataDisplay['used_loyalty_point'] = $data->used_loyalty_point;
            $dataDisplay['used_loyalty_to_zar'] = $data->used_loyalty_to_zar;
            $dataDisplay['loyalty_type'] = $data->loyalty_type;
            if($data->loyalty_type == null) {
                $dataDisplay['loyalty_type'] = '';
            }
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'detail' => $dataDisplay
        ]);
    }

    public function update(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_type' => 'required',
                // 'co_id' => 'required',
                'name' => 'required',
                'isd_code' => 'required',
                'phone_no' => 'required',
                'date' => 'required',
                'time' => 'required',
                'address' => 'required',
                'car_id' => 'required',
                'body_type_id' => 'required',
                // 'cwo_id' => 'required',
                'wash_types' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');
        $prebooking_type = $request->input('prebooking_type');
        // $co_id = $request->input('co_id');
        $name = $request->input('name');
        $isd_code = $request->input('isd_code');
        $phone_no = $request->input('phone_no');
        $date = $request->input('date');
        $time = $request->input('time');
        $address = $request->input('address');
        $car_id = $request->input('car_id');
        $body_type_id = $request->input('body_type_id');
        // $cwo_id = $request->input('cwo_id');
        if($date != ''){
            $date = date("Y-m-d", strtotime($date));
        }
        if($time != ''){
            $time = date("H:i:s", strtotime($time));
        }
        $dt = Carbon::now();

        $is_free_wash = $request->input('is_free_wash');
        $free_wash_type_id = $request->input('free_wash_type_id');
        $loyalty_type = $request->input('loyalty_type'); // 1 or 2 (1=Free Wash, 2=Price Discount)
        // $no_of_paid_wash = $request->input('no_of_paid_wash'); 
        $discount_value_in_percentage = $request->input('discount_value_in_percentage');  
        if($discount_value_in_percentage == ''){
            $discount_value_in_percentage = 0;
        }

        $dob = $request->input('dob');
        if($dob != '') {
            $dob = date("Y-m-d", strtotime($dob)); 
        } else {
            $dob = NULL;
        }

        if($body_type_id != ''){
            $getBodyType = BodyType::where('id', $body_type_id)->select('name')->first();
            $body_type = $getBodyType->name;
        } else {
            $body_type_id = 0;
            $body_type = '';
        }

        $lat = $request->input('lat');
        $long = $request->input('long');

        $wash_types = $request->input('wash_types');
        $amount = 0; 
        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $amount = $amount + $getPrice->price;
                    } else {
                        $amount = $amount + 0;
                    }
                } // foreach ends
            } // if ends
        }
        $total_amount = $amount;*/
        if($is_free_wash == 'true'){ // true starts
            // echo "1";exit;
            $is_free_wash = 1;  
            // $amount = 0;  
            /*** free wash id logic starts ***/
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){  // if starts
                    if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                        if($loyalty_type == 1){ // if loyalty_type = 1 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $amount = $amount + 0;    
                                } else {
                                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                    if($getPrice != ''){
                                        $amount = $amount + $getPrice->price;
                                    } else {
                                        $amount = $amount + 0;
                                    }
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 1 ends
                        if($loyalty_type == 2){ // if loyalty_type = 2 starts
                            foreach ($wash_type_id_array as $e) { // foreach starts
                                // echo $e['wash_type_id'];exit;
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                                
                            } // foreach ends
                        } // if loyalty_type = 2 ends
                    } else { //*** if loyalty_type is blank in old version stick to free_wash_type_id
                        foreach ($wash_type_id_array as $e) {
                            // echo $e['wash_type_id'];exit;
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $amount = $amount + 0;    
                            } else {
                                $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                                if($getPrice != ''){
                                    $amount = $amount + $getPrice->price;
                                } else {
                                    $amount = $amount + 0;
                                }
                            }
                            
                        } // foreach ends
                    } // if loyalty type exists check ends
                } // if ends
            }
            /*** free wash id logic ends ***/
        } // true ends
        if($is_free_wash == 'false'){
            // echo "0";exit;
            $is_free_wash = 0; 
            /*if($getPrice != ''){
                $amount = $getPrice->price;
            } else {
                $amount = 0;
            }*/

            /*wash category add starts*/
            // $wash_types = $request->input('wash_types');
            if($wash_types != ''){
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){
                    foreach ($wash_type_id_array as $e) {
                        $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                        if($getPrice != ''){
                            $amount = $amount + $getPrice->price;
                        } else {
                            $amount = $amount + 0;
                        }
                    }
                }
            }
            /*wash category add ends*/
        }
        $dt = Carbon::now(); 
        $total_amount = $amount;

        $recordDetail = PreBooking::findOrFail($prebooking_id);
        $record_status = $recordDetail->status;
        if($record_status == 4) {
            $getWash = WashDetail::select('id')->where('prebooking_id', $prebooking_id)->first();
            if($getWash != ''){
                $wash_id = $getWash->id;
            } else {
                $wash_id = 0;
            }
        } else {
            $wash_id = 0;
        }

        $cwo_id = $recordDetail->cwo_id;
        $co_id = $recordDetail->co_id;
        /*update pre_bookings table starts*/
        $data = $recordDetail->update([
            'prebooking_type'=> $prebooking_type,
            // 'co_id'=> $co_id,
            'name'=> $name,
            'isd_code'=> $isd_code,
            'phone_no'=> $phone_no,
            'dob'=> $dob,
            'date'=> $date,
            'time'=> $time,
            'date_time'=> $date . ' ' . $time,
            'address'=> $address,
            'lat'=> $lat,
            'long'=> $long,
            'car_id'=> $car_id,
            'body_type_id'=> $body_type_id,
            'body_type'=> $body_type,
            // 'cwo_id'=> $cwo_id,
            'amount'=> $amount,
            'total_amount'=> $total_amount,
            'is_free_wash'=> $is_free_wash,
            'discount'=> $discount_value_in_percentage,
            // 'status'=> 1,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*update pre_bookings table ends*/

        /*extra add starts*/
        $extras = $request->input('extras');
        // echo $extras;exit;
        DB::delete("DELETE FROM `optional_extras` WHERE `prebooking_id` = " . $prebooking_id . "");
        if($extras != ''){
            $extra_array=json_decode($extras, true);
            if($extra_array != ""){
                // $extra_price = 0;
                foreach ($extra_array as $e) {
                    // $extra_json = json_encode($e);
                    // $extra_price = $extra_price + $e['price'];
                    $total_amount = $total_amount + $e['price'];
                    $addOptionalExtra = OptionalExtra::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_id'=> $wash_id,
                        'optional_extra'=> $e['optional_extra'],
                        'price'=> $e['price'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
                // $total_amount = $amount + $extra_price;
            }
        }
        /*extra add ends*/

        /*if loyalty type 2 exists starts*/
        if($loyalty_type != ""){
            if($loyalty_type == 2){
                $discount_amount = ($discount_value_in_percentage/100) * $total_amount;
                $total_amount = $total_amount - $discount_amount;
            }
        }
        /*if loyalty type 2 exists ends*/

        $record_prebooking = PreBooking::find($prebooking_id);
        $record_prebooking->total_amount = $total_amount;
        $record_prebooking->save();

        /*cleaner add starts*/
        /*$cleaners = $request->input('cleaners');
        if($cleaners != ''){
            $cleaner_array=json_decode($cleaners, true);
            if($cleaner_array != ""){
                foreach ($cleaner_array as $e) {
                    $assignCleaner = CleanerWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_id'=> $wash_id,
                        'cleaner_id'=> $e['cleaner_id'],
                        'description'=> $e['description'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }*/
        /*cleaner add ends*/

        /*wash category add starts*/
        $wash_types = $request->input('wash_types');
        DB::delete("DELETE FROM `wash_type_to_washes` WHERE `prebooking_id` = " . $prebooking_id . "");
        if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($is_free_wash == 1){ // if it is a free wash starts
                        if($loyalty_type != ""){ //*** if loyalty_type exists in new version
                            if($loyalty_type == 1){ // if loyalty_type = 1 starts
                                if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                    $wash_type_price = 0;
                                } else {
                                    if($getPrice != ''){
                                        $wash_type_price = $getPrice->price;
                                    } else {
                                        $wash_type_price = 0;
                                    }    
                                }
                            } // if loyalty_type = 1 ends
                            if($loyalty_type == 2){ // if loyalty_type = 2 starts
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }
                            } // if loyalty_type = 2 ends
                        } else {  //*** if loyalty_type is blank in old version stick to free_wash_type_id
                            if($free_wash_type_id != '' && $e['wash_type_id'] == $free_wash_type_id) {
                                $wash_type_price = 0;
                            } else {
                                if($getPrice != ''){
                                    $wash_type_price = $getPrice->price;
                                } else {
                                    $wash_type_price = 0;
                                }    
                            }
                        }
                        
                    } // if it is a free wash ends
                    if($is_free_wash == 0){ // if it is not a free wash starts
                        if($getPrice != ''){
                            $wash_type_price = $getPrice->price;
                        } else {
                            $wash_type_price = 0;
                        }
                    } // if it is not a free wash ends
                    
                    $assignWashType = WashTypeToWash::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_id'=> $wash_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }
        /*wash category add ends*/

        /*if($wash_types != ''){
            $wash_type_id_array=json_decode($wash_types, true);
            if($wash_type_id_array != ""){  // if starts
                foreach ($wash_type_id_array as $e) {
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $wash_type_price = $getPrice->price;
                    } else {
                        $wash_type_price = 0;
                    }
                    $assignWashType = WashTypeToPrebooking::create([
                        'prebooking_id'=> $prebooking_id,
                        'wash_type_id'=> $e['wash_type_id'],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                } // foreach ends
            } // if ends
        }*/

        /*if new loyalty system exists starts*/
        $is_new_loyalty = $request->input('is_new_loyalty');
        if($is_new_loyalty != '') { // is_new_loyalty starts
            // echo $is_new_loyalty;exit;// echo $loyalty_type;exit;
            $total_loyalty_points =  $request->input('total_loyalty_points');            
            $used_loyalty_point =  $request->input('used_loyalty_point');            
            $used_zar_value =  $request->input('used_zar_value');   
            // echo $total_loyalty_points . ' -> ' . $used_loyalty_point . '-> ' . $used_zar_value . '<br>';
            $record_prebooking->used_loyalty_point = $used_loyalty_point != '' ? $used_loyalty_point : 0;
            $record_prebooking->used_loyalty_to_zar = $used_zar_value != '' ? $used_loyalty_point : 0;
            $record_prebooking->save();
            DB::delete("DELETE FROM `loyalty_score_usage_logs` WHERE `prebooking_id` = " . $prebooking_id . "");
            DB::delete("DELETE FROM `loyalty_score_add_logs` WHERE `prebooking_id` = " . $prebooking_id . "");
            if($loyalty_type == 3) { // if loyalty type 3 starts
                if($total_loyalty_points != '' && $used_loyalty_point != '' && $used_zar_value != '') {
                    if($used_loyalty_point > 0) {
                        $remaining_loyalty_point =  $total_loyalty_points - $used_loyalty_point; 
                        // echo 'remaining-> ' . $remaining_loyalty_point;
                        $total_amount = $total_amount - $used_zar_value;
                        //update wash_deatils srtarts
                        $record_prebooking->used_loyalty_point = $used_loyalty_point;
                        $record_prebooking->used_loyalty_to_zar = $used_zar_value;
                        $record_prebooking->total_amount = $total_amount;
                        $record_prebooking->loyalty_type = $loyalty_type;
                        if($total_amount == 0){
                            $record_prebooking->payment_status = 1;
                            $record_prebooking->payment_details = 'Loyalty Points';
                        }
                        $record_prebooking->save();
                        //update wash_deatils ends

                        // loyalty_score_usage_logs starts
                        LoyaltyScoreUsageLog::create([
                            'prebooking_id'=> $prebooking_id,
                            'cwo_id'=> $cwo_id,
                            'co_id'=> $co_id,
                            'isd_code'=> $isd_code,
                            'phone'=> $phone_no,
                            'available_total_loyalty_point'=> $total_loyalty_points,
                            'used_loyalty_point'=> $used_loyalty_point,
                            'remaining_loyalty_point'=> $remaining_loyalty_point,
                            'used_date'=> date('Y-m-d'),
                            'created_at'=>$dt->toDayDateTimeString(),
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                        // loyalty_score_usage_logs ends 
                        // loyalty_scores data starts
                        $loyaltyData = LoyaltyScore::where('cwo_id', $cwo_id)
                                            ->where('isd_code', $isd_code)
                                            ->where('phone', $phone_no)
                                            ->first();
                        // echo "<pre>";print_r($loyaltyData);exit;
                        if($loyaltyData != ""){
                            // echo "loyalty row exists";exit;
                            // echo $remaining_loyalty_point;exit;
                            $loyaltyData->update([
                                'loyalty_point'=> $remaining_loyalty_point,
                                'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                        } else {
                            // echo "loyalty row does not exist";exit;
                            LoyaltyScore::create([
                                'cwo_id'=> $cwo_id,
                                'co_id'=> $co_id,
                                'isd_code'=> $isd_code,
                                'phone'=> $phone_no,
                                'loyalty_point'=> $remaining_loyalty_point,
                                'created_at'=>$dt->toDayDateTimeString(),
                                'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                        }
                        // loyalty_scores data ends
                        // loyalty_score_add_logs starts
                        // LoyaltyScoreAddLog::create([
                        //     'wash_id'=> $wash_id,
                        //     'cwo_id'=> $cwo_id,
                        //     'co_id'=> $co_id,
                        //     'isd_code'=> $isd_code,
                        //     'phone'=> $phone_no,
                        //     'available_total_loyalty_point'=> $total_loyalty_points,
                        //     'added_loyalty_point'=> $used_loyalty_point,
                        //     'total_loyalty_point'=> '',
                        //     'wash_entry_date'=> $today,
                        //     'created_at'=>$dt->toDayDateTimeString(),
                        //     'updated_at'=>$dt->toDayDateTimeString()
                        // ]);
                        // loyalty_score_add_logs ends  
                    }
                }        
            } // if loyalty type 3 ends
            // exit;

            if($wash_types != ''){
                $lpCount = 0;
                $wash_type_id_array=json_decode($wash_types, true);
                if($wash_type_id_array != ""){
                    foreach ($wash_type_id_array as $e) {
                        $getLoyaltyPoints = WashCategoryLoyaltyPoint::where('wash_category_id', $e['wash_type_id'])->where('body_type_id', $body_type_id)->first();
                        if($getLoyaltyPoints != ''){ // if loyalty points earn starts
                            $lpCount = $lpCount + $getLoyaltyPoints->loyalty_point;
                        } // if loyalty points earn ends
                    } // foreach ends
                    $getLoyaltyData = LoyaltyScore::where('cwo_id', $cwo_id)
                                    ->where('isd_code', $isd_code)
                                    ->where('phone', $phone_no)
                                    ->first();
                    if($getLoyaltyData != ""){
                        $existingLoyaltyPoint = $getLoyaltyData->loyalty_point;
                        $finalLoyaltyPoint = $existingLoyaltyPoint + $lpCount;
                        $getLoyaltyData->update([
                            'loyalty_point'=> $finalLoyaltyPoint,
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    } else {
                        $existingLoyaltyPoint = 0;
                        $finalLoyaltyPoint = $lpCount;
                        LoyaltyScore::create([
                            'cwo_id'=> $cwo_id,
                            'co_id'=> $co_id,
                            'isd_code'=> $isd_code,
                            'phone'=> $phone_no,
                            'loyalty_point'=> $finalLoyaltyPoint,
                            'created_at'=>$dt->toDayDateTimeString(),
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    } 
                    // loyalty_score_add_logs starts
                    if($lpCount > 0) {
                        LoyaltyScoreAddLog::create([
                            'prebooking_id'=> $prebooking_id,
                            'cwo_id'=> $cwo_id,
                            'co_id'=> $co_id,
                            'isd_code'=> $isd_code,
                            'phone'=> $phone_no,
                            'available_total_loyalty_point'=> $existingLoyaltyPoint,
                            'added_loyalty_point'=> $lpCount,
                            'total_loyalty_point'=> $finalLoyaltyPoint,
                            'wash_entry_date'=> date('Y-m-d'),
                            'created_at'=>$dt->toDayDateTimeString(),
                            'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    }
                    // loyalty_score_add_logs ends 
                } // if ends
            }                        
        } // is_new_loyalty ends
        /*if new loyalty system exists ends*/
        // exit;

        $getCwo = CarWashOwner::where('id', $cwo_id)->select('cwo_company', 'cwo_email', 'currency_id')->first();
        $cwo_company = $getCwo->cwo_company;
        $cwo_email = $getCwo->cwo_email;
        if($getCwo->currency_id != 0){
            $getCurrency = CurrencyMaster::findorfail($getCwo->currency_id);
            $currency = $getCurrency->symbol;
        } else {
            $currency = 'R';
        }

        $getCar = CarOwnerCar::where('id', $car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;

        $getCo = CarOwner::where('id', $co_id)->select('co_fname', 'co_lname', 'email')->first();
        if($name != '') {
            $co_name = $name;
        } else {
            $co_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $co_email = $getCo->email;

        /*send mail to CWO starts*/
        if($cwo_email != ''){
            $subject_cwo = 'Autoclick App - Car Pre Booking';
            // $message_body_cwo = '<html>
            //                     <head>
            //                     <title>Autoclick Car Pre Booking</title>
            //                     </head>
            //                     <body>
            //                         <p>Hi ' . $cwo_company . '</p>
            //                         <p>A Pre booking has been updated. Following are the Details.</p>
            //                         <p>Car Registration No.: ' . $car_registration_no . '</p>
            //                         <p>Body Type: ' . $body_type . '</p>
            //                         <p>Name: ' . $name . '</p>
            //                         <p>Phone: +' . $isd_code . $phone_no . '</p>
            //                         <p>Date: ' . $date . '</p>
            //                         <p>Time: ' . $time . '</p>
            //                         <p>Adrees: ' . $address . '</p>
            //                         <p>Total Amount: ' . $currency . $total_amount . '</p>
            //                         <p>Regards</p>
            //                         <p>AUTOCLICK</p>
            //                         <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
            //                     </body>
            //                 </html>';
            $message_body_cwo = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $cwo_company . '</p>
                                    <p>A car wash booking request from a clienthas been updated. Please log in to the app to accept or decline under My Bookings.</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';                 
            // echo $message_body_cwo;exit;
            // $email_cwo = sendMail(array($cwo_company, $cwo_email), $message_body_cwo, $subject_cwo);
            // print_r($email_cwo);exit;
        }
        /*send mail to CWO ends*/

        /*send mail to CO starts*/
        if($co_email != ''){
            $subject_co = 'Autoclick App - Car Pre Booking';
            $message_body_co = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking</title>
                                </head>
                                <body>
                                    <p>Hi ' . $co_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been updated at  ' . $cwo_company . '.  Following are the Details.</p>
                                    <p>CWO Company: ' . $cwo_company . '</p>
                                    <p>Car Registration No.: ' . $car_registration_no . '</p>
                                    <p>Body Type: ' . $body_type . '</p>
                                    <p>Name: ' . $name . '</p>
                                    <p>Phone: +' . $isd_code . $phone_no . '</p>
                                    <p>Date: ' . $date . '</p>
                                    <p>Time: ' . $time . '</p>
                                    <p>Adrees: ' . $address . '</p>
                                    <p>Total Amount: ' . $currency . $total_amount . '</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body_co;exit;
            // $email_co = sendMail(array($co_name, $co_email), $message_body_co, $subject_co);
            // print_r($email_co);exit;
        }
        /*send mail to CO ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre-booking has been updated successfully. We will contact you shortly.',
            'prebooking_id' => $prebooking_id
        ]);

    }

    public function cancel(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'prebooking_id' => 'required',
                'user_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }

        $prebooking_id = $request->input('prebooking_id');
        $user_id = $request->input('user_id');

        $record = PreBooking::find($prebooking_id);
        $record->status = 8;
        $record->declined_by_user_id = $user_id;
        $record->save();

        /*if new loyalty system exists starts*/
        $is_new_loyalty = $request->input('is_new_loyalty');
        if($is_new_loyalty != '') { // is_new_loyalty starts
            $isd_code = $record->isd_code;
            $phone_no = $record->phone_no;
            $cwo_id = $record->cwo_id;
            $dt = Carbon::now();
            if($isd_code != '' && $phone_no != ''){
                // echo "found";exit;
                $new_loyalty_point = 0;
                $loyaltyData = LoyaltyScore::where('cwo_id', $cwo_id)
                                    ->where('isd_code', $isd_code)
                                    ->where('phone', $phone_no)
                                    ->first();
                // echo "<pre>";print_r($loyaltyData);exit;
                if($loyaltyData != ''){
                    $existingLoyaltyPoint = $loyaltyData->loyalty_point;                    
                } else {
                    $existingLoyaltyPoint = 0;
                }
                // echo $existingLoyaltyPoint;exit;                 

                $getUsed = LoyaltyScoreUsageLog::where('prebooking_id', $prebooking_id)->first();
                if($getUsed != '') {
                    $used_loyalty_point = $getUsed->used_loyalty_point;
                    $new_loyalty_point = $existingLoyaltyPoint + $used_loyalty_point;
                    $loyaltyData->update([
                        'loyalty_point'=> $new_loyalty_point,
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    $getUsed->update([
                        'status'=> 0,
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }

                $getAdded = LoyaltyScoreAddLog::where('prebooking_id', $prebooking_id)->first();
                if($getAdded != '') {
                    $added_loyalty_point = $getAdded->added_loyalty_point;
                    if($new_loyalty_point > 0){
                                $final_loyalty_point = $new_loyalty_point - $added_loyalty_point;
                            } else {
                                $final_loyalty_point = 0;
                            }
                    $loyaltyData->update([
                        'loyalty_point'=> $final_loyalty_point,
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    $getAdded->update([
                        'status'=> 0,
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
        }

        /*if new loyalty system exists ends*/
        // exit;

        $getCwo = CarWashOwner::where('id', $record->cwo_id)->select('cwo_company')->first();
        $cwo_company = $getCwo->cwo_company;
        $getCar = CarOwnerCar::where('id', $record->car_id)->select('car_registration_no')->first();
        $car_registration_no = $getCar->car_registration_no;
        $getCo = CarOwner::where('id', $record->co_id)->select('co_fname', 'co_lname', 'email', 'fcm_token')->first();
        if($record->name != '') {
            $recipient_name = $record->name;
        } else {
            $recipient_name = $getCo->co_fname . ' ' . $getCo->co_lname;
        }
        $email = $getCo->email;
        $fcm_token = $getCo->fcm_token;

        /*send mail starts*/
        if($email != ''){
            $recipient_email = $email;
            // echo $recipient_email;exit;
            $subject = 'Autoclick App - Car Pre Booking Cancelled';
            $message_body = '<html>
                                <head>
                                <title>Autoclick Car Pre Booking Cancelled</title>
                                </head>
                                <body>
                                    <p>Hi ' . $recipient_name . '</p>
                                    <p>Pre booking for your car ' . $car_registration_no . ' has been declined at  ' . $cwo_company . '. Thank you!</p>
                                    <p>Regards</p>
                                    <p>AUTOCLICK</p>
                                    <p><a href="www.autoclickcarwashapp.com">www.autoclickcarwashapp.com</a> | <a href="mailto:info@autoclick.co.za">info@autoclick.co.za</a></p>
                                </body>
                            </html>';
            // echo $message_body;exit;
            $email = sendMail(array($recipient_name, $recipient_email), $message_body, $subject);
            // print_r($email);exit;
        }
        /*send mail ends*/

        /*push starts*/
        $notification_title = 'Autoclick Car Pre Booking Cancelled';
        $notification_body = 'Pre booking for your car ' . $car_registration_no . ' has been cancelled at ' . $cwo_company;
        // echo $notification_title . ' ->' . $notification_body;exit;
        $data=array("request_type" => "notification");
        sendFcmNotification($fcm_token, $notification_title, $notification_body, $data);
        /*push ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Pre booking has been cancelled.'
        ]);
    }

    public function upcoming(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'co_id' => 'required'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $co_id = $request->input('co_id');

        $coDetails = CarOwner::findorfail($co_id);
        $co_phone = $coDetails->co_phone;

        $currentTime = date('Y-m-d H:i:s');
        // echo $currentTime;exit;


        $data = PreBooking::select('pre_bookings.id', 'pre_bookings.date', 'pre_bookings.time', 'pre_bookings.date_time', 'pre_bookings.status', 'pre_bookings.car_id', 'co_car.car_registration_no', 'cwo_master.cwo_company', 'pre_booking_types.type')
            ->join('co_car', 'co_car.id', '=', 'pre_bookings.car_id')
            ->join('co_master', 'co_master.id', '=', 'pre_bookings.co_id')
            ->join('pre_booking_types', 'pre_booking_types.id', '=', 'pre_bookings.prebooking_type')
            ->join('cwo_master', 'cwo_master.id', '=', 'pre_bookings.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            // ->where('pre_bookings.status', '!=', 4)
            ->where('pre_bookings.status', '!=', 0)
            ->where('pre_bookings.status', '!=', 1)
            ->where('pre_bookings.status', '!=', 2)
            ->where('pre_bookings.status', '!=', 3)
            ->where('pre_bookings.status', '!=', 4)
            ->where('pre_bookings.status', '!=', 5)
            ->where('pre_bookings.status', '!=', 8)
            ->where('pre_bookings.date_time', '>', $currentTime)
            ->where(function($query) use ($co_phone, $co_id) {
                $query->where('pre_bookings.co_id', $co_id)
                    ->orWhere('pre_bookings.phone_no', $co_phone);
            })
            ->orderBy('pre_bookings.date_time', 'asc')
            ->take(1)
            ->get();
        // $data = $data->orderBy('pre_bookings.id', 'desc');
        // $dataCount = $data->count();
        // $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit;   

        // $dataDisplay=[];
        $dataDisplay = null;
        if(isset($data[0])) {
            $dataDisplay['id'] = $data[0]->id;
            $dataDisplay['prebooking_type'] = $data[0]->type;
            if($data[0]->date != '') {
                $dataDisplay['date']  = date("d/m/Y", strtotime($data[0]->date));
            } else {
                $dataDisplay['date']  = '';
            }
            if($data[0]->time != '') {
                $dataDisplay['time']  = date("h:i a", strtotime($data[0]->time));
            } else {
                $dataDisplay['time']  = '';
            }
            $dataDisplay['date_time'] = $data[0]->date_time;
            $dataDisplay['status_id'] = $data[0]->status;
            // if($data[0]->status == 1) {
            //     $dataDisplay['status'] = 'Pending';
            // }
            // if($data[0]->status == 2) {
            //     $dataDisplay['status'] = 'Confirmed';
            // }
            // if($data[0]->status == 3) {
            //     $dataDisplay['status'] = 'Cancelled';
            // }
            if($data[0]->status == 0) {
                $dataDisplay['status'] = 'In-Queue';
            }
            if($data[0]->status == 1) {
                $dataDisplay['status'] = 'In Wash Bay';
            }
            if($data[0]->status == 2) {
                $dataDisplay['status'] = 'Finishing Bay';
            }
            if($data[0]->status == 3) {
                $dataDisplay['status'] = 'Car Wash Completed';
            }
            if($data[0]->status == 4) {
                $dataDisplay['status'] = 'Wash Cancelled';
            }
            if($data[0]->status == 5) {
                $dataDisplay['status'] = 'Keys Collected';
            }
            if($data[0]->status == 6) {
                $dataDisplay['status'] = 'Pending';
            }
            if($data[0]->status == 7) {
                $dataDisplay['status'] = 'Confirmed';
            }
            if($data[0]->status == 8) {
                $dataDisplay['status'] = 'Declined';
            }
            $dataDisplay['car_id'] = $data[0]->car_id;
            $dataDisplay['car_registration_no'] = $data[0]->car_registration_no;
            $dataDisplay['cwo_company'] = $data[0]->cwo_company;
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'upcomingBookingList' => $dataDisplay
        ]);
    }


}
