<?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\LoyaltyScoreAddLog;
use Carbon\Carbon;
use DB;
use Auth;

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

    public function index(Request $request)
    {
        // echo "search car";exit;
        $cwo_id = Auth::user()->cwo_id;
        $dataBag = array();
        $dataBag['chMenu'] = 'LoyaltyScoreAddLogReportList';
        $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 = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'co_car.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id')
            ->join('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
            ->join('co_car', 'co_car.id', '=', 'wash_details.car_id')
            ->join('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
            // ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
            ->orderBy('loyalty_score_add_logs.id', 'desc');*/
        /*$data = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'au.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id', 'loyalty_score_add_logs.other_service_report_id', 'other_service_reports.name', 'other_service_reports.cwo_user_id as other_services_cwo_user_id', 'loyalty_score_add_logs.prebooking_id', 'pre_bookings.name as prebookingname', 'pre_bookings.car_id as prebookingcar_id', 'pre_bookings.body_type as prebookingbody_type')
        ->leftJoin('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
        ->leftJoin('other_service_reports', 'other_service_reports.id', '=', 'loyalty_score_add_logs.other_service_report_id')
        ->leftJoin('pre_bookings', 'pre_bookings.id', '=', 'loyalty_score_add_logs.prebooking_id')
        ->leftJoin('co_car  as au', 'au.id', '=', 'wash_details.car_id')
        ->leftJoin('co_car  as cu', 'cu.id', '=', 'pre_bookings.car_id')
        ->leftJoin('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
        // ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
        ->where('loyalty_score_add_logs.status', '=', 1)
        // ->where('loyalty_score_add_logs.prebooking_id', '=', 0)
        ->orderBy('loyalty_score_add_logs.id', 'desc');
        if ($car_registration_no != '') {
            // $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
            $phone_1 = substr($car_registration_no, 1);
            $data = $data->where(function ($query) use ($car_registration_no, $phone_1) {
                $query->where('au.car_registration_no', $car_registration_no)
                    ->orWhere('wash_details.driver_name', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $phone_1)
                    ->orWhere('other_service_reports.name', $car_registration_no)
                    ->orWhere('other_service_reports.phone', $car_registration_no)
                    ->orWhere('other_service_reports.phone', $phone_1)
                    ->orWhere('loyalty_score_add_logs.phone', $car_registration_no)
                    ->orWhere('loyalty_score_add_logs.phone', $phone_1)
                    ->orwhere('cu.car_registration_no', $car_registration_no)
                    ->orWhere('pre_bookings.name', $car_registration_no)
                    ->orWhere('pre_bookings.phone_no', $car_registration_no)
                    ->orWhere('pre_bookings.phone_no', $phone_1);
                // Add more columns as needed
            });
        }*/   
        $data = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'au.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id', 'loyalty_score_add_logs.other_service_report_id', 'loyalty_score_add_logs.prebooking_id', 'wash_details.wash_count', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.date_washed', 'wash_details.loyalty_type', 'wash_details.discount', 'wash_details.total_amount', 'currency_masters.symbol', 'wash_details.id as wash_details_id')
        ->leftJoin('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
        ->leftJoin('co_car  as au', 'au.id', '=', 'wash_details.car_id')
        ->leftJoin('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
        ->where('loyalty_score_add_logs.status', '=', 1)
        // ->where('loyalty_score_add_logs.prebooking_id', '=', 0)
        // ->where('loyalty_score_add_logs.other_service_report_id', '=', 0)
        ->where('loyalty_score_add_logs.wash_id', '!=', 0)
        ->where('wash_details.id', '!=', '')
        ->orderBy('loyalty_score_add_logs.id', 'desc');
        if ($car_registration_no != '') {
            // $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
            $phone_1 = substr($car_registration_no, 1);
            $data = $data->where(function ($query) use ($car_registration_no, $phone_1) {
                $query->where('au.car_registration_no', $car_registration_no)
                    ->orWhere('wash_details.driver_name', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $phone_1)
                    ->orWhere('loyalty_score_add_logs.phone', $car_registration_no)
                    ->orWhere('loyalty_score_add_logs.phone', $phone_1);
                // Add more columns as needed
            });
        } 
        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.loyaltyscoreaddlog.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 = 'loyalty-accrual-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 = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'co_car.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id')
            ->join('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
            ->join('co_car', 'co_car.id', '=', 'wash_details.car_id')
            ->join('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
            // ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
            ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
            ->orderBy('loyalty_score_add_logs.id', 'desc');*/
        /*$data = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'au.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id', 'loyalty_score_add_logs.other_service_report_id', 'other_service_reports.name', 'other_service_reports.cwo_user_id as other_services_cwo_user_id', 'loyalty_score_add_logs.prebooking_id', 'pre_bookings.name as prebookingname', 'pre_bookings.car_id as prebookingcar_id', 'pre_bookings.body_type as prebookingbody_type')
        ->leftJoin('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
        ->leftJoin('other_service_reports', 'other_service_reports.id', '=', 'loyalty_score_add_logs.other_service_report_id')
        ->leftJoin('pre_bookings', 'pre_bookings.id', '=', 'loyalty_score_add_logs.prebooking_id')
        ->leftJoin('co_car  as au', 'au.id', '=', 'wash_details.car_id')
        ->leftJoin('co_car  as cu', 'cu.id', '=', 'pre_bookings.car_id')
        ->leftJoin('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
        // ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
        ->where('loyalty_score_add_logs.status', '=', 1)
        // ->where('loyalty_score_add_logs.prebooking_id', '=', 0)
        ->orderBy('loyalty_score_add_logs.id', 'desc');
        if ($car_registration_no != '') {
            // $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
            $phone_1 = substr($car_registration_no, 1);
            $data = $data->where(function ($query) use ($car_registration_no, $phone_1) {
                $query->where('au.car_registration_no', $car_registration_no)
                    ->orWhere('wash_details.driver_name', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $phone_1)
                    ->orWhere('other_service_reports.name', $car_registration_no)
                    ->orWhere('other_service_reports.phone', $car_registration_no)
                    ->orWhere('other_service_reports.phone', $phone_1)
                    ->orWhere('loyalty_score_add_logs.phone', $car_registration_no)
                    ->orWhere('loyalty_score_add_logs.phone', $phone_1)
                    ->orwhere('cu.car_registration_no', $car_registration_no)
                    ->orWhere('pre_bookings.name', $car_registration_no)
                    ->orWhere('pre_bookings.phone_no', $car_registration_no)
                    ->orWhere('pre_bookings.phone_no', $phone_1);
                // Add more columns as needed
            });
        }   
        if($start_date != '') {
            $data->whereDate('loyalty_score_add_logs.wash_entry_date', '>=', $start_date);
        } 
        if($end_date != '') {
            $data->whereDate('loyalty_score_add_logs.wash_entry_date', '<=', $end_date);
        }*/  

        $data = LoyaltyScoreAddLog::select('loyalty_score_add_logs.id', 'loyalty_score_add_logs.isd_code', 'loyalty_score_add_logs.phone', 'loyalty_score_add_logs.available_total_loyalty_point', 'loyalty_score_add_logs.added_loyalty_point', 'loyalty_score_add_logs.total_loyalty_point', 'loyalty_score_add_logs.wash_entry_date', 'wash_details.driver_name', 'wash_details.car_id', 'au.car_registration_no', 'wash_details.cwo_user_id', 'wash_details.body_type', 'loyalty_score_add_logs.wash_id', 'loyalty_score_add_logs.other_service_report_id', 'loyalty_score_add_logs.prebooking_id', 'wash_details.wash_count', 'wash_details.driver_isd_code', 'wash_details.driver_phone', 'wash_details.date_washed', 'wash_details.loyalty_type', 'wash_details.discount', 'wash_details.total_amount', 'currency_masters.symbol', 'wash_details.id as wash_details_id')
        ->leftJoin('wash_details', 'wash_details.id', '=', 'loyalty_score_add_logs.wash_id')
        ->leftJoin('co_car  as au', 'au.id', '=', 'wash_details.car_id')
        ->leftJoin('cwo_master', 'cwo_master.id', '=', 'loyalty_score_add_logs.cwo_id')
        ->leftJoin('currency_masters', 'currency_masters.id', '=', 'cwo_master.currency_id')
        ->where('loyalty_score_add_logs.cwo_id', $cwo_id)
        ->where('loyalty_score_add_logs.status', '=', 1)
        // ->where('loyalty_score_add_logs.prebooking_id', '=', 0)
        // ->where('loyalty_score_add_logs.other_service_report_id', '=', 0)
        ->where('loyalty_score_add_logs.wash_id', '!=', 0)
        ->where('wash_details.id', '!=', '')
        ->orderBy('loyalty_score_add_logs.id', 'desc');
        if ($car_registration_no != '') {
            // $data = $data->where('co_car.car_registration_no', 'like', '%' . $car_registration_no . '%');
            $phone_1 = substr($car_registration_no, 1);
            $data = $data->where(function ($query) use ($car_registration_no, $phone_1) {
                $query->where('au.car_registration_no', $car_registration_no)
                    ->orWhere('wash_details.driver_name', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $car_registration_no)
                    ->orWhere('wash_details.driver_phone', $phone_1)
                    ->orWhere('loyalty_score_add_logs.phone', $car_registration_no)
                    ->orWhere('loyalty_score_add_logs.phone', $phone_1);
                // Add more columns as needed
            });
        } 
        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();
        // echo "<pre>";print_r($data);exit;

        $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('Transaction ID', 'Client Name', 'Client Phone', 'Car Reg. No.', '# of Times Washed Here', '# of Times to Free Wash', 'Body Type', 'Car Wash Type', 'Amount Paid', 'Date Washed', 'Loyalty Type', 'Discount(%)', 'Earned Points', 'Total Available Points', 'Logged in User');

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

            $i = 1;
            foreach ($data as $d) {
                // if($d->wash_id > 0){
                    if($d->cwo_user_id > 0){
                        $row['logged_in_user'] = getUserFromIdInCsv($d->cwo_user_id); 
                    } else {
                        if(Auth::user()->email != ''){
                            $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                        } else {
                            $row['logged_in_user'] = Auth::user()->name;
                        }
                    }
                // }
                // if($d->other_service_report_id > 0){
                //     if($d->other_services_cwo_user_id > 0){
                //         $row['logged_in_user'] = getUserFromIdInCsv($d->other_services_cwo_user_id); 
                //     } else {
                //         if(Auth::user()->email != ''){
                //             $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                //         } else {
                //             $row['logged_in_user'] = Auth::user()->name;
                //         }
                //     }
                // }
                // if($d->wash_id == 0 && $d->prebooking_id > 0){
                //     if(Auth::user()->email != ''){
                //         $row['logged_in_user'] = Auth::user()->name . ' - ' . Auth::user()->email;
                //     } else {
                //         $row['logged_in_user'] = Auth::user()->name;
                //     }
                // }

                // if($d->wash_id > 0){
                    $row['driver_name']  = $d->driver_name;
                // }
                // if($d->other_service_report_id > 0){
                //     $row['driver_name']  = $d->name;
                // }
                // if($d->wash_id == 0 && $d->prebooking_id > 0){
                //     $row['driver_name']  = $d->prebookingname;
                // }

                // if($d->phone != ''){
                //     $row['phone'] = '+' . $d->isd_code . $d->phone;
                // }
                if($d->driver_phone != ''){
                    $row['co_phone'] = '+' . $d->driver_isd_code . $d->driver_phone;
                } else {
                    $row['co_phone']  = '';
                }
                $row['car_registration_no']  = $d->car_registration_no;
                // if($d->wash_id == 0 && $d->prebooking_id > 0){
                //     $row['car_registration_no']  = getCarRegNo($d->prebookingcar_id);
                // }
                $row['available_total_loyalty_point']  = $d->available_total_loyalty_point;
                $row['added_loyalty_point']  = $d->added_loyalty_point;
                $row['total_loyalty_point']  = $d->total_loyalty_point;
                if ($d->wash_entry_date != '') {
                    $row['wash_entry_date']  = date("Y/m/d", strtotime($d->wash_entry_date));
                } else {
                    $row['wash_entry_date'] = '';
                }
                $row['body_type']  = $d->body_type;
                // if($d->wash_id == 0 && $d->prebooking_id > 0){
                //     $row['body_type']  = $d->prebookingbody_type;
                // }
                $row['car_wash_type']  = getWashTypes($d->wash_id);
                // if($d->wash_id == 0 && $d->prebooking_id > 0){
                //     $row['car_wash_type']  = getWashTypesOfPreBooking($d->prebooking_id);
                // }

                $row['total_amount']  = $d->symbol . $d->total_amount;
                if ($d->date_washed != '') {
                    $row['date_washed']  = date("Y/m/d", strtotime($d->date_washed));
                } else {
                    $row['date_washed'] = '';
                }
                $row['discount']  = $d->discount;

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

                if($d->loyalty_type == 1) {
                    $row['loyalty_type'] = 'Free Wash';
                } elseif($d->loyalty_type == 2) {
                    $row['loyalty_type'] = 'Discount';
                } elseif($d->loyalty_type == 3) {
                    $row['loyalty_type'] = 'Loyalty Points';
                } else {
                    $row['loyalty_type'] = '';
                }

                if($d->driver_phone != ''){
                    $row['no_of_time_washed'] = noOfTimesWashed(Auth::user()->cwo_id, $d->driver_phone);
                } else {
                    $row['no_of_time_washed'] = '';
                }

                if($d->driver_phone != ''){
                    $row['no_of_time_to_free_wash'] = noOfTimesToFreeWash(Auth::user()->cwo_id, $d->driver_phone, $d->wash_id);
                } else {
                    $row['no_of_time_to_free_wash'] = '';
                }

                // fputcsv($file, array($row['logged_in_user'], $row['driver_name'], $row['phone'], $row['car_registration_no'], $row['body_type'], $row['car_wash_type'], $row['available_total_loyalty_point'], $row['added_loyalty_point'], $row['total_loyalty_point'], $row['wash_entry_date']));
                fputcsv($file, array($row['wash_count'], $row['driver_name'], $row['co_phone'], $row['car_registration_no'], $row['no_of_time_washed'], $row['no_of_time_to_free_wash'], $row['body_type'], $row['car_wash_type'], $row['total_amount'], $row['date_washed'], $row['loyalty_type'], $row['discount'], $row['added_loyalty_point'], $row['total_loyalty_point'], $row['logged_in_user']));
                // fputcsv($file, array($row['wash_count'], $row['driver_name'], $row['co_phone'], $row['car_registration_no'], $row['no_of_time_washed'], $row['no_of_time_to_free_wash'], $row['body_type'], $row['car_wash_type'], $row['total_amount'], $row['date_washed'], $row['loyalty_type'], 'Discount(%)', 'Earned Points', 'Total Available Points', 'Logged in User'));
            }

            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', 'cwo_master.cwo_company', 'cwo_master.cwo_isd', 'cwo_master.cwo_phone', 'other_service_reports.record_count')
        ->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;
        $dataBag['cwo_company'] = $data[0]->cwo_company;
        if($data[0]->cwo_phone != ''){
            // $dataBag['cwo_isd'] = $data[0]->cwo_isd;
            $dataBag['cwo_phone'] = '+' . $data[0]->cwo_isd . $data[0]->cwo_phone;
        } else {
            $dataBag['cwo_phone'] = '';
        }
        $dataBag['record_count'] = $data[0]->record_count;
        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("Y/m/d", 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;
        $dataDisplay=[];
        $dataArray = [];
        // echo "<pre>";print_r($data->toArray());exit;
        if($data != ''){
            foreach ($data as $d) {
                $dataDisplay['service_id'] = $d->id;
                $dataDisplay['service'] = $d->description;
                $dataDisplay['price'] = $d->price;
                $dataDisplay['qty_in_stock_applicable'] = $d->qty_in_stock_applicable;
                if($d->quantity != ''){
                    $dataDisplay['quantity_in_stock'] = $d->quantity;
                } else {
                    $dataDisplay['quantity_in_stock'] = '';
                }
                $getPr = OtherServiceReportToProduct::where('other_service_report_id', $id)->where('other_service_id', $d->id)->get();
                $dataDisplay['exists'] = $getPr->toArray();
                $dataArray[] = $dataDisplay;
            }
        }
        // echo "<pre>";print_r($dataArray);exit;
        $dataBag['dataArray'] = $dataArray;

        $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([
            'service_id' => 'required',
            // 'optional_extra_price' => 'numeric|nullable',
            // 'name' => 'required',
            // 'car_registration_no' => 'required|unique:co_car,car_registration_no,' . $request->input('car_id'),
        ], [
            'service_id.required' => 'Please choose atleast one service.',
            // 'name.required' => 'Please enter a driver name.',
            // 'car_registration_no.unique' => 'This car registration number already exists.'
        ]);
        $service_id = $request->input('service_id');
        // echo "<pre>";print_r($service_id);
        $price = $request->input('price');
        // echo "<pre>";print_r($price);
        $quantity = $request->input('quantity');
        // echo "<pre>";print_r($quantity);
        $other_service_report_id = $id;

        $name = $request->input('name');
        if($name == ''){
            $name = 'Annonymous';
        }
        $email = $request->input('email');
        $isd_code = $request->input('isd_code');
        $phone = $request->input('phone');

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

        $dt = Carbon::now();

        $data = OtherServiceReport::findOrFail($id);

        $amount = 0; 
        $total_amount = 0; 

        DB::delete("DELETE FROM `other_service_report_to_products` WHERE `other_service_report_id` = " . $other_service_report_id . "");
        if (count($service_id) > 0) {
            for ($i = 0; $i < count($service_id); $i++) {
                // echo $service_id[$i] . ' - ' . $price[$i] . ' - ' . $quantity[$i] . ' - ' .   '<br>';
                // $getPrice = WashCategoryBodyType::where('servic '<br>';
                $getPrice = OtherService::where('id', $service_id[$i])->first();
                $service_price = $getPrice->price;
                // echo $service_id[$i] . ' - ' . $service_price . ' - ' . $quantity[$i] . ' - ' .   '<br>';

                // $total_price = $price[$i] * $quantity[$i];
                $total_price = $service_price * $quantity[$i];
                // echo 'total price -> ' . $total_price . "<br>";
                $total_amount = $total_amount + $total_price;

                $assignServices = OtherServiceReportToProduct::create([
                        'other_service_report_id'=> $other_service_report_id,
                        'other_service_id'=> $service_id[$i],
                        'price'=> $price[$i],
                        'quantity'=> $quantity[$i],
                        'total_price'=> $price[$i] * $quantity[$i],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);

                if($getPrice->qty_in_stock_applicable == 1) {
                    $remaining_quantity = $getPrice->quantity - $quantity[$i];
                    $getPrice->quantity = $remaining_quantity;
                    $getPrice->save();
                }



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

        $data->update([
            'name' => $name,
            'email' => $email,
            'isd_code' => $isd_code,
            'phone' => $phone
        ]);

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


        return back()->with('success', 'Other Services 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);
    }

    public function quantityCheck(Request $request)
    {
        $service_id = $request->service_id;
        $quantity = $request->quantity;

        $record = OtherService::findorfail($service_id);
        $qty_in_stock_applicable = $record->qty_in_stock_applicable;
        $quantity_in_stock = $record->quantity;

        if($qty_in_stock_applicable == 1){
            if($quantity_in_stock >= $quantity){
                $status = 1;
                $message = 'success';
            } else {
                $status = 0;
                $message = 'Quantity should be within ' . $quantity_in_stock;
            }
        } else {
            $status = 1;
            $message = 'success';
        }


        // 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' => $message, 'status' => $status], 200);
    }

}
