<?php

namespace App\Http\Controllers\OwnerPanel;

use App\Http\Controllers\Controller;
// use App\Services\CarSearchService;
use Illuminate\Http\Request;
use App\Models\WashDetail;
use App\Models\OptionalExtra;
use App\Models\CleanerWash;
use App\Models\WashTypeToWash;
use App\Models\WashCategory;
use App\Models\WashCategoryBodyType;
use App\Models\CarOwnerCar;
use Carbon\Carbon;
use DB;
use Auth;

class OwnerCarWashReportController extends Controller
{
    // protected $carsearchService;

    // public function __construct(CarSearchService $carsearchService)
    // {
    //     $this->carsearchService = $carsearchService;
    // }
    public function __construct()
    {
    }

    public function index(Request $request)
    {
        // echo "search car";exit;
        $cwo_id = Auth::user()->cwo_id;
        $dataBag = array();
        $dataBag['chMenu'] = 'carWashReportList';
        $car_registration_no = $request->input('car_registration_no');
        $start_date = $request->input('start_date');
        if($start_date != ''){
            $start_date = date("Y-m-d", strtotime($start_date));
        }
        $end_date = $request->input('end_date');
        if($end_date != ''){
            $end_date = date("Y-m-d", strtotime($end_date));
        }
        /*$data = WashDetail::select('wash_details.id', 'wash_details.car_id', 'wash_details.entry_date', 'wash_details.wash_type_id', 'wash_details.body_type', 'wash_details.amount', 'wash_details.date_washed', 'wash_details.time_washed', 'wash_details.status', 'wash_details.payment_status', 'wash_details.payment_details', 'cwo_master.cwo_name', 'cwo_master.cwo_company', 'co_master.co_fname', 'co_master.co_lname', 'co_master.co_phone', 'users.email', 'co_car.car_registration_no', 'wash_categories.wash_name', 'currency_masters.symbol', 'wash_details.entry_time', 'co_master.isd_code', 'wash_details.driver_name', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.total_amount', 'wash_details.is_free_wash', 'wash_details.driver_email', 'wash_details.wash_in', 'wash_details.wash_out')
            ->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)
            // ->orderBy('co_car.id', 'desc');
            ->orderBy('wash_details.id', 'desc');*/
            $data = WashDetail::select('wash_details.id', 'wash_details.car_id', 'wash_details.entry_date', 'wash_details.wash_type_id', 'wash_details.body_type', 'wash_details.amount', 'wash_details.date_washed', 'wash_details.time_washed', 'wash_details.status', 'wash_details.payment_status', 'wash_details.payment_details', 'cwo_master.cwo_name', 'cwo_master.cwo_company', 'co_master.co_fname', 'co_master.co_lname', 'co_master.co_phone', 'users.email', 'co_car.car_registration_no', 'co_car.make', 'currency_masters.symbol', 'wash_details.entry_time', 'co_master.isd_code', 'wash_details.driver_name', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.total_amount', 'wash_details.is_free_wash', 'wash_details.driver_email', 'wash_details.wash_in', 'wash_details.wash_out', 'wash_details.wash_type_id', 'wash_details.created_at', 'wash_details.updated_at', 'wash_details.keys_collected', 'wash_details.wash_count', 'wash_details.discount', 'co_car.vehicle_color', 'co_car.car_model')
            ->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('cwo_master', 'cwo_master.id', '=', 'wash_details.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('wash_details.cwo_id', $cwo_id)
            // ->orderBy('co_car.id', 'desc');
            ->orderBy('wash_details.id', 'desc');
        if ($car_registration_no != '') {
            $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        }   
        if($start_date != '') {
            $data->whereDate('wash_details.date_washed', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('wash_details.date_washed', '<=', $end_date);
        }    

        $dataCnt = $data->count();
        $data = $data->paginate(10);
        $dataBag['allRecords'] = $dataCnt;
        $dataBag['records'] = $data;
        // echo "<pre>";print_r($dataBag['records']->toArray());exit;
        return view('owner.washreport.list', $dataBag);
    }


    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }

    public function download(Request $request)
    {
        $cwo_id = Auth::user()->cwo_id;
        $fileName = 'car-wash-report.csv';

        $car_registration_no = $request->input('car_registration_no');
        $start_date = $request->input('start_date');
        if($start_date != ''){
            $start_date = date("Y-m-d", strtotime($start_date));
        }
        $end_date = $request->input('end_date');
        if($end_date != ''){
            $end_date = date("Y-m-d", strtotime($end_date));
        }

        /*$data = WashDetail::select('wash_details.id', 'wash_details.car_id', 'wash_details.entry_date', 'wash_details.wash_type_id', 'wash_details.body_type', 'wash_details.amount', 'wash_details.date_washed', 'wash_details.time_washed', 'wash_details.status', 'wash_details.payment_status', 'wash_details.payment_details', 'cwo_master.cwo_name', 'cwo_master.cwo_company', 'co_master.co_fname', 'co_master.co_lname', 'co_master.co_phone', 'users.email', 'co_car.car_registration_no', 'wash_categories.wash_name', 'currency_masters.symbol', 'wash_details.entry_time', 'co_master.isd_code', 'wash_details.driver_name', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.total_amount', 'wash_details.is_free_wash', 'wash_details.driver_email', 'wash_details.wash_in', 'wash_details.wash_out')
            ->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)
            // ->orderBy('co_car.id', 'desc');
            ->orderBy('wash_details.id', 'desc');*/
        $data = WashDetail::select('wash_details.id', 'wash_details.car_id', 'wash_details.entry_date', 'wash_details.wash_type_id', 'wash_details.body_type', 'wash_details.amount', 'wash_details.date_washed', 'wash_details.time_washed', 'wash_details.status', 'wash_details.payment_status', 'wash_details.payment_details', 'cwo_master.cwo_name', 'cwo_master.cwo_company', 'co_master.co_fname', 'co_master.co_lname', 'co_master.co_phone', 'users.email', 'co_car.car_registration_no', 'co_car.make', 'currency_masters.symbol', 'wash_details.entry_time', 'co_master.isd_code', 'wash_details.driver_name', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.total_amount', 'wash_details.is_free_wash', 'wash_details.driver_email', 'wash_details.wash_in', 'wash_details.wash_out', 'wash_details.created_at', 'wash_details.updated_at', 'wash_details.keys_collected', 'wash_details.wash_count', 'wash_details.discount', 'co_car.vehicle_color', 'co_car.car_model')
            ->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('cwo_master', 'cwo_master.id', '=', 'wash_details.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('wash_details.cwo_id', $cwo_id)
            // ->orderBy('co_car.id', 'desc');
            ->orderBy('wash_details.id', 'desc');    
        if ($car_registration_no != '') {
            $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        }   
        if($start_date != '') {
            $data->whereDate('wash_details.date_washed', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('wash_details.date_washed', '<=', $end_date);
        }     

        $data = $data->get();

        $headers = array(
            "Content-type"        => "text/csv",
            "Content-Disposition" => "attachment; filename=$fileName",
            "Pragma"              => "no-cache",
            "Cache-Control"       => "must-revalidate, post-check=0, pre-check=0",
            "Expires"             => "0"
        );

        // $columns = array('Client Name', 'Client Email', 'Client Phone', 'Car Registration No.', 'Car Make/Model', 'Vehicle Color', 'Body Type', 'Car Wash Type', 'Amount', 'Discount', 'Cleaners', 'Date Washed', 'In-Queue Time', 'In Wash Bay Time', 'Finishing Bay Time', 'Completed Time', 'Time In Queue', 'Time In Washbay', 'Time In Finishing Bay', 'Total Wash Time', 'Total Time @Carwash', 'Car Wash Status', 'Payment Status', 'Payment Type', 'Free Wash', 'Keys Collected');
        $columns = array('Transaction ID', 'Logged in User', 'Client Name', 'Client Phone', 'Car Registration No.', 'Car Make', 'Car Model', 'Vehicle Color', 'Body Type', 'Car Wash Type', 'Amount', 'Discount', 'Cleaners', 'Date Washed', 'In-Queue Time', 'In Wash Bay Time', 'Finishing Bay Time', 'Completed Time', 'Time In Queue', 'Time In Washbay', 'Time In Finishing Bay', 'Total Wash Time', 'Total Time @Carwash', 'Car Wash Status', 'Payment Status', 'Payment Type', 'Free Wash', 'Keys Collected');

        $callback = function () use ($data, $columns) {
            $file = fopen('php://output', 'w');
            fputcsv($file, $columns);

            foreach ($data as $d) {
                // $row['cwo_name']  = $d->cwo_name;
                if($d->driver_name != ''){
                    $row['co_fname']  = $d->driver_name;
                } else {
                    $row['co_fname']  = $d->co_fname . ' ' . $d->co_lname;
                }
                if($d->driver_email) {
                    $row['email']  = $d->driver_email;
                } else {
                    $row['email']  = $d->email;
                }
                // if($d->co_phone != ''){
                //     $row['co_phone']  = '+' . $d->isd_code . $d->co_phone;
                // } else {
                //     $row['co_phone']  = '';
                // }

                if($row['email'] != '') {
                    $row['username'] = $row['co_fname'] . ' - ' . $row['email'];
                } else {
                    $row['username'] = $row['co_fname'];
                }

                if($d->driver_phone != ''){
                    $row['co_phone'] = '+' . $d->driver_isd_code . $d->driver_phone;
                } else {
                    if($d->co_phone != ''){
                        $row['co_phone']  = '+' . $d->isd_code . $d->co_phone;
                    } else {
                        $row['co_phone']  = '';
                    }
                }
                $row['car_registration_no']  = $d->car_registration_no;
                $row['make']  = $d->make;
                $row['car_model']  = $d->car_model;
                $row['vehicle_color']  = $d->vehicle_color;
                $row['body_type']  = $d->body_type;
                // $row['wash_name']  = $d->wash_name;
                // $row['amount']  = $d->symbol . $d->total_amount;
                $row['amount']  = $d->total_amount;
                $row['cleaners'] = getCleaners($d->id);
                $row['extras'] = getExtra($d->id);
                if ($d->date_washed != '') {
                    $row['date_washed']  = date("Y/m/d", strtotime($d->date_washed));
                } else {
                    $row['date_washed'] = '';
                }
                if ($d->time_washed != '') {
                    $row['time_washed']  = date("H:i", strtotime($d->time_washed));
                } else {
                    $row['time_washed'] = '';
                }
                if ($d->status == 0) {
                    $row['status']  = 'In Queue';
                } 
                if ($d->status == 1) {
                    $row['status']  = 'In Wash Bay';
                } 
                if ($d->status == 2) {
                    $row['status']  = 'Finishing Bay';
                } 
                if ($d->status == 3) {
                    $row['status']  = 'Completed';
                }
                if ($d->status == 4) {
                    $row['status']  = 'Cancelled';
                }
                if ($d->status == 5) {
                    $row['status']  = 'Keys Collected';
                }
                if ($d->payment_status == 1) {
                    $row['payment_status']  = 'Paid';
                } else {
                    $row['payment_status']  = 'Not Paid';
                }
                // if($d->is_free_wash == 1 && $d->amount == $d->total_amount){
                //     $row['payment_details']  = 'Free Wash';    
                // } else {
                //     $row['payment_details']  = $d->payment_details;
                // }
                $row['payment_details']  = $d->payment_details;
                
                if($d->is_free_wash == 1 ){
                    $row['is_free_wash'] = 'Yes';  
                } else {
                    $row['is_free_wash'] = 'No';
                }

                if ($d->wash_in != '') {
                    $row['wash_in']  = date("H:i", strtotime($d->wash_in));
                } else {
                    $row['wash_in'] = '';
                }
                if ($d->wash_out != '') {
                    $row['wash_out']  = date("H:i", strtotime($d->wash_out));
                } else {
                    $row['wash_out'] = '';
                }

                if ($d->wash_out != '') {
                    $row['bay_time'] = getDateDiffBay($d->wash_in, $d->wash_out);
                } else {
                    $row['bay_time'] = '';
                }

                $row['wash_name']  = getWashTypes($d->id);
                if($d->wash_type_id > 0){
                    $row['wash_name'] = getSingleWashTypeName($d->wash_type_id);
                }

                // $row['date_washed']  = date("Y-m-d", strtotime($d->created_at));

                $row['in_queue_time']  = date("H:i", strtotime($d->created_at));

                if ($d->wash_in != '') {
                    $row['time_in_queue'] = getDateDiffBay($d->created_at, $d->wash_in);
                } else {
                    $row['time_in_queue'] = '';
                }

                if ($d->wash_in != '' && $d->wash_out != '') {
                    $row['time_in_wash_in'] = getDateDiffBay($d->wash_in, $d->wash_out);
                } else {
                    $row['time_in_wash_in'] = '';
                }

                if ($d->wash_out != '' && $d->time_washed) {
                    $row['time_in_wash_out'] = getDateDiffBay($d->wash_out, $d->updated_at);
                } else {
                    $row['time_in_wash_out'] = '';
                }

                if ($d->wash_in != '' && $d->time_washed != '') {
                    $row['total_wash_time'] = getDateDiffBay($d->wash_in, $d->updated_at);
                } else {
                    $row['total_wash_time'] = '';
                }

                if ($d->time_washed != '') {
                    $row['total_time_at_car_wash'] = getDateDiffBay($d->created_at, $d->updated_at);
                } else {
                    $row['total_time_at_car_wash'] = '';
                }

                if ($d->keys_collected != '') {
                    $row['keys_collected']  = date("Y-m-d H:i", strtotime($d->keys_collected));
                } else {
                    $row['keys_collected'] = '';
                }

                $row['discount']  = $d->discount . "%";

                $row['wash_count']  = $d->wash_count;

                if(Auth::user()->email != ''){
                    $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                } else {
                    $row['logged_in_user'] = Auth::user()->name;
                }

                // dd($row);
                // fputcsv($file, array($row['co_fname'], $row['email'], $row['co_phone'], $row['car_registration_no'], $row['body_type'], $row['wash_name'] . ',' . $row['extras'], $row['amount'], $row['cleaners'], $row['wash_in'], $row['wash_out'], $row['bay_time'], $row['date_washed'], $row['time_washed'], $row['status'], $row['payment_status'], $row['payment_details'], $row['is_free_wash']));


                // fputcsv($file, array($row['co_fname'], $row['email'], $row['co_phone'], $row['car_registration_no'], $row['make'], $row['vehicle_color'], $row['body_type'], $row['wash_name'] . ',' . $row['extras'], $row['amount'], $row['discount'], $row['cleaners'], $row['date_washed'], $row['in_queue_time'], $row['wash_in'], $row['wash_out'], $row['time_washed'], $row['time_in_queue'], $row['time_in_wash_in'], $row['time_in_wash_out'], $row['total_wash_time'], $row['total_time_at_car_wash'], $row['status'], $row['payment_status'], $row['payment_details'], $row['is_free_wash'], $row['keys_collected']));
                fputcsv($file, array($row['wash_count'], $row['logged_in_user'], $row['username'], $row['co_phone'], $row['car_registration_no'], $row['make'], $row['car_model'], $row['vehicle_color'], $row['body_type'], $row['wash_name'] . ',' . $row['extras'], $row['amount'], $row['discount'], $row['cleaners'], $row['date_washed'], $row['in_queue_time'], $row['wash_in'], $row['wash_out'], $row['time_washed'], $row['time_in_queue'], $row['time_in_wash_in'], $row['time_in_wash_out'], $row['total_wash_time'], $row['total_time_at_car_wash'], $row['status'], $row['payment_status'], $row['payment_details'], $row['is_free_wash'], $row['keys_collected']));
            }

            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }

    public function printWashDetail($id)
    {
        // $wash_id = $request->input('wash_id');
        // echo $wash_id;exit;
        // $dataBag['cwo'] = CarWashOwner::where('account_no', $account_no)->first();
        $data = 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_details.otp', 'wash_details.payment_details', 'wash_details.amount', 'wash_details.total_amount', 'co_master.isd_code', 'wash_details.driver_name', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'cwo_master.cwo_logo', 'wash_details.wash_type_id', 'co_car.make', 'co_car.car_model', 'co_car.vehicle_color')
        ->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('cwo_master', 'cwo_master.id', '=', 'wash_details.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('wash_details.id', $id);
        $data = $data->get();
        // echo "<pre>";print_r($data->toArray());exit;
        $dataBag['id'] = $data[0]->id;
        $dataBag['car_id'] = $data[0]->car_id;
        if($data[0]->driver_name != ''){
            $dataBag['co_fname'] = $data[0]->driver_name;
            $dataBag['co_lname'] = '';
        } else {
            $dataBag['co_fname'] = $data[0]->co_fname;
            $dataBag['co_lname'] = $data[0]->co_lname;
        }
        if($data[0]->driver_phone != ''){
            $dataBag['isd_code'] = '+' . $data[0]->driver_isd_code;
            $dataBag['co_phone'] = $data[0]->driver_phone;
        } else {
            $dataBag['isd_code'] = '+' . $data[0]->isd_code;
            $dataBag['co_phone'] = $data[0]->co_phone;
        }
        $dataBag['car_registration_no'] = $data[0]->car_registration_no;
        $dataBag['make'] = $data[0]->make;
        $dataBag['car_model'] = $data[0]->car_model;
        $dataBag['vehicle_color'] = $data[0]->vehicle_color;
        // $dataBag['wash_name'] = $data[0]->wash_name;
        if($data[0]->date_washed != '') {
            $dataBag['date_washed']  = date("d/m/Y", strtotime($data[0]->date_washed));
        } else {
            $dataBag['date_washed']  = '';
        }
        if($data[0]->time_washed != '') {
            $dataBag['time_washed']  = date("h:i a", strtotime($data[0]->time_washed));
        } else {
            $dataBag['time_washed']  = '';
        }
        $dataBag['payment_status_id'] = $data[0]->payment_status;
        if($data[0]->payment_status == 1) {
            $dataBag['payment_status'] = 'Paid';
        } else {
            $dataBag['payment_status'] = 'Not Paid';
        }
        $dataBag['status_id'] = $data[0]->status;
        if($data[0]->status == 0) {
            $dataBag['status'] = 'Car in-queue';
        }
        if($data[0]->status == 1) {
            $dataBag['status'] = 'In Wash Bay';
        }
        if($data[0]->status == 2) {
            $dataBag['status'] = 'Finishing Bay';
        }
        if($data[0]->status == 3) {
            $dataBag['status'] = 'Car Wash Completed';
        }
        if($data[0]->status == 4) {
            $dataBag['status'] = 'Cancelled';
        }
        $dataBag['otp'] = $data[0]->otp;
        $dataBag['payment_mode'] = $data[0]->payment_details;
        $dataBag['wash_amount'] = $data[0]->amount;
        $dataBag['total_amount'] = $data[0]->total_amount;
        $optionalExtra = OptionalExtra::where('wash_id', $data[0]->id)->select('optional_extra', 'price')->orderBy('id', 'asc')->get();
        $dataBag['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', $data[0]->id)
                            ->orderBy('cleaner_washes.id', 'asc')
                            ->get();
        $dataBag['cleaners'] = $cleaners;

        if($data[0]->cwo_logo != ''){
            $dataBag['cwo_logo'] = asset('images/cwo') . '/' . $data[0]->cwo_logo;
        } else {
            $dataBag['cwo_logo'] = '';
        }

        $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.wash_id', $data[0]->id)
                            ->orderBy('wash_type_to_washes.id', 'asc')
                            ->get();
        $dataBag['wash_types'] = $wash_types;

        if($data[0]->wash_type_id > 0){
            $getWashType = WashCategory::where('id', $data[0]->wash_type_id)->select('wash_name')->first();
            if($getWashType != ''){
                $dataBag['wash_name'] = $getWashType->wash_name;    
            } else {
                $dataBag['wash_name'] = '';
            }
        } else {
            $dataBag['wash_name'] = '';
        }
        // echo "<pre>";print_r($dataBag);exit;
        return view('print.washdetail', $dataBag);
    }

    public function delete($id)
    {
        $record = WashDetail::find($id); // fetch the record
        $record->delete();

        $optionalExtra = OptionalExtra::where('wash_id', $id);
        $optionalExtra->delete();

        $cleanerWash = CleanerWash::where('wash_id', $id);
        $cleanerWash->delete();

        $washTypeToWash = WashTypeToWash::where('wash_id', $id);
        $washTypeToWash->delete();

        return back()->with('msg', 'Car wash record has been deleted successfully.')
            ->with('msg_class', 'alert alert-success');
    }

    public function edit($id)
    {
        $record = WashDetail::find($id); // fetch the record
        // echo "wash_id-> " . $id . ", cwo_id-> " . $record->cwo_id . ", body_type_id-> " . $record->body_type_id;exit; 
        $dataBag['details'] = $record;
        // echo "<pre>";print_r($dataBag['details']);exit;

        $dataBag['carDetails'] = CarOwnerCar::find($record->car_id);

        $data = WashCategory::where('cwo_id', $record->cwo_id)->where('is_active', 1)->orderBy('wash_name', 'asc')->select('id', 'wash_name', 'wash_desc')->get();
        $dataDisplay=[];
        $dataArray = [];
        if($data != ''){
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['wash_name'] = $d->wash_name;
                $dataDisplay['wash_desc'] = $d->wash_desc;
                // $dataDisplay['body_types'] = WashCategoryBodyType::where('wash_category_id', $d->id)->get();
                if($record->body_type_id == '') {
                    $dataDisplay['body_types'] = WashCategoryBodyType::select('body_types.name','wash_category_body_types.body_type_id','wash_category_body_types.price','wash_category_body_types.duration')
                    ->join('body_types','body_types.id','=','wash_category_body_types.body_type_id')
                    ->where('wash_category_body_types.wash_category_id', $d->id)
                    ->orderBy('body_types.id', 'asc')
                    ->get();
                } else {
                    $dataDisplay['body_types'] = WashCategoryBodyType::select('body_types.name','wash_category_body_types.body_type_id','wash_category_body_types.price','wash_category_body_types.duration')
                    ->join('body_types','body_types.id','=','wash_category_body_types.body_type_id')
                    ->where('wash_category_body_types.wash_category_id', $d->id)
                    ->where('wash_category_body_types.body_type_id', $record->body_type_id)
                    ->orderBy('body_types.id', 'asc')
                    ->get();
                }
                // echo "<pre>";print_r($dataDisplay['body_types']->toArray());
                

                $dataArray[] = $dataDisplay;
            }
            // exit;
        }
        $dataBag['washCategories'] = $dataArray;
        // echo "<pre>";print_r($dataBag);exit;

        $existingWashArray = array();
        $getExistingWash = WashTypeToWash::where('wash_id', $id)->select('wash_type_id')->get();
        if($getExistingWash != ''){
            foreach($getExistingWash as $w)
            array_push($existingWashArray, $w->wash_type_id);
        }
        $dataBag['existingWashArray'] = $existingWashArray;
        // echo "<pre>";print_r($existingWashArray);exit;

        $dataBag['optionalExtra'] = OptionalExtra::where('wash_id', $id)->select('optional_extra', 'price')->get();

        return view('owner.washreport.edit', $dataBag); 
    }

    public function update(Request $request, $id)
    {
        // echo $id;exit;
        $request->validate([
            'wash_category_id' => 'required',
            // 'optional_extra_price' => 'numeric|nullable',
            'driver_name' => 'required',
            'car_registration_no' => 'required|unique:co_car,car_registration_no,' . $request->input('car_id'),
        ], [
            'wash_category_id.required' => 'Please choose atleast one wash.',
            'driver_name.required' => 'Please enter a driver name.',
            'car_registration_no.unique' => 'This car registration number already exists.'
        ]);
        $wash_category_id = $request->input('wash_category_id');
        $price = $request->input('price');
        $optional_extra = $request->input('optional_extra');
        $optional_extra_price = $request->input('optional_extra_price');
        $wash_id = $id;
        // echo "<pre>"; print_r($optional_extra);
        // exit;
        // echo "<pre>"; print_r($optional_extra_price);exit;

        $driver_name = $request->input('driver_name');
        $driver_email = $request->input('driver_email');
        $driver_isd_code = $request->input('driver_isd_code');
        $driver_phone = $request->input('driver_phone');

        $car_id = $request->input('car_id');
        $car_registration_no = $request->input('car_registration_no');
        $make = $request->input('make');

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

        $dt = Carbon::now();

        $data = WashDetail::findOrFail($id);
        $is_free_wash = $data->is_free_wash;
        $body_type_id = $data->body_type_id;
        $free_wash_type_id = getLowestPrice($wash_category_id, $body_type_id);
        // echo $free_wash_type_id;exit;

        $amount = 0; 

        DB::delete("DELETE FROM `wash_type_to_washes` WHERE `wash_id` = " . $wash_id . "");
        if (count($wash_category_id) > 0) {
            for ($i = 0; $i < count($wash_category_id); $i++) {
                // echo $wash_category_id[$i] . '<br>';

                if($is_free_wash == 1){ // true starts
                    // echo "1";exit;
                    /*** free wash id logic starts ***/
                    if($free_wash_type_id != '' && $wash_category_id[$i] == $free_wash_type_id) {
                        $amount = $amount + 0; 
                        $wash_type_price = 0;   
                    } else {
                        $getPrice = WashCategoryBodyType::where('wash_category_id', $wash_category_id[$i])->where('body_type_id', $body_type_id)->first();
                        if($getPrice != ''){
                            $amount = $amount + $getPrice->price;
                            $wash_type_price = $getPrice->price;
                        } else {
                            $amount = $amount + 0;
                            $wash_type_price = 0;
                        }
                    }
                    /*** free wash id logic ends ***/
                } // true ends

                if($is_free_wash == 0){
                    $getPrice = WashCategoryBodyType::where('wash_category_id', $wash_category_id[$i])->where('body_type_id', $body_type_id)->first();
                    if($getPrice != ''){
                        $amount = $amount + $getPrice->price;
                        $wash_type_price = $getPrice->price;
                    } else {
                        $amount = $amount + 0;
                        $wash_type_price = 0;
                    }
                }

                $assignWashType = WashTypeToWash::create([
                        'wash_id'=> $wash_id,
                        'wash_type_id'=> $wash_category_id[$i],
                        'price'=> $wash_type_price,
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);



            } // foreach ends
        }
        $total_amount = $amount;
        $data->update([
            'amount' => $amount,
            'total_amount' => $total_amount
        ]);
        // exit;

        DB::delete("DELETE FROM `optional_extras` WHERE `wash_id` = " . $wash_id . "");
        if (count($optional_extra) > 0) {
            for ($i = 0; $i < count($optional_extra); $i++) {
                if($optional_extra[$i] != '' && $optional_extra_price[$i] != ''){
                    $total_amount = $total_amount + $optional_extra_price[$i];
                    OptionalExtra::create([
                        'wash_id'=> $wash_id,
                        'optional_extra'=> $optional_extra[$i],
                        'price'=> $optional_extra_price[$i],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);
                }
            }
            $data->total_amount = $total_amount;
            $data->save();
        }

        $data->update([
            'driver_name' => $driver_name,
            'driver_email' => $driver_email,
            'driver_isd_code' => $driver_isd_code,
            'driver_phone' => $driver_phone
        ]);

        if($payment_status == 1){
            $data->update([
                'payment_status' => $payment_status
            ]);    
        }

        $carData = CarOwnerCar::find($car_id);
        $carData->update([
            'car_registration_no' => $car_registration_no,
            'make' => $make
        ]);


        return back()->with('success', 'Carwash record has been updated successfully.')->with('msg_class', 'alert alert-success');
    }

    public function multiDelete(Request $request)
    {
        $delete_ids = $request->delete_ids;
        // echo "<pre>";print_r($delete_ids);exit;
        if($delete_ids != ''){
            $myArray = explode(',', $delete_ids);
            foreach ($myArray as $id) {
                $record = WashDetail::find($id); // fetch the record
                $record->delete();

                $optionalExtra = OptionalExtra::where('wash_id', $id);
                $optionalExtra->delete();

                $cleanerWash = CleanerWash::where('wash_id', $id);
                $cleanerWash->delete();

                $washTypeToWash = WashTypeToWash::where('wash_id', $id);
                $washTypeToWash->delete();
            }
        }
        return response()->json(['message' => 'Car wash records have been deleted successfully', 'status' => 1], 200);
    }

}
