<?php

namespace App\Http\Controllers\AdminPanel;

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;

class CarWashReportController extends Controller
{
    // protected $carsearchService;

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

    public function index(Request $request)
    {
        // echo "search car";exit;
        $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', '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')
            ->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')
            // ->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('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)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

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

    public function download(Request $request)
    {
        $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')
            // ->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')
            ->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')
            // ->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('CWO Name', 'Client Name', 'Client Email', 'Client Phone', 'Car Registration No.', 'Car Make/Model', 'Body Type', 'Car Wash Type', 'Amount(R)', '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');

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

            foreach ($data as $d) {
                $row['cwo_name']  = $d->cwo_company;
                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($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['body_type']  = $d->body_type;
                // $row['wash_name']  = getWashTypes($d->id);
                // if($d->wash_name != ''){
                //     $row['wash_name']  = $d->wash_name;
                // }
                // $row['amount']  = $d->symbol . $d->amount;
                $row['amount']  = $d->total_amount;
                $row['cleaners'] = getCleaners($d->id);
                $row['extras'] = getExtra($d->id);
                // if ($d->date_washed != '') {
                //     $row['date_washed']  = date("jS M Y", strtotime($d->date_washed));
                // } else {
                //     $row['date_washed'] = '';
                // }
                if ($d->time_washed != '') {
                    $row['time_washed']  = date("H:i:s", 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->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'] = 'One free wash';  
                } else {
                    $row['is_free_wash'] = 'No';
                }

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

                $wash_type = "";
                $wash_type  = getWashTypes($d->id);
                // if(!empty($row['wash_name'])){
                //     $wash_type = $row['wash_name'];
                // }
                if($d->wash_type_id > 0){
                    $wash_type = getSingleWashTypeName($d->wash_type_id);
                }
                if(!empty($row['extras'])){
                    $wash_type .= ', '.$row['extras'];
                }

                if ($d->wash_in != '') {
                    $row['wash_in']  = date("H:i:s", strtotime($d->wash_in));
                } else {
                    $row['wash_in'] = '';
                }
                if ($d->wash_out != '') {
                    $row['wash_out']  = date("H:i:s", 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['date_washed']  = date("Y-m-d", strtotime($d->created_at));

                $row['in_queue_time']  = date("H:i:s", 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'] = '';
                }

                // fputcsv($file, array($row['cwo_name'], $row['co_fname'], $row['email'], $row['co_phone'], $row['car_registration_no'], $row['body_type'], $wash_type, $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['cwo_name'], $row['co_fname'], $row['email'], $row['co_phone'], $row['car_registration_no'], $row['make'], $row['body_type'], $wash_type, $row['amount'], $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']));
            }

            fclose($file);
        };

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

    public function duration(Request $request)
    {
        $dataBag = array();
        $dataBag['chMenu'] = 'carWashDurationReportList';
        $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')
            ->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')
            ->orderBy('co_car.id', 'desc');

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

    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')
        ->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_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['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');
    }
}
