<?php

namespace App\Http\Controllers\OwnerPanel;

use App\Http\Controllers\Controller;
// use App\Services\CarSearchService;
use Illuminate\Http\Request;
use App\Models\OtherServiceReport;
use App\Models\OtherServiceReportToProduct;
use App\Models\OtherService;
use Carbon\Carbon;
use DB;
use Auth;

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

    public function index(Request $request)
    {
        // echo "search car";exit;
        $cwo_id = Auth::user()->cwo_id;
        $dataBag = array();
        $dataBag['chMenu'] = 'otherServiceReportList';
        // $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 = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time')
            ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->orderBy('other_service_reports.id', 'desc');
        // if ($car_registration_no != '') {
        //     $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        // }   
        if($start_date != '') {
            $data->whereDate('other_service_reports.date', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('other_service_reports.date', '<=', $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.otherservicesreport.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 = 'other-services-products-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 = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time')
            ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
            ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->orderBy('other_service_reports.id', 'desc');
        // if ($car_registration_no != '') {
        //     $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
        // }   
        if($start_date != '') {
            $data->whereDate('other_service_reports.date', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('other_service_reports.date', '<=', $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('Sl #', 'Logged in User', 'Client Name', 'Client Phone', 'Products/Services', 'Amount(R)', 'Date', 'Time', 'Payment Status', 'Payment Type');

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

            $i = 1;
            foreach ($data as $d) {
                if(Auth::user()->email != ''){
                    $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                } else {
                    $row['logged_in_user'] = Auth::user()->name;
                }

                if($d->email != '') {
                    $row['name'] = $d->name . ' - ' . $d->email;
                } else {
                    $row['name'] = $d->name;
                }

                if($d->phone != ''){
                    $row['phone'] = '+' . $d->isd_code . $d->phone;
                } else {
                    $row['phone']  = '';
                }
                $row['amount']  = $d->total_amount;
                $row['services'] = getOtherServices($d->id);
                if ($d->date != '') {
                    $row['date']  = date("Y/m/d", strtotime($d->date));
                } else {
                    $row['date'] = '';
                }
                if ($d->time != '') {
                    $row['time']  = date("H:i", strtotime($d->time));
                } else {
                    $row['time'] = '';
                }
                if ($d->payment_status == 1) {
                    $row['payment_status']  = 'Paid';
                } else {
                    $row['payment_status']  = 'Not Paid';
                }
                $row['payment_details']  = $d->payment_details;

                fputcsv($file, array($i++, $row['logged_in_user'], $row['name'], $row['phone'], $row['services'], $row['amount'], $row['date'], $row['time'], $row['payment_status'], $row['payment_details']));
            }

            fclose($file);
        };

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

    public function printDetail($id)
    {
        $data = OtherServiceReport::select('other_service_reports.id', 'other_service_reports.name', 'other_service_reports.isd_code', 'other_service_reports.phone', 'other_service_reports.email', 'other_service_reports.total_amount', 'other_service_reports.payment_status', 'other_service_reports.payment_details', 'other_service_reports.date', 'other_service_reports.time', 'cwo_master.cwo_logo')
        ->join('cwo_master', 'cwo_master.id', '=', 'other_service_reports.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('other_service_reports.id', $id);
        $data = $data->get();
        // echo "<pre>";print_r($data->toArray());exit;
        $dataBag['id'] = $data[0]->id;
        if($data[0]->name != ''){
            $dataBag['name'] = $data[0]->name;
        } else {
            $dataBag['name'] = '';
        }
        if($data[0]->phone != ''){
            $dataBag['phone'] = '+' . $data[0]->isd_code . $data[0]->phone;
        } else {
            $dataBag['phone'] = '';
        }
        if($data[0]->date != '') {
            $dataBag['date']  = date("d/m/Y", strtotime($data[0]->date));
        } else {
            $dataBag['date']  = '';
        }
        if($data[0]->time != '') {
            $dataBag['time']  = date("h:i a", strtotime($data[0]->time));
        } else {
            $dataBag['time']  = '';
        }
        $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['payment_mode'] = $data[0]->payment_details;
        $dataBag['total_amount'] = $data[0]->total_amount;

        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();
        $services = DB::table('other_service_report_to_products')->select('other_services.description', 'other_service_report_to_products.price', 'other_service_report_to_products.quantity', 'other_service_report_to_products.total_price')
                ->join('other_service_reports', 'other_service_report_to_products.other_service_report_id', 'other_service_reports.id')
                ->join('other_services', 'other_service_report_to_products.other_service_id', 'other_services.id')
                ->where('other_service_report_to_products.other_service_report_id', $data[0]->id)
                ->orderBy('other_service_report_to_products.id', 'asc')
                ->get();                   
        $dataBag['services'] = $services;

        // echo "<pre>";print_r($dataBag);exit;
        return view('owner.otherservicesreport.print', $dataBag);
    }

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

        $serviceReportToProduct = OtherServiceReportToProduct::where('other_service_report_id', $id);
        $serviceReportToProduct->delete();

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

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

        $data = OtherService::where('cwo_id', $cwo_id)->where('is_active', 1)->orderBy('description', 'asc')->get();
        $dataBag['otherServices'] = $data;
        // echo "<pre>";print_r($dataBag);exit;

        $existingServicesArray = array();
        $getExistingService = OtherServiceReportToProduct::where('other_service_report_id', $id)->select('other_service_id')->get();
        if($getExistingService != ''){
            foreach($getExistingService as $w)
            array_push($existingServicesArray, $w->other_service_id);
        }
        $dataBag['existingServicesArray'] = $existingServicesArray;
        // echo "<pre>";print_r($existingServicesArray);exit;

        return view('owner.otherservicesreport.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 = OtherServiceReport::find($id); // fetch the record
                $record->delete();

                $serviceReportToProduct = OtherServiceReportToProduct::where('other_service_report_id', $id);
                $serviceReportToProduct->delete();
            }
        }
        return response()->json(['message' => 'This record have been deleted successfully', 'status' => 1], 200);
    }

}
