<?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 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('id', '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(); 

        /*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,
            'wash_id'=> $wash_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;
        
        return response()->json([
            'success' => 1,
            'message' => 'Success',
            'otherServiceStatus' => $otherServiceStatus,
        ]);
    }

    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.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.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.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.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.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.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.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.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.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.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 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')
            ->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');
        $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 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');

        $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'
        ]);

    }


}
