<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarWashOwner;
use App\Models\User;
use App\Models\CarOwner;
use App\Models\CarOwnerCar;
use App\Models\WashDetail;
use App\Models\BodyType;
use App\Models\WashCategoryBodyType;
use App\Models\OptionalExtra;
use App\Models\CleanerWash;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;
use Config;
use Hash;
use Auth;

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


    public function index()
    {
    }

    // public function manualEntry(Request $request){
    //     $validate = Validator::make($request->all(),
    //         [
    //             'cwo_id' => 'required',
    //             'car_registration_no' => 'required',
    //             'body_type' => 'required',
    //             'car_owner_name' => 'required',
    //             'phone' => 'required',
    //             // 'email' => 'required|email',
    //         ],[
    //             // 'email.unique' => 'This email already exists.'
    //         ]);

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

    //     $cwo_id = $request->input('cwo_id');
    //     $car_registration_no = $request->input('car_registration_no');
    //     $body_type = $request->input('body_type');
    //     $car_owner_name = $request->input('car_owner_name');
    //     $phone = $request->input('phone');
    //     $email = $request->input('email');
    //     $dt = Carbon::now();

    //     $getCoUser = User::where('phone', $phone)->first();
    //     // print_r($getCoUser->toArray());exit;
    //     if(!empty($getCoUser)){
    //         if($getCoUser->user_type == 3){
    //             $co_user_id = $getCoUser->id;
    //             $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
    //             $co_id = $co->id;
    //         } else {
    //             return response()->json([
    //                 'success' => 0,
    //                 'message' => 'This phone already exists for another user type'
    //             ]);
    //         }
    //     } else {
    //         /*insert into users table starts*/
    //         $insertUser = User::create([
    //             'name'=> $car_owner_name,
    //             'email'=> $email,
    //             'phone'=> $phone,
    //             'user_type'=> 3,
    //             'created_at'=>$dt->toDayDateTimeString(),
    //             'updated_at'=>$dt->toDayDateTimeString()
    //         ]);
    //         /*insert into users table ends*/
    //         $user_id = $insertUser->id;
    //         /*insert into co_master table starts*/
    //         $insertCo = CarOwner::create([
    //             'co_fname'=> $car_owner_name,
    //             'co_phone'=> $phone,
    //             'user_id'=> $user_id,
    //             'created_at'=>$dt->toDayDateTimeString(),
    //             'updated_at'=>$dt->toDayDateTimeString()
    //         ]);
    //         /*insert into co_master table ends*/
    //         $co_id = $insertCo->id;
    //     }
    //     // echo "Co ID-----------> " . $co_id . "<br>";

    //     /*insert into co_car table starts*/
    //     $checkCar = CarOwnerCar::where('car_registration_no', $car_registration_no)->first();
    //     if(!empty($checkCar)){
    //         $car_id = $checkCar->id;
    //     } else {
    //         $insertCar = CarOwnerCar::create([
    //             'car_registration_no'=> $car_registration_no,
    //             'body_type'=> $body_type,
    //             'co_id'=> $co_id,
    //             'created_at'=>$dt->toDayDateTimeString(),
    //             'updated_at'=>$dt->toDayDateTimeString()
    //         ]);
    //         /*insert into co_car table ends*/
    //         $car_id = $insertCar->id;
    //     }
    //     // echo "Car ID-----------> " . $car_id . "<br>";

    //     /*insert into wash_details table starts*/
    //     $insertWashDetail = WashDetail::create([
    //         'car_id'=> $car_id,
    //         'entry_date'=> date('Y-m-d'),
    //         'body_type'=> $body_type,
    //         'status'=> 0,
    //         'payment_status'=> 0,
    //         'created_at'=>$dt->toDayDateTimeString(),
    //         'updated_at'=>$dt->toDayDateTimeString()
    //     ]);
    //     /*insert into wash_details table ends*/
    //     $wash_detail_id = $insertWashDetail->id;

    //     return response()->json([
    //         'success' => 1,
    //         'message' => 'Success',
    //         'co_id' => $co_id,
    //         'car_id' => $car_id,
    //         'wash_detail_id' => $wash_detail_id,
    //     ]);

    // }

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

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

        $cwo_id = $request->input('cwo_id');
        // $start_date = $request->input('start_date'); // format -> yyyy-mm-dd, today or less than today
        // $end_date = $request->input('end_date'); // format -> yyyy-mm-dd, today
        // $today = date('Y-m-d');

        /***************** queue starts *********************/
        $carsInQueueList = WashDetail::select('wash_details.id', 'wash_details.car_id', 'wash_details.date_washed', 'wash_details.time_washed', 'wash_details.status', 'wash_details.payment_status', 'co_master.co_fname', 'co_master.co_lname', 'co_master.co_phone', 'co_car.car_registration_no', 'wash_categories.wash_name', 'wash_details.otp', 'wash_details.payment_details')
        ->join('co_car', 'co_car.id', '=', 'wash_details.car_id')
        ->join('co_master', 'co_master.id', '=', 'co_car.co_id')
        ->join('users', 'users.id', '=', 'co_master.user_id')
        ->join('wash_categories', 'wash_categories.id', '=', 'wash_details.wash_type_id')
        ->join('cwo_master', 'cwo_master.id', '=', 'wash_categories.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('wash_categories.cwo_id', $cwo_id)
        ->where('wash_details.status', 0);
        // if($start_date != '') {
        //     $carsInQueueList->whereDate('wash_details.date_washed', '>=', $start_date);
        // }
        // if($end_date != '') {
        //     $carsInQueueList->whereDate('wash_details.date_washed', '<=', $end_date);
        // }
        // $carsInQueueList = $carsInQueueList->orderBy('co_car.id', 'desc');
        $carsInQueueList = $carsInQueueList->orderBy('wash_details.id', 'desc');
        $carsInQueueCount = $carsInQueueList->count();
        $carsInQueueList = $carsInQueueList->get();


        // echo "<pre>";print_r($carsInQueueList->toArray());exit;
        /***************** queue ends *********************/

        $dataDisplay=[];
        $dataArray = [];
        if($carsInQueueList != '') {
            foreach ($carsInQueueList as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['car_id'] = $d->car_id;
                $dataDisplay['co_fname'] = $d->co_fname;
                $dataDisplay['co_lname'] = $d->co_lname;
                $dataDisplay['co_phone'] = $d->co_phone;
                $dataDisplay['car_registration_no'] = $d->car_registration_no;
                $dataDisplay['wash_name'] = $d->wash_name;
                if($d->date_washed != '') {
                    $dataDisplay['date_washed']  = date("d/m/Y", strtotime($d->date_washed));
                } else {
                    $dataDisplay['date_washed']  = '';
                }
                if($d->time_washed != '') {
                    $dataDisplay['time_washed']  = date("h:i a", strtotime($d->time_washed));
                } else {
                    $dataDisplay['time_washed']  = '';
                }
                $dataDisplay['payment_status_id'] = $d->payment_status;
                if($d->payment_status == 1) {
                    $dataDisplay['payment_status'] = 'Paid';
                } else {
                    $dataDisplay['payment_status'] = 'Not Paid';
                }
                $dataDisplay['status_id'] = $d->status;
                if($d->status == 0) {
                    $dataDisplay['status'] = 'Car in-queue';
                }
                if($d->status == 1) {
                    $dataDisplay['status'] = 'Car Wash Started';
                }
                if($d->status == 2) {
                    $dataDisplay['status'] = 'Drying';
                }
                if($d->status == 3) {
                    $dataDisplay['status'] = 'Car Wash Completed';
                }
                if($d->status == 4) {
                    $status = 'Cancelled';
                }
                $dataDisplay['otp'] = $d->otp;
                $dataDisplay['payment_mode'] = $d->payment_details;
                $optionalExtra = OptionalExtra::where('wash_id', $d->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
                $dataDisplay['extras'] = $optionalExtra;

                $cleaners = CleanerWash::select('cleaner_masters.name', 'cleaner_washes.description as cleaning_description')
                            ->join('cleaner_masters', 'cleaner_masters.id', '=', 'cleaner_washes.cleaner_id')
                            ->where('cleaner_washes.wash_id', $d->id)
                            ->orderBy('cleaner_washes.id', 'asc')
                            ->get();
                $dataDisplay['cleaners'] = $cleaners;

                $dataArray[] = $dataDisplay;
            }
        }

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'carsInQueueCount' => $carsInQueueCount,
            'carsInQueueList' => $dataArray
        ]);

    }

    public function getBodyTypes(Request $request)
    {

        $body_types = BodyType::where('status', 1)->orderBy('id', 'asc')->select('id', 'name')->get();

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'body_types' => $body_types
        ]);

    }

    public function manualEntry(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'car_registration_no' => 'required',
            ],
            [
                // 'email.unique' => 'This email already exists.'
            ]
        );

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

        $checkCar = CarOwnerCar::where('car_registration_no', $car_registration_no)->first();
        // print_r($checkCar->toArray());exit;
        $getCo = [];
        if(!empty($checkCar)) {
            $getCo = CarOwner::where('id', $checkCar->co_id)->first();
            $success = 1;
            $message = 'Success';
        } else { // insert the car
            $body_type_id = $request->input('body_type_id');
            if($body_type_id != '') {
                $getBodyType = BodyType::where('id', $body_type_id)->select('name')->first();
                if($getBodyType != '') {
                    $body_type = $getBodyType->name;
                } else {
                    $body_type_id = 0;
                    $body_type = '';
                }

            } else {
                $body_type_id = 0;
                $body_type = '';
            }
            $dt = Carbon::now();
            /*insert into co_car table starts*/
            $insertCar = CarOwnerCar::create([
                'car_registration_no'=> $car_registration_no,
                'body_type'=> $body_type,
                'body_type_id'=> $body_type_id,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString()
            ]);
            /*insert into co_car table ends*/
            $checkCar = CarOwnerCar::where('id', $insertCar->id)->first();
            $success = 1;
            // $message = 'Car registration no. does not exist.';
            $message = 'Success';
        }


        if($checkCar->image) {
            $checkCar->image=asset('images/CarOwner') . '/' . $checkCar->image;
        }
        return response()->json([
            'success' => $success,
            'message' => $message,
            'car_details' => $checkCar,
            'car_owner_details' => $getCo,
        ]);

    }


    public function updateCarImage(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'id' => 'required',
            ],
            [
                 'id.required' => 'Please provide car detail  id.'
            ]
        );

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


        // co_car
        $id = $request->input('id');

        $checkCar = CarOwnerCar::where('id', $id)->first();

        $getCo = CarOwner::where('id', $checkCar->co_id)->first();




        $image = $checkCar->image;

        if ($request->hasFile('image') && $id) {
            $image = time() . '.' . $request->file('image')->extension();

            /***:- save new file -:***/
            $path = $request->file('image')->move(public_path('images/CarOwner/'), $image);


            /***:- delete old file -:***/

            $oldFile=public_path('images/CarOwner/') . $checkCar->image;
            if(file_exists($oldFile) && $checkCar->image!='') {
                unlink($oldFile);
            }

            /***:- update data -:***/
            $checkCar->update([
            'image'=>$image
            ]);

        }

        $checkCar = CarOwnerCar::where('id', $id)->first();
        $asset=asset('images/CarOwner/') . $checkCar->image;



        if($checkCar->image) {
            $checkCar->image=$asset;
        }


        return response()->json([
            'success' => 1,
            'message' =>'Success',
            'car_details' => $checkCar,
            'car_owner_details' => $getCo,
        ]);

    }

    public function addDriverDetails(Request $request)
    {

        $validate = Validator::make(
            $request->all(),
            [
                'name' => 'required',
                'car_id' => 'required',
            ],
            [
                // 'email.unique' => 'This email already exists.'
            ]
        );

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

        $name = $request->input('name');
        $phone = $request->input('phone');
        $email = $request->input('email');
        $car_id = $request->input('car_id');
        $dt = Carbon::now();
        $account_no = generateUniqueNumberCo();

        if($phone == '' && $email =='') {
            // echo "hello1";exit;
            /*insert into users table starts*/
            $insertUser = User::create([
                'name'=> $name,
                'user_type'=> 3,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString()
            ]);
            $user_id = $insertUser->id;
            /*insert into co_master table starts*/
            $insertCo = CarOwner::create([
                'co_fname'=> $name,
                'user_id'=> $user_id,
                'account_no'=> $account_no,
                'make'=> $request->has('make')?$request->make:null,
                'keytag'=> $request->has('keytag')?$request->keytag:null,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString()
            ]);
            /*insert into co_master table ends*/
            $co_id = $insertCo->id;
        }
        if($phone != '' && $email =='') {
            // echo "hello2";exit;
            $getCoUser = User::where('phone', $phone)->first();
            if(!empty($getCoUser)) { // if co phone no already exists
                if($getCoUser->user_type == 3) { // if co phone no already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $userDetails = User::findOrFail($user_id);
                    $co->update([
                        'co_fname'=> $name,
                        'co_lname'=> '',
                        // 'phone'=> $phone,
                        'make'=> $request->has('make')?$request->make:null,
                        'keytag'=> $request->has('keytag')?$request->keytag:null,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    $userDetails->update([
                        'name'=> $name,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);


                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This phone already exists for another user type'
                    ]);
                }
            } else { // if co phone no does not exists
                /*insert into users table starts*/
                $insertUser = User::create([
                    'name'=> $name,
                    'phone'=> $phone,
                    'user_type'=> 3,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into users table ends*/
                $user_id = $insertUser->id;

                /*insert into co_master table starts*/
                $insertCo = CarOwner::create([
                    'co_fname'=> $name,
                    'co_phone'=> $phone,
                    'user_id'=> $user_id,
                    'account_no'=> $account_no,
                    'make'=> $request->has('make')?$request->make:null,
                    'keytag'=> $request->has('keytag')?$request->keytag:null,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into co_master table ends*/
                $co_id = $insertCo->id;

            }
        }
        if($phone == '' && $email !='') {
            // echo "hello3";exit;
            $getCoUser = User::where('email', $email)->first();
            if(!empty($getCoUser)) { // if co email already exists
                if($getCoUser->user_type == 3) { // if co email already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $userDetails = User::findOrFail($user_id);
                    $co->update([
                        'co_fname'=> $name,
                        'co_lname'=> '',
                        'make'=> $request->has('make')?$request->make:null,
                        'keytag'=> $request->has('keytag')?$request->keytag:null,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    $userDetails->update([
                        'name'=> $name,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);


                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This email already exists for another user type'
                    ]);
                }
            } else { // if co email does not exists
                /*insert into users table starts*/
                $insertUser = User::create([
                    'name'=> $name,
                    'email'=> $email,
                    'user_type'=> 3,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into users table ends*/
                $user_id = $insertUser->id;

                /*insert into co_master table starts*/
                $insertCo = CarOwner::create([
                    'co_fname'=> $name,
                    'email'=> $email,
                    'user_id'=> $user_id,
                    'account_no'=> $account_no,
                    'make'=> $request->has('make')?$request->make:null,
                    'keytag'=> $request->has('keytag')?$request->keytag:null,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into co_master table ends*/
                $co_id = $insertCo->id;

            }
        }
        if($phone != '' && $email !='') {
            // echo "hello4";exit;
            $getCoUser = User::where('phone', $phone)->first();
            // print_r($getCoUser->toArray());exit;
            if(!empty($getCoUser)) { // if co phone no already exists
                if($getCoUser->user_type == 3) { // if co phone no already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $emailCheck = User::where('email', $email)->where('id', '!=', $user_id)->first();
                    if(!empty($emailCheck)) {
                        return response()->json([
                            'success' => 0,
                            'message' => 'This email already exists for another user'
                        ]);
                    } else {
                        $userDetails = User::findOrFail($user_id);
                        $co->update([
                            'co_fname'=> $name,
                            'co_lname'=> '',
                            'email'=> $email,
                            'make'=> $request->has('make')?$request->make:null,
                            'keytag'=> $request->has('keytag')?$request->keytag:null,
                            // 'phone'=> $phone,
                            'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                        $userDetails->update([
                            'name'=> $name,
                            'email'=> $email,
                            'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                    }

                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This phone already exists for another user type'
                    ]);
                }
            } else { // if co phone no does not exists
                $emailCheck = User::where('email', $email)->first();
                if(!empty($emailCheck)) {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This email already exists for another user'
                    ]);
                } else {
                    /*insert into users table starts*/
                    $insertUser = User::create([
                        'name'=> $name,
                        'email'=> $email,
                        'phone'=> $phone,
                        'user_type'=> 3,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    /*insert into users table ends*/
                    $user_id = $insertUser->id;

                    /*insert into co_master table starts*/
                    $insertCo = CarOwner::create([
                        'co_fname'=> $name,
                        'co_phone'=> $phone,
                        'email'=> $email,
                        'user_id'=> $user_id,
                        'account_no'=> $account_no,
                        'make'=> $request->has('make')?$request->make:null,
                        'keytag'=> $request->has('keytag')?$request->keytag:null,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    /*insert into co_master table ends*/
                    $co_id = $insertCo->id;
                }

            }
        }

        /*update co_car table starts*/
        $carDetails = CarOwnerCar::findOrFail($car_id);
        $carDetails->update([
            'co_id'=> $co_id,
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*update co_car table ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'co_id' => $co_id,
            'user_id' => $user_id
        ]);

    }


    public function scan(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'car_registration_no' => 'required',
                // 'car_model' => 'required',
                // 'body_type_id' => 'required',
                // 'control_no' => 'required',
                // 'make' => 'required',
                // 'engine_no' => 'required',
                // 'vin' => 'required',
                // 'license_expiry_date' => 'required',
            ],
            [
                // 'email.unique' => 'This email already exists.'
            ]
        );

        if($validate->fails()) {
            $errorString = implode(",", $validate->messages()->all());
            return response()->json([
                'success' => 0,
                'message' => $errorString,
            ]);
        }
        $car_registration_no = $request->input('car_registration_no');
        $car_model = $request->input('car_model');
        $body_type_id = $request->input('body_type_id');
        $control_no = $request->input('control_no');
        $make = $request->input('make');
        $keytag = $request->input('keytag');
        $engine_no = $request->input('engine_no');
        $vin = $request->input('vin');
        $license_expiry_date = $request->input('license_expiry_date');
        $co_id = 0;
        $dt = Carbon::now();

        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 = '';
        }
        if($license_expiry_date != '') {
            $license_expiry_date = date("Y-m-d", strtotime($license_expiry_date));
        }

        $checkCar = CarOwnerCar::where('car_registration_no', $car_registration_no)->first();
        // print_r($checkCar->toArray());exit;
        $getCo = [];
        if(!empty($checkCar)) {
            $getCo = CarOwner::where('id', $checkCar->co_id)->first();
            return response()->json([
                'success' => 1,
                'message' => 'Car registration no. already exists.',
                'car_id' => $checkCar->id,
                'car_registration_no'=> $car_registration_no,
                'car_details' => $checkCar,
                'car_owner_details' => $getCo,
            ]);
        } else {


            $image = '';

            if ($request->hasFile('image')) {
                $image = time() . '.' . $request->file('image')->extension();
                $path = $request->file('image')->move(public_path('images/CarOwner/'), $image);
            }

            /*insert into co_car table starts*/

            $carData=[
                'co_id'=> $co_id,
                'car_model'=> $car_model,
                'car_registration_no'=> $car_registration_no,
                'body_type'=> $body_type,
                'body_type_id'=> $body_type_id,
                'control_no'=> $control_no,
                'make'=> $make,
                'keytag'=> $keytag,
                'engine_no'=> $engine_no,
                'vin'=> $vin,
                'license_expiry_date'=> $license_expiry_date,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString(),
                'image'=>$image
            ];


            $insertCar = CarOwnerCar::create($carData);
            /*insert into co_car table ends*/
            $checkCar = CarOwnerCar::where('id', $insertCar->id)->first();
            return response()->json([
                'success' => 1,
                'message' => 'Success',
                'car_id' => $insertCar->id,
                'car_registration_no'=> $car_registration_no,
                'car_details' => $checkCar,
                'car_owner_details' => $getCo,
            ]);
        }
    }

    public function addBodyType(Request $request)
    {
        $validate = Validator::make(
            $request->all(),
            [
                'body_type_name' => 'required|unique:body_types,name',
                'wash_type_id' => 'required',
                'price' => 'required',
                'duration' => 'required'
            ]
        );

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

        $body_type_name = $request->input('body_type_name');
        $wash_type_id = $request->input('wash_type_id');
        $price = $request->input('price');
        $duration = $request->input('duration');
        $dt = Carbon::now();

        /*insert into body_types table starts*/
        $data = BodyType::create([
            'name'=> $body_type_name,
            'status'=> 1,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*insert into body_types table ends*/

        /*insert into wash_category_body_types table starts*/
        $body_type_id = $data->id;
        $dataCwo = WashCategoryBodyType::create([
            'wash_category_id'=> $wash_type_id,
            'body_type_id'=> $body_type_id,
            'price'=> $price,
            'duration'=> $duration,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*insert into wash_category_body_types table ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'body_type_id' => $body_type_id
        ]);

    }


    public function updateDriverDetails(Request $request)
    {

        $validate = Validator::make(
            $request->all(),
            [
                'name' => 'required',
                'car_id' => 'required',
            ],
            [
                // 'email.unique' => 'This email already exists.'
            ]
        );

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

        $name = $request->input('name');
        $phone = $request->input('phone');
        $email = $request->input('email');
        $car_id = $request->input('car_id');
        $dt = Carbon::now();

        if($phone == '' && $email =='') {
            /*insert into users table starts*/
            $insertUser = User::create([
                'name'=> $name,
                'user_type'=> 3,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString()
            ]);
            $user_id = $insertUser->id;
            /*insert into co_master table starts*/
            $insertCo = CarOwner::create([
                'co_fname'=> $name,
                'user_id'=> $user_id,
                'created_at'=>$dt->toDayDateTimeString(),
                'updated_at'=>$dt->toDayDateTimeString()
            ]);
            /*insert into co_master table ends*/
            $co_id = $insertCo->id;
        }
        if($phone != '' && $email =='') {
            $getCoUser = User::where('phone', $phone)->first();
            if(!empty($getCoUser)) { // if co phone no already exists
                if($getCoUser->user_type == 3) { // if co phone no already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $userDetails = User::findOrFail($user_id);
                    $co->update([
                        'co_fname'=> $name,
                        'co_lname'=> '',
                        // 'phone'=> $phone,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    $userDetails->update([
                        'name'=> $name,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);


                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This phone already exists for another user type'
                    ]);
                }
            } else { // if co phone no does not exists
                /*insert into users table starts*/
                $insertUser = User::create([
                    'name'=> $name,
                    'phone'=> $phone,
                    'user_type'=> 3,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into users table ends*/
                $user_id = $insertUser->id;

                /*insert into co_master table starts*/
                $insertCo = CarOwner::create([
                    'co_fname'=> $name,
                    'co_phone'=> $phone,
                    'user_id'=> $user_id,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into co_master table ends*/
                $co_id = $insertCo->id;

            }
        }
        if($phone == '' && $email !='') {
            $getCoUser = User::where('email', $email)->first();
            if(!empty($getCoUser)) { // if co email already exists
                if($getCoUser->user_type == 3) { // if co email already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $userDetails = User::findOrFail($user_id);
                    $co->update([
                        'co_fname'=> $name,
                        'co_lname'=> '',
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);
                    $userDetails->update([
                        'name'=> $name,
                        'updated_at'=>$dt->toDayDateTimeString()
                        ]);


                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This email already exists for another user type'
                    ]);
                }
            } else { // if co email does not exists
                /*insert into users table starts*/
                $insertUser = User::create([
                    'name'=> $name,
                    'email'=> $email,
                    'user_type'=> 3,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into users table ends*/
                $user_id = $insertUser->id;

                /*insert into co_master table starts*/
                $insertCo = CarOwner::create([
                    'co_fname'=> $name,
                    'email'=> $email,
                    'user_id'=> $user_id,
                    'created_at'=>$dt->toDayDateTimeString(),
                    'updated_at'=>$dt->toDayDateTimeString()
                ]);
                /*insert into co_master table ends*/
                $co_id = $insertCo->id;

            }
        }
        if($phone != '' && $email !='') {
            $getCoUser = User::where('phone', $phone)->first();
            // print_r($getCoUser->toArray());exit;
            if(!empty($getCoUser)) { // if co phone no already exists
                if($getCoUser->user_type == 3) { // if co phone no already exists for CO (user_type=3) then update the user
                    $co_user_id = $getCoUser->id;
                    $co = CarOwner::where('user_id', $co_user_id)->select('id')->first();
                    $co_id = $co->id;
                    $user_id = $co_user_id;
                    $emailCheck = User::where('email', $email)->where('id', '!=', $user_id)->first();
                    if(!empty($emailCheck)) {
                        return response()->json([
                            'success' => 0,
                            'message' => 'This email already exists for another user'
                        ]);
                    } else {
                        $userDetails = User::findOrFail($user_id);
                        $co->update([
                            'co_fname'=> $name,
                            'co_lname'=> '',
                            'email'=> $email,
                            // 'phone'=> $phone,
                            'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                        $userDetails->update([
                            'name'=> $name,
                            'email'=> $email,
                            'updated_at'=>$dt->toDayDateTimeString()
                            ]);
                    }

                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This phone already exists for another user type'
                    ]);
                }
            } else { // if co phone no does not exists
                $emailCheck = User::where('email', $email)->first();
                if(!empty($emailCheck)) {
                    return response()->json([
                        'success' => 0,
                        'message' => 'This email already exists for another user'
                    ]);
                } else {
                    /*insert into users table starts*/
                    $insertUser = User::create([
                        'name'=> $name,
                        'email'=> $email,
                        'phone'=> $phone,
                        'user_type'=> 3,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    /*insert into users table ends*/
                    $user_id = $insertUser->id;

                    /*insert into co_master table starts*/
                    $insertCo = CarOwner::create([
                        'co_fname'=> $name,
                        'co_phone'=> $phone,
                        'email'=> $email,
                        'user_id'=> $user_id,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                    /*insert into co_master table ends*/
                    $co_id = $insertCo->id;
                }

            }
        }

        /*update co_car table starts*/
        $carDetails = CarOwnerCar::findOrFail($car_id);
        $carDetails->update([
            'co_id'=> $co_id,
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*update co_car table ends*/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'co_id' => $co_id,
            'user_id' => $user_id
        ]);

    }


}
