<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\CarWashOwner;
use App\Models\OtherService;
use App\Models\CarOwnerCar;
use App\Models\OtherServiceReport;
use App\Models\OtherServiceReportToProduct;
use App\Models\CwoPasscode;
use App\Models\CarOwner;
use App\Models\CwoPreBookingType;
use Carbon\Carbon;
use DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Validator;

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


    public function index(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_id' => 'required',
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $cwo_id = $request->input('cwo_id');
        $getCurrency = getCurencyOfCwo($cwo_id);
        $data = OtherService::where('cwo_id', $cwo_id)->where('is_active', 1)->orderBy('description', 'asc')->select('id', 'description', 'price', 'qty_in_stock_applicable', 'quantity')->get();
        // echo "<pre>";print_r($data->toArray());exit;
        $otherServiceStatus = getOtherServicesCount($cwo_id);
        // echo $otherServiceStatus;exit;
        $dataDisplay=[];
        $dataArray = [];
        if($data != ''){
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['service'] = $d->description;
                $dataDisplay['price'] = $d->price;
                // $dataDisplay['qty_in_stock_applicable'] = $d->qty_in_stock_applicable;
                $dataDisplay['qty_in_stock_applicable'] = 1;
                if($d->quantity != ''){
                    $dataDisplay['quantity_in_stock'] = $d->quantity;
                } else {
                    $dataDisplay['quantity_in_stock'] = '';
                }
                
                $dataArray[] = $dataDisplay;
            }
        }
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'currency' => $getCurrency,
            'otherServiceStatus' => $otherServiceStatus,
            'otherServices' => $dataArray
        ]);
    }

    public function addOtherServices(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_id' => 'required',
                // 'car_id' => 'required',
                // 'name' => 'required',
                // 'isd_code' => 'required',
                // 'phone' => 'required',
                // 'email' => 'required',
                // 'wash_id' => 'required',
                'other_services' => 'required',
                'total_amount' => 'required'
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $cwo_id = $request->input('cwo_id');
        $car_id = $request->input('car_id');
        $name = $request->input('name');
        $isd_code = $request->input('isd_code');
        $phone = $request->input('phone');
        $email = $request->input('email');
        $wash_id = $request->input('wash_id');
        $other_services = $request->input('other_services');
        $total_amount = $request->input('total_amount');

        if($name == '') {
            $name = 'Annonymous';
        }
        if($wash_id == '') {
            $wash_id = 0;
        }
        if($car_id != '') {
            $getCar = CarOwnerCar::where('id', $car_id)->select('co_id')->first();
            $co_id = $getCar->co_id;
        } else {
            $co_id = 0;
        }
        // echo 'name- ' . $name . ', wash_id-  '. $wash_id . ', co_id - ' . $co_id;exit;
        $dt = Carbon::now(); 

        $user_id = $request->input('user_id');  
        if($user_id == ''){
            $user_id = 0;
        }

        $getRecordCount = OtherServiceReport::select('record_count')->where('cwo_id', $cwo_id)->orderBy('id', 'desc')->take(1)->get();
        // echo $getRecordCount->count();exit;
        // print_r($getRecordCount->toarray());exit;
        if ($getRecordCount->count() > 0){
            $record_count = $getRecordCount[0]->record_count + 1;
        } else {
            $record_count = 1;
        }
        
        // echo $record_count;exit;

        /*insert into other_service_reports table starts*/
        $insertOtherService = OtherServiceReport::create([
            'co_id'=> $co_id,
            'name'=> $name,
            'isd_code'=> $isd_code,
            'phone'=> $phone,
            'email'=> $email,
            'total_amount'=> $total_amount,
            'payment_status'=> 0,
            'date'=> date('Y-m-d'),
            'time'=> date('H:i:s'),
            'cwo_id'=> $cwo_id,
            'record_count'=> $record_count,
            'wash_id'=> $wash_id,
            'cwo_user_id'=> $user_id,
            'created_at'=>$dt->toDayDateTimeString(),
            'updated_at'=>$dt->toDayDateTimeString()
        ]);
        /*insert into other_service_reports table ends*/     
        $other_service_report_id = $insertOtherService->id;

        if($other_services != ''){
            $other_services_id_array=json_decode($other_services, true);
            if($other_services_id_array != ""){  // if starts
                foreach ($other_services_id_array as $e) { // foreach starts
                    $assignWashType = OtherServiceReportToProduct::create([
                        'other_service_report_id'=> $other_service_report_id,
                        'other_service_id'=> $e['other_service_id'],
                        'price'=> $e['unit_price'],
                        'quantity'=> $e['quantity'],
                        'total_price'=> $e['total_price'],
                        'created_at'=>$dt->toDayDateTimeString(),
                        'updated_at'=>$dt->toDayDateTimeString()
                    ]);

                    $getOtherService = OtherService::findorfail($e['other_service_id']);
                    // echo $getOtherService->qty_in_stock_applicable . ' - ' . $getOtherService->quantity . "<br>";
                    if($getOtherService->qty_in_stock_applicable == 1) {
                        $remaining_quantity = $getOtherService->quantity - $e['quantity'];
                        $getOtherService->quantity = $remaining_quantity;
                        $getOtherService->save();
                    }


                } // foreach starts
            } // if ends
        }
        // exit;
        
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'other_service_report_id' => $other_service_report_id,
        ]);
    }

    public function getStatus(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_id' => 'required',
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $cwo_id = $request->input('cwo_id');
        $otherServiceStatus = getOtherServicesCount($cwo_id);
        // echo $otherServiceStatus;exit;

        $cwo_detail = CarWashOwner::select('allow_prebooking')->where('id', $cwo_id)->first();
        $allow_prebooking = $cwo_detail->allow_prebooking;
        $dataArray = [];
        if($allow_prebooking == 1) {
            $prebookingTypes = CwoPreBookingType::select('cwo_pre_booking_types.prebooking_type_id', 'pre_booking_types.type')
                            ->join('pre_booking_types', 'pre_booking_types.id', 'cwo_pre_booking_types.prebooking_type_id')
                            ->orderBy('pre_booking_types.id', 'asc')
                            ->where('cwo_pre_booking_types.cwo_id', $cwo_id)
                            ->get();
            $dataArray = $prebookingTypes;                
        }
        
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'otherServiceStatus' => $otherServiceStatus,
            'allow_prebooking' => $allow_prebooking,
            'preBookingType' => $dataArray
        ]);
    }

    public function revenue_withOutSplit(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_id' => 'required'
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

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

        $getCurrency = getCurencyOfCwo($cwo_id);
        $today = date('Y-m-d');

        /***************** today starts *********************/
        $todayRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'cash')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInCash->toArray());exit;
        $todayRevenueInCash = $todayRevenueInCash[0]->total_revenue != '' ? $todayRevenueInCash[0]->total_revenue : 0;

        $todayRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInCard->toArray());exit;
        $todayRevenueInCard = $todayRevenueInCard[0]->total_revenue != '' ? $todayRevenueInCard[0]->total_revenue : 0;

        $todayRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInContract->toArray());exit;
        $todayRevenueInContract = $todayRevenueInContract[0]->total_revenue != '' ? $todayRevenueInContract[0]->total_revenue : 0;

        // $todayRevenueInCash = $todayRevenueInCash + $todayRevenueInContract;
        /******************* today ends ************************/

        /**************** month to date starts ****************/
        $one_month_ago = date('Y-m-d', strtotime('-1 month', strtotime($today)));
        $monthAgoRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'cash')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInCash = $monthAgoRevenueInCash[0]->total_revenue != '' ? $monthAgoRevenueInCash[0]->total_revenue : 0; 
        
        $monthAgoRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInCard = $monthAgoRevenueInCard[0]->total_revenue != '' ? $monthAgoRevenueInCard[0]->total_revenue : 0;

        $monthAgoRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInContract = $monthAgoRevenueInContract[0]->total_revenue != '' ? $monthAgoRevenueInContract[0]->total_revenue : 0;     

        // $monthAgoRevenueInCash = $monthAgoRevenueInCash + $monthAgoRevenueInContract;
        /**************** month to date ends *******************/

        /**************** year to date starts ****************/
        $one_year_ago = date('Y-m-d', strtotime('-1 year', strtotime($today)));
        $yearAgoRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'cash')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInCash = $yearAgoRevenueInCash[0]->total_revenue != '' ? $yearAgoRevenueInCash[0]->total_revenue : 0; 
        
        $yearAgoRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInCard = $yearAgoRevenueInCard[0]->total_revenue != '' ? $yearAgoRevenueInCard[0]->total_revenue : 0; 

        $yearAgoRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInContract = $yearAgoRevenueInContract[0]->total_revenue != '' ? $yearAgoRevenueInContract[0]->total_revenue : 0;  

        // $yearAgoRevenueInCash = $yearAgoRevenueInCash + $yearAgoRevenueInContract;
        /**************** year to date ends *******************/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            // 'totalRevenue' => $getCurrency[0]->symbol . $total_revenue,
            'currency' => $getCurrency,
            'todayRevenueInCash' => "$todayRevenueInCash",
            'todayRevenueInCard' => "$todayRevenueInCard",
            'todayRevenueInContract' => "$todayRevenueInContract",
            'monthToDateRevenueInCash' => "$monthAgoRevenueInCash",
            'monthToDateRevenueInCard' => "$monthAgoRevenueInCard",
            'monthToDateRevenueInContract' => "$monthAgoRevenueInContract",
            'yearToDateRevenueInCash' => "$yearAgoRevenueInCash",
            'yearToDateRevenueInCard' => "$yearAgoRevenueInCard",
            'yearToDateRevenueInContract' => "$yearAgoRevenueInContract",
        ]);
    }

    public function revenue(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'cwo_id' => 'required'
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

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

        $getCurrency = getCurencyOfCwo($cwo_id);
        $today = date('Y-m-d');

        /***************** today starts *********************/
        $todayRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.cash_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'cash')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInCash->toArray());exit;
        $todayRevenueInCash = $todayRevenueInCash[0]->total_revenue != '' ? $todayRevenueInCash[0]->total_revenue : 0;

        $todayRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.card_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            // ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInCard->toArray());exit;
        $todayRevenueInCard = $todayRevenueInCard[0]->total_revenue != '' ? $todayRevenueInCard[0]->total_revenue : 0;

        $todayRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInContract->toArray());exit;
        $todayRevenueInContract = $todayRevenueInContract[0]->total_revenue != '' ? $todayRevenueInContract[0]->total_revenue : 0;

        $todayRevenueInEft = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'eft' . '%')
            ->whereDate('other_service_reports.date', '=', $today)
            ->get();
        // echo "<pre>";print_r($todayRevenueInEft->toArray());exit;
        $todayRevenueInEft = $todayRevenueInEft[0]->total_revenue != '' ? $todayRevenueInEft[0]->total_revenue : 0;

        // $todayRevenueInCash = $todayRevenueInCash + $todayRevenueInContract;
        /******************* today ends ************************/

        /**************** month to date starts ****************/
        $one_month_ago = date('Y-m-d', strtotime('-1 month', strtotime($today)));
        $monthAgoRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.cash_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'cash')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInCash = $monthAgoRevenueInCash[0]->total_revenue != '' ? $monthAgoRevenueInCash[0]->total_revenue : 0; 
        
        $monthAgoRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.card_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            // ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInCard = $monthAgoRevenueInCard[0]->total_revenue != '' ? $monthAgoRevenueInCard[0]->total_revenue : 0;

        $monthAgoRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInContract = $monthAgoRevenueInContract[0]->total_revenue != '' ? $monthAgoRevenueInContract[0]->total_revenue : 0;    

        $monthAgoRevenueInEft = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'eft' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->whereMonth('other_service_reports.date', Carbon::now()->month)
            ->get();
        $monthAgoRevenueInEft = $monthAgoRevenueInEft[0]->total_revenue != '' ? $monthAgoRevenueInEft[0]->total_revenue : 0; 

        // $monthAgoRevenueInCash = $monthAgoRevenueInCash + $monthAgoRevenueInContract;
        /**************** month to date ends *******************/

        /**************** year to date starts ****************/
        $one_year_ago = date('Y-m-d', strtotime('-1 year', strtotime($today)));
        $yearAgoRevenueInCash = OtherServiceReport::select(DB::raw('SUM(other_service_reports.cash_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'cash')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInCash = $yearAgoRevenueInCash[0]->total_revenue != '' ? $yearAgoRevenueInCash[0]->total_revenue : 0; 
        
        $yearAgoRevenueInCard = OtherServiceReport::select(DB::raw('SUM(other_service_reports.card_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            // ->where('other_service_reports.payment_details', 'card')
            // ->where('other_service_reports.payment_details', 'like', '%' . 'card' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInCard = $yearAgoRevenueInCard[0]->total_revenue != '' ? $yearAgoRevenueInCard[0]->total_revenue : 0; 

        $yearAgoRevenueInContract = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'contract' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInContract = $yearAgoRevenueInContract[0]->total_revenue != '' ? $yearAgoRevenueInContract[0]->total_revenue : 0;  

        $yearAgoRevenueInEft = OtherServiceReport::select(DB::raw('SUM(other_service_reports.total_amount) as total_revenue'))
            ->join('cwo_master','cwo_master.id','=','other_service_reports.cwo_id')
            ->where('other_service_reports.cwo_id', $cwo_id)
            ->where('other_service_reports.status', 1)
            ->where('other_service_reports.payment_details', 'like', '%' . 'eft' . '%')
            ->whereYear('other_service_reports.date', Carbon::now()->year)
            ->get();
        $yearAgoRevenueInEft = $yearAgoRevenueInEft[0]->total_revenue != '' ? $yearAgoRevenueInEft[0]->total_revenue : 0;

        // $yearAgoRevenueInCash = $yearAgoRevenueInCash + $yearAgoRevenueInContract;
        /**************** year to date ends *******************/

        return response()->json([
            'success' => 1,
            'message' => 'Success',
            // 'totalRevenue' => $getCurrency[0]->symbol . $total_revenue,
            'currency' => $getCurrency,
            'todayRevenueInCash' => "$todayRevenueInCash",
            'todayRevenueInCard' => "$todayRevenueInCard",
            'todayRevenueInContract' => "$todayRevenueInContract",
            'todayRevenueInEft' => "$todayRevenueInEft",
            'monthToDateRevenueInCash' => "$monthAgoRevenueInCash",
            'monthToDateRevenueInCard' => "$monthAgoRevenueInCard",
            'monthToDateRevenueInContract' => "$monthAgoRevenueInContract",
            'monthToDateRevenueInEft' => "$monthAgoRevenueInEft",
            'yearToDateRevenueInCash' => "$yearAgoRevenueInCash",
            'yearToDateRevenueInCard' => "$yearAgoRevenueInCard",
            'yearToDateRevenueInContract' => "$yearAgoRevenueInContract",
            'yearToDateRevenueInEft' => "$yearAgoRevenueInEft",
        ]);
    }

    public function serviceSoldList_withOutSplit(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'cwo_id' => 'required',
                'per_page' => 'required',
                'total_viewed' => 'required'
            ],
            [
                'cwo_id.required' => 'Please enter CWO ID',
                'per_page.required' => 'Please enter per page',
                'total_viewed.required' => 'Please enter a total records viewed',
            ]
        );

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

        $cwo_id = $request->input('cwo_id');
        $per_page = $request->input('per_page');
        $total_viewed = $request->input('total_viewed');

        $getCurrency = getCurencyOfCwo($cwo_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')
            ->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)
            ->where('other_service_reports.status',1)
            ->orderBy('other_service_reports.id', 'desc');
        $dataCount = $data->count();
        $data = $data->limit($per_page)->offset($total_viewed);
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit; 

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone'] = $d->phone;
                $dataDisplay['email'] = $d->email;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['payment_status_id'] = $d->payment_status;
                if($d->payment_status == 1) {
                    $dataDisplay['payment_status'] = 'Paid';
                } else {
                    $dataDisplay['payment_status'] = 'Not Paid';
                }
                $dataDisplay['payment_details'] = $d->payment_details;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }

                $services = OtherServiceReportToProduct::select('other_services.id', 'other_services.description as service', 'other_services.price as unit_price', 'other_services.qty_in_stock_applicable', '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', $d->id)
                            ->orderBy('other_service_report_to_products.id', 'asc')
                            ->get();
                // $dataDisplay['services'] = $services;
                if($services != '') {  
                    $servicesArr = [];
                    foreach($services as $ser) {
                        $other_products =
                                array(
                                    'id' => $ser->id,
                                    'service' => $ser->service,
                                    'unit_price' => $ser->unit_price,
                                    // 'qty_in_stock_applicable' => $ser->qty_in_stock_applicable,
                                    'qty_in_stock_applicable' => 1,
                                    'quantity' => $ser->quantity,
                                    'total_price' => $ser->total_price,
                                );
                        array_push($servicesArr, $other_products);      
                        $dataDisplay['services'] = $servicesArr;          
                    } 
                }

                $dataArray[] = $dataDisplay;
            }
        }  
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'currency' => $getCurrency,
            'count' => $dataCount,
            'otherServiceList' => $dataArray
        ]); 
    }

    public function serviceSoldList(Request $request){
        $validate = Validator::make(
            $request->all(),
            [
                'cwo_id' => 'required',
                'per_page' => 'required',
                'total_viewed' => 'required'
            ],
            [
                'cwo_id.required' => 'Please enter CWO ID',
                'per_page.required' => 'Please enter per page',
                'total_viewed.required' => 'Please enter a total records viewed',
            ]
        );

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

        $cwo_id = $request->input('cwo_id');
        $per_page = $request->input('per_page');
        $total_viewed = $request->input('total_viewed');

        $getCurrency = getCurencyOfCwo($cwo_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', 'other_service_reports.card_amount', 'other_service_reports.cash_amount')
            ->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)
            ->where('other_service_reports.status',1)
            ->orderBy('other_service_reports.id', 'desc');
        $dataCount = $data->count();
        $data = $data->limit($per_page)->offset($total_viewed);
        $data = $data->get(); 
        // echo "<pre>";print_r($data->toArray());exit; 

        $dataDisplay=[];
        $dataArray = [];
        if($data != '') {
            foreach ($data as $d) {
                $dataDisplay['id'] = $d->id;
                $dataDisplay['name'] = $d->name;
                $dataDisplay['isd_code'] = $d->isd_code;
                $dataDisplay['phone'] = $d->phone;
                $dataDisplay['email'] = $d->email;
                $dataDisplay['total_amount'] = $d->total_amount;
                $dataDisplay['card_amount'] = $d->card_amount;
                $dataDisplay['cash_amount'] = $d->cash_amount;
                $dataDisplay['payment_status_id'] = $d->payment_status;
                if($d->payment_status == 1) {
                    $dataDisplay['payment_status'] = 'Paid';
                } else {
                    $dataDisplay['payment_status'] = 'Not Paid';
                }
                $dataDisplay['payment_details'] = $d->payment_details;
                if($d->date != '') {
                    $dataDisplay['date']  = date("d/m/Y", strtotime($d->date));
                } else {
                    $dataDisplay['date']  = '';
                }
                if($d->time != '') {
                    $dataDisplay['time']  = date("h:i a", strtotime($d->time));
                } else {
                    $dataDisplay['time']  = '';
                }

                $services = OtherServiceReportToProduct::select('other_services.id', 'other_services.description as service', 'other_services.price as unit_price', 'other_services.qty_in_stock_applicable', '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', $d->id)
                            ->orderBy('other_service_report_to_products.id', 'asc')
                            ->get();
                // $dataDisplay['services'] = $services;
                if($services != '') {  
                    $servicesArr = [];
                    foreach($services as $ser) {
                        $other_products =
                                array(
                                    'id' => $ser->id,
                                    'service' => $ser->service,
                                    'unit_price' => $ser->unit_price,
                                    // 'qty_in_stock_applicable' => $ser->qty_in_stock_applicable,
                                    'qty_in_stock_applicable' => 1,
                                    'quantity' => $ser->quantity,
                                    'total_price' => $ser->total_price,
                                );
                        array_push($servicesArr, $other_products);      
                        $dataDisplay['services'] = $servicesArr;          
                    } 
                }

                $dataArray[] = $dataDisplay;
            }
        }  
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'currency' => $getCurrency,
            'count' => $dataCount,
            'otherServiceList' => $dataArray
        ]); 
    }

    public function paymentStatusChange_withOutSplit(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'other_service_report_id' => 'required',
                'payment_status' => 'required',
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

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

        $record = OtherServiceReport::find($other_service_report_id);
        $record->payment_status = $payment_status;
        $record->payment_details = $payment_mode;
        $record->save(); 

        return response()->json([
            'success' => 1,
            'message' => 'Payment status has been changed successfully'
        ]);

    }

    public function paymentStatusChange(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'other_service_report_id' => 'required',
                'payment_status' => 'required',
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

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

        $card_amount = $request->input('card_amount');
        if($card_amount == '') {
            $card_amount = 0.00;
        }
        $cash_amount = $request->input('cash_amount');
        if($cash_amount == '') {
            $cash_amount = 0.00;
        }

        $record = OtherServiceReport::find($other_service_report_id);
        $record->payment_status = $payment_status;
        $record->payment_details = $payment_mode;

        $record->card_amount = $card_amount;
        $record->cash_amount = $cash_amount;
        $record->split_flag = 1;

        $record->save(); 

        return response()->json([
            'success' => 1,
            'message' => 'Payment status has been changed successfully'
        ]);

    }

    public function cancel(Request $request){
        $validate = Validator::make($request->all(), 
            [
                'other_service_report_id' => 'required',
                // 'cwo_id' => 'required',
                // 'code' => 'required'
            ]);
            
        if($validate->fails()){
            $errorString = implode(",",$validate->messages()->all());
            return response()->json([
                'success' => 0,
                // 'message' => $validate->errors(),
                'message' => $errorString,
            ]);
        }

        $other_service_report_id = $request->input('other_service_report_id');
        $cwo_id = $request->input('cwo_id');
        $code = $request->input('code');

        if($code != ''){ // new version with passcode
            $getPasscode = CwoPasscode::where('cwo_id', $cwo_id)->first();
            if($getPasscode != ''){
                if($getPasscode->code == $code){
                    $record = OtherServiceReport::find($other_service_report_id);
                    $record->status = 2; // cancel 
                    $record->payment_status = 0;
                    $record->payment_details = '';
                    $record->total_amount = 0.00;
                    $record->save(); 

                    /*push starts*/
                    /*$getCwo = CarWashOwner::where('id', $record->cwo_id)->select('cwo_company')->first();
                    $cwo_company = $getCwo->cwo_company;
                    $getCo = CarOwner::where('id', $record->co_id)->select('co_fname', 'co_lname', 'fcm_token')->first();
                    $fcm_token = $getCo->fcm_token;
                    // $fcm_token = "eL409rTNQ1CiR4Y5wOUGh7:APA91bGLnCrYpQPlqwPQa_TnCvkZrT-kkmRmTiXyNFDhu7sJ3los_EZXOji2jBTcAc3haxJbCFq0Yb1iYa8l_ifAtCnK36Ut5Lw_ctTB-WV5LUfNnO8IQZFG4BEuohI1MYJuYdt_lnPo";
                    $notification_title = "Other Services Purchase Cancelled";
                    $notification_body = 'Your purchase of other services has been calcelled in ' . $cwo_company;
                    $data=array("request_type" => "notification");
                    // sendFcmNotification($fcm_token, $notification_title, $notification_body, $data);*/
                    /*push ends*/

                    return response()->json([
                        'success' => 1,
                        'message' => 'Purchase of other services has been cancelled successfully.'
                    ]);
                } else {
                    return response()->json([
                        'success' => 0,
                        'message' => 'Passcode to cancel did not match.',
                    ]); 
                }
            } else {
                return response()->json([
                    'success' => 0,
                    'message' => 'Passcode to cancel did not match.',
                ]);    
            }
        } else { //old version without passcode
            $record = OtherServiceReport::find($other_service_report_id);
            $record->status = 2; // cancel 
            $record->payment_status = 0;
            $record->payment_details = '';
            $record->total_amount = 0.00;
            $record->save();   
            return response()->json([
                'success' => 1,
                'message' => 'Purchase of other services has been cancelled successfully.'
            ]);  
        }

    }

    public function updateOtherServicesReportCount(Request $request){
        $record = OtherServiceReport::get();
        // echo "<pre>";print_r($record->toArray());exit;
        foreach ($record as $d) {
            $record = OtherServiceReport::find($d->id);
            $getRecordCount = OtherServiceReport::where('cwo_id', $record->cwo_id)->where('id', '<', $d->id)->count();
            // echo $getRecordCount . "<br>";
            $record_count = $getRecordCount + 1;
            $record->record_count = $record_count;
            $record->save(); 
        }
        exit;
    }

    public function splitFlag(Request $request){
        // $wash = OtherServiceReport::where('split_flag', 0)->limit(100)->get();
        $wash = OtherServiceReport::where('payment_status', 1)->where('split_flag', 0)->limit(1000)->get();
        // echo "<pre>";print_r($wash->toArray());exit;
        foreach ($wash as $d) {
            $record = OtherServiceReport::find($d->id);
            $payment_details = $record->payment_details;
            $payment_status = $record->payment_status;
            $total_amount = $record->total_amount;
            echo $d->id . " - " . $payment_details . "<br>";

            if($payment_status == 1){
                if($payment_details =='cash') {
                    $record->cash_amount = $total_amount;
                    // $record->split_flag = 1;
                    $record->save();    
                }
                if($payment_details =='Cash') {
                    $record->cash_amount = $total_amount;
                    // $record->split_flag = 1;
                    $record->save();    
                }
                if (str_contains($payment_details, 'Card')) {
                    echo "card-------" . "<br></br></br>";
                    $record->card_amount = $total_amount;
                    // $record->split_flag = 1;
                    $record->save();    
                }
                if (str_contains($payment_details, 'card')) {
                    echo "card-------" . "<br></br></br>";
                    $record->card_amount = $total_amount;
                    // $record->split_flag = 1;
                    $record->save();    
                }
                $record->split_flag = 1;
                $record->save(); 
            }
        }
        // exit;
    }


}
