<?php

namespace TPS\Shop\Http\Controllers;

use Illuminate\Http\Request;
use Hash;
use Webkul\Core\Repositories\SubscribersListRepository;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Str;
use TPS\Shop\Http\Requests\CustomerSignupRequest;
use Webkul\Customer\Repositories\CustomerGroupRepository;
use Webkul\Customer\Repositories\CustomerRepository;
use Webkul\Shop\Http\Controllers\Controller;
use TPS\Shop\Http\Requests\CustomerProfileRequest;


class Registration extends Controller
{
    public function __construct(protected CustomerRepository $customerRepository,
                                protected CustomerGroupRepository $customerGroupRepository,
                                protected SubscribersListRepository $subscriptionRepository)
    {
        $this->_config = request('_config');
    }

    public function verify(Request $request)
    {
        $request->validate([
            'code' => 'required|digits:4'
        ]);

        if($data = $request->session()->get('signup'))
        {
            if($data['token']==$request->input('code') && $customer = $this->customerRepository->create($data))
            {
                return response([
                    'success' => true,
                    'message' => trans('shop::app.customer.signup-form.success'),
                    'redirect' => route($this->_config['redirect'])
                ]);
            }
        }

        return response([
            'message' => trans('auth.failed'),
            'errors'=>[
                'register'=>[
                    trans('shop::app.customer.signup-verification.failed')
                ]
            ]
        ],422);
    }

    public function sendCode(){
        $data = session()->get('signup');
        $data['token'] = rand(1000,9999);
        session()->put('signup',$data);
        Event::dispatch('shop.register.verify', $data);
    }

    public function create(CustomerSignupRequest $request){
        $request->validated();

        if(is_null($request->email))
        {
            $request->email = '';
        }


        $verify = core()->getConfigData('customer.settings.email.verification') ;

        $data = array_merge(request()->only('first_name', 'phone'), [
            'email'                     => $request->email,
            'password'                  => bcrypt(request()->input('password')),
            'api_token'                 => Str::random(80),
            'is_verified'               => ! $verify ,
            'customer_group_id'         => $this->customerGroupRepository->findOneWhere(['code' => 'general'])->id,
            'token'                     => rand(1000,9999),
            'subscribed_to_news_letter' => 0,
        ]);

        session(['signup' => $data]);

        if($verify){

            Event::dispatch('shop.register.verify', $request->merge(['token'=>$data['token']]));
        }
        else{
            $customer = $this->customerRepository->create($data);

            if (! $customer) {

                return response([
                    'message' => trans('auth.failed'),
                    'errors'=>[
                        'register'=>[
                            trans('shop::app.customer.signup-form.failed')
                        ]
                    ]
                ],422);
            }
//            session()->flash('success', trans('shop::app.customer.signup-form.success'));
        }

//        $customer = $this->customerRepository->create($data);

//        if (! $customer) {
//
//            return response([
//                'message' => trans('auth.failed'),
//                'errors'=>[
//                    'register'=>[
//                        trans('shop::app.customer.signup-form.failed')
//                    ]
//                ]
//            ],422);
//        }


//        if (core()->getConfigData('customer.settings.email.verification')) {
//            try {
//                if (core()->getConfigData('emails.general.notifications.emails.general.notifications.verification')) {
//                    Mail::queue(new VerificationEmail(['email' => $data['email'], 'token' => $data['token']]));
//                }
//
//                session()->flash('success', trans('shop::app.customer.signup-form.success-verify'));
//            } catch (\Exception $e) {
//                report($e);
//
//                session()->flash('info', trans('shop::app.customer.signup-form.success-verify-email-unsent'));
//            }
//        } else {
//            try {
//                if (core()->getConfigData('emails.general.notifications.emails.general.notifications.registration')) {
//                    Mail::queue(new RegistrationEmail(request()->all(), 'customer'));
//                }
//
//                if (core()->getConfigData('emails.general.notifications.emails.general.notifications.customer-registration-confirmation-mail-to-admin')) {
//                    Mail::queue(new RegistrationEmail(request()->all(), 'admin'));
//                }
//
//                session()->flash('success', trans('shop::app.customer.signup-form.success-verify'));
//            } catch (\Exception $e) {
//                report($e);
//
//                session()->flash('info', trans('shop::app.customer.signup-form.success-verify-email-unsent'));
//            }
//            session()->flash('success', trans('shop::app.customer.signup-form.success'));
//        }

        return response([
            'success' => true,
            'message' => trans('shop::app.customer.signup-form.success'),
//            'redirect' => route($this->_config['redirect'])
        ]);
    }

    public function update(CustomerProfileRequest $customerProfileRequest)
    {
        $isPasswordChanged = false;

        $data = $customerProfileRequest->validated();

        if (isset($data['date_of_birth']) && $data['date_of_birth'] == '') {
            unset($data['date_of_birth']);
        }

        $data['subscribed_to_news_letter'] = isset($data['subscribed_to_news_letter']) ? 1 : 0;

        if (isset($data['oldpassword'])) {
            if ($data['oldpassword'] != '' || $data['oldpassword'] != null) {
                if (Hash::check($data['oldpassword'], auth()->guard('customer')->user()->password)) {
                    $isPasswordChanged = true;

                    $data['password'] = bcrypt($data['password']);
                } else {
                    session()->flash('warning', trans('shop::app.customer.account.profile.unmatch'));

                    return redirect()->back();
                }
            } else {
                unset($data['password']);
            }
        }

        Event::dispatch('customer.update.before');

        if ($customer = $this->customerRepository->update($data, auth()->guard('customer')->user()->id)) {
            if ($isPasswordChanged) {
                Event::dispatch('user.admin.update-password', $customer);
            }

            Event::dispatch('customer.update.after', $customer);

            if ($data['subscribed_to_news_letter']) {
                $subscription = $this->subscriptionRepository->findOneWhere(['email' => $data['email']]);

                if ($subscription) {
                    $this->subscriptionRepository->update([
                        'customer_id'   => $customer->id,
                        'is_subscribed' => 1,
                    ], $subscription->id);
                } else {
                    $this->subscriptionRepository->create([
                        'email'         => $data['email'],
                        'customer_id'   => $customer->id,
                        'channel_id'    => core()->getCurrentChannel()->id,
                        'is_subscribed' => 1,
                        'token'         => $token = uniqid(),
                    ]);

                    try {
                        Mail::queue(new SubscriptionEmail([
                            'email' => $data['email'],
                            'token' => $token,
                        ]));
                    } catch (\Exception $e) {
                    }
                }
            } else {
                $subscription = $this->subscriptionRepository->findOneWhere(['email' => $data['email']]);

                if ($subscription) {
                    $this->subscriptionRepository->update([
                        'customer_id'   => $customer->id,
                        'is_subscribed' => 0,
                    ], $subscription->id);
                }
            }

            $this->customerRepository->uploadImages($data, $customer);

            session()->flash('success', trans('shop::app.customer.account.profile.edit-success'));

            return redirect()->route($this->_config['redirect']);
        }

        session()->flash('success', trans('shop::app.customer.account.profile.edit-fail'));

        return redirect()->back($this->_config['redirect']);
    }

    public function resetPassword(Request $request){ 

        $request->validate([
            'phone' => 'required|digits:8'
        ]);

        if($customer = $this->customerRepository
            ->where('phone', $request->phone)
            ->first()){

            $res = Event::dispatch('shop.register.verify', $request);

            $res = $res[0];

            if (!$res->successful()) {
                return response()->json([
                    'success' => false,
                    'status' => $res->status(),
                    'error' => $res->body()
                ], $res->status());
            }
        
            return response()->json(['success' => true]);

        }else{
            return response([
                'message' => trans('shop::app.customer.login-text.no_account'),
                'errors'=>[
                    'recovery'=>[
                        trans('shop::app.customer.login-text.no_account')
                    ]
                ]
            ],404);
        }
    }

    public function changePassword(Request $request){
        $request->validate([
            'phone' => 'required|digits:8',
            'token' => 'required',
            'password' => 'required|min:6',
        ]);

        if($customer = $this->customerRepository
            ->where('phone', $request->phone)
            ->first()){

            $res = Event::dispatch('shop.register.checkVerify', $request);

            $res = $res[0]; 

            if ($res->status() !== 200) {
                return response()->json([
                    'success' => false,
                    'status' => $res->status(),
                    'error' => $res->body()
                ], $res->status());
            }

            $customer->password = bcrypt($request->password);
            $customer->save();

            return response()->json(['success' => true,'message' => trans('shop::app.customer.reset-password.reset-success')]);
        }else{
            return response([
                'message' => trans('shop::app.customer.reset-password.wrong-token'),
                'errors'=>[
                    'reset'=>[
                        trans('shop::app.customer.reset-password.wrong-token')
                    ]
                ]
            ],400);
        }
    }

}