<?php

namespace App\Http\Controllers\API;

use App\Consulting;
use App\ConsultingComplaint;
use App\ConsultingEvaluate;
use App\ConsultingRequest;
use App\ConsultingTopic;
use App\Http\Controllers\Controller;
use App\Http\Requests\API\ConsultingBookingRequest;
use App\Http\Requests\API\ConsultingComplaintRequest;
use App\Http\Requests\API\ConsultingEvaluateRequest;
use App\Http\Resources\ConsultingRequestResource;
use App\Http\Resources\ConsultingTopicResource;
use Carbon\Carbon;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class ConsultingController extends Controller
{

    /**
     * Consulting request
     * @param ConsultingBookingRequest $request
     * @return JsonResponse
     */
    public function consultingRequest(ConsultingBookingRequest $request) :JsonResponse
    {
        $data = $request->all();
        $user = Auth::user();
        $consulting = Consulting::whereStatus(1)
//            ->where('type', $request->type)
            ->where('id', $request->consulting_id)->first();
        if (!$consulting){
            return response()->json(['message' => __('consultings.consulting_not_found'),'data' => null], 400);
        }

        $price = $consulting->price;
        $addedValue = settings('added_value');

        if ($request->coupon_code){
            /**
             * for_consulting_request To determine that
             * the verification of the code
             * is in order to request a consultation
             */
            $request['for_consulting_request'] = true;
            $checkCoupon = CouponController::checkCoupon($request);
            $data['coupon_id'] =  $checkCoupon['coupon_id'];
            $data['coupon'] =  $checkCoupon['coupon'];
            $price = $checkCoupon['total'];
        }


        if(!$request->coupon_code) {
            $price = $price+(($price*$addedValue)/100);
            $price = round($price);
        }

        // not_active For zoom consulting
        $data['status'] = 'not_active';
        // active Foreach phone, zoom consulting
        if (in_array($request->consulting_way, ['phone', 'office'])){
            $data['status'] = 'active';
        }

        $paymentWay = [
            2 => 'visa_master',
            6 => 'mada',
            11 => 'apple_pay',
            14 => 'stc_pay',
            4 => 'sadad',
            20 => 'visa_master_direct',
            9 => 'visa_master_direct_3ds_flow',
            5 => 'benefit',
            8 => 'uae_debit_cards',
            1 => 'knet',
            3 => 'amex',
            7 => 'qatar_debit_cards'
        ];

        $data['pay_way'] = $paymentWay[$request->pay_way] ?? null;
        $data['user_id'] = $user->id;
        $data['consulting_id'] = $request->consulting_id;
        $data['user_name'] = $user->name;
        $data['user_phone'] = $user->phone;
        $data['user_email'] = $user->email;
        $data['consulting_type'] = $request->type;
        $data['consulting_date'] = $consulting->consulting_date;
        $data['consulting_time'] = $consulting->consulting_time;
        $data['total'] =  $price;
        $data['service_name'] =  __('consultings.consulting_request').
            __('activeConsultings.'.$consulting->type).
            __('activeConsultings.'.$consulting->way);
        $data['consulting_price'] = $consulting->price;


        /**
         * Here initializing payment
         * And if there's any errors in payment
         * must stop next steps
         */

        $consultingRequest = ConsultingRequest::create($data);

        $consulting->update(['status' => 0]);
        $couponId = $data['coupon_id'] ?? null;
        if ($couponId){
            $coupon = $data['coupon'];
            $coupon->update([
                'available_users' => ($coupon->available_users-1),
                'used_count' => ($coupon->used_count+1),
            ]);
        }

        $consultingRequest = ConsultingRequestResource::make($consultingRequest);

        return response()->json(['message' => __('consultings.consulting_don_successfully'), 'data' => $consultingRequest], 200);


    }

    /**
     * Get dates and times for consulting
     * @param Request $request
     * @return JsonResponse
     */
    public function getConsultingDateAndTime(Request $request) :JsonResponse
    {

        $date = Carbon::now()->format('Y-m-d');
        // When click on consulting way to get dates
        if ($request->consulting_way && !$request->consulting_date & !$request->consulting_id){
            $dates = Consulting::whereStatus(1)->orderBy('id', 'desc')
                ->where('consulting_date', '>=', $date)
//                    ->where('type', $request->type)
                ->where('way', $request->consulting_way)
                ->cursor()->pluck('consulting_date')->toArray();

            if (!count($dates)){
                return response()->json(['message' => __('consultings.no_data'),'data' => null], 400);
            }

            return response()->json(['message' => '', 'data' => array_values(array_unique($dates))], 200);
        }

        // When click on date box to get times
        if ($request->consulting_date && $request->consulting_way && !$request->consulting_id){
            $times = Consulting::whereStatus(1)
//                    ->where('type', $request->type)
                ->where('consulting_date', '>=', $date)
                ->where('way', $request->consulting_way)
                ->where('consulting_date', '=', $request->consulting_date)->cursor();

            if (!count($times)){
                return response()->json(['message' => __('consultings.no_data'),'data' => null], 400);
            }
            $allConsultingTimes = [];
            foreach ($times as $time) {
                $allConsultingTimes[] = [
                    'consulting_id' => $time->id,
                    'time' => date('h:i', strtotime($time->consulting_time)),
                    'local_time' => date('h:i A', strtotime($time->consulting_time)),
                ];
            }
            return response()->json(['message' => '', 'data' => $allConsultingTimes], 200);

        }

        // When click on time box to get price
        if ($request->consulting_id){
            $consulting = Consulting::whereStatus(1)->whereId($request->consulting_id)
                ->where('consulting_date', '>=', $date)->first();
            if (!$consulting){
                return response()->json(['message' => __('consultings.no_data'),'data' => null], 400);
            }
            $addedValue = settings('added_value');
            $price = $consulting->price + (($consulting->price*$addedValue)/100);
            $price = round($price);
            $data = [
                'consulting_id' => $consulting->id,
                'consulting_way' => $request->consulting_way,
//                    'consulting_type' => $consulting->type,
                'consulting_date' => $consulting->consulting_date,
                'consulting_time' => date('h:i A', strtotime($consulting->consulting_time)),
                'price' => $price,
//                    'time' => date('h:i A', strtotime($consulting->consulting_time))
            ];
            return response()->json(['message' => '', 'data' => $data]);

        }


    }

    /**
     * Get user consultings
     * @return JsonResponse
     */
    public function myConsulting() :JsonResponse
    {
        $user = Auth::user();
        $consultingRequests = $user->consultings()->orderByDesc('id')->cursor()->groupBy('status');
        $allConsultingRequests = [];

        foreach ($consultingRequests as $status => $consultingRequest) {
            $allConsultingRequests[$status] = ConsultingRequestResource::collection($consultingRequest);
        }
        return response()->json(['message' => '', 'data' => $allConsultingRequests], 200);
    }

    /**
     * Consulting details
     * @param $id
     * @return JsonResponse
     */
    public function myConsultingDetails($id) :JsonResponse
    {
        $user = Auth::user();
        $consultingRequest = ConsultingRequest::find($id);

        if (!$consultingRequest || $user->id != $consultingRequest->user_id){
            return response()->json(['message' => __('activeConsultings.consultaongs_not_found'), 'data' => null], 400);
        }
        $consultingRequest = ConsultingRequestResource::make($consultingRequest);
        return response()->json(['message' => '', 'data' => $consultingRequest], 200);
    }

    /**
     * Consulting evaluates
     * @param ConsultingEvaluateRequest $request
     * @param $id
     * @return JsonResponse
     */
    public  function consultingEvaluate(ConsultingEvaluateRequest $request, $id) :JsonResponse
    {
        $user = Auth::user();
        $consultingRequest = ConsultingRequest::find($id);

        if (!$consultingRequest){
            return response()->json(['message' => __('activeConsultings.consultaongs_not_found'), 'data' => null], 400);
        }

        if ($user->id != $consultingRequest->user_id){
            return response()->json(['message' => __('consultingEvaluates.evaluate_not_allowed'), 'data' => null], 400);
        }

        if($consultingRequest->status != 'finished'){
            return response()->json(['message' => __('consultingEvaluates.consulting_not_finished_yet'), 'data' => null], 400);
        }

        $consultingEvaluateBefore = ConsultingEvaluate::where('consulting_request_id', $consultingRequest->id)->first();

        if ($consultingEvaluateBefore){
            return response()->json(['message' => __('consultingEvaluates.consulting_evaluated_before'), 'data' => null], 400);
        }

        $data = $request->all();
        $data['consulting_request_id'] = $consultingRequest->id;
        $data['user_id'] = $user->id;
        $evaluate = ConsultingEvaluate::create($data);
        return response()->json(['message' => __('consultingEvaluates.consulting_evaluated_success'), 'data' => $evaluate], 200);

    }

    /**
     * Consulting complaints
     * @param ConsultingComplaintRequest $request
     * @param $id
     * @return JsonResponse
     */
    public  function consultingComplaint(ConsultingComplaintRequest $request) :JsonResponse
    {
        $user = Auth::user();

        $consultingRequest = ConsultingRequest::find($request->consulting_request_id);

        if (!$consultingRequest){
            return response()->json(['message' => __('activeConsultings.consultaongs_not_found'), 'data' => null], 400);
        }

        if ($user->id != $consultingRequest->user_id){
            return response()->json(['message' => __('consultingComplaints.complaint_not_allowed'), 'data' => null], 400);
        }

        if($consultingRequest->status != 'finished'){
            return response()->json(['message' => __('consultingComplaints.consulting_not_finished_yet'), 'data' => null], 400);
        }
        $data = $request->all();
        $data['consulting_request_id'] = $consultingRequest->id;
        $data['user_id'] = $user->id;

        $consultingComplaint = ConsultingComplaint::create($data);
        return response()->json(['message' => __('consultingComplaints.consulting_complaint_success'), 'data' => $consultingComplaint], 200);
    }

    /**
     * Update consulting complaint
     * @param ConsultingComplaintRequest $request
     * @param $id
     * @return JsonResponse
     */
    public  function updateConsultingComplaint(ConsultingComplaintRequest $request, $id) :JsonResponse
    {
        $user = Auth::user();
        $consultingRequest = ConsultingRequest::find($id);

        if (!$consultingRequest){
            return response()->json(['message' => __('activeConsultings.consultaongs_not_found'), 'data' => null], 400);
        }

        if ($user->id != $consultingRequest->user_id){
            return response()->json(['message' => __('consultingComplaints.complaint_not_allowed'), 'data' => null], 400);
        }

        if($consultingRequest->status != 'finished'){
            return response()->json(['message' => __('consultingComplaints.consulting_not_finished_yet'), 'data' => null], 400);
        }

        $complaint = ConsultingComplaint::where('consulting_request_id', $id)->first();

        $data = $request->all();
        $data['consulting_request_id'] = $id;
        $data['user_id'] = $user->id;
        $complaint->update($data);
        return response()->json(['message' => __('consultingComplaints.consulting_complaint_success'), 'data' => $complaint], 200);
    }


    public function consultingTopics()
    {
        $topics = ConsultingTopic::withDescription();
        $data  = ConsultingTopicResource::collection($topics);
        return response()->json(['message' => '', 'data' => $data], 200);
    }


}
