<?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 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(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 = '';
        }

        $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,
            '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()
        ]);
        $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')->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 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>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 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*/

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

    }

    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')
            ->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');
        $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'] = $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 == 1) {
                    $dataDisplay['status'] = 'Pending';
                }
                if($d->status == 2) {
                    $dataDisplay['status'] = 'Confirmed';
                }
                if($d->status == 3) {
                    $dataDisplay['status'] = 'Declined';
                }
                if($d->status == 4) {
                    $dataDisplay['status'] = 'Wash Started';
                }
                $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_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;

                $wash_types = WashTypeToWash::select('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 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(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
        ]);

    }


}
