<?php

namespace twa\ecomauth\controllers\v1;

use App\Http\Controllers\Controller;
use Carbon\Carbon;
use twa\apilibs\traits\APITrait;
use twa\ecomauth\controllers\EcomUsersRegistration;
use twa\ecomauth\models\EcomUsersVerificationChallengesModel;

use twa\ecomauth\repositories\AuthenticateRepository;
use twa\ecomauth\repositories\CommonRepository;
use twa\ecomauth\repositories\OTPRepository;

use twa\ecomgeneral\models\EcomUsersModel;
use Validator;

class ResetPasswordController extends Controller
{
    use APITrait;

    public function __construct()
    {
        $this->AuthenticateRepository = new AuthenticateRepository();
        $this->CommonRepository = new CommonRepository();
        $this->OTPRepository = new OTPRepository();
    }


    public function requestResetPassword($store , $lang , $type_slug){

        $user = session('auth_login_user');

        if(!$user){ return abort("403" , "User not found"); }

        if(!is_null($type_slug) && !in_array($type_slug , ["phone" , "email"])){
            $type = null;
        }else{
            $type = $type_slug;
        }

        $challenge = $this->OTPRepository->sendChallenge($user , $type , true);

        if(!$challenge){
            return $this->CommonRepository->redirectAsError('limit-exceeded-verifications');
        }

        session(['challenge' => $challenge , 'challenge_verified' => null ]);

        $sent_to = $this->CommonRepository->getChallengeSentTo($challenge , $user);

        return view('EcomAuthViews::v1.verify-pin' , [
           'type' => in_array($type , ["phone" , "email"]) ? $type : null,
           'target' => route('verify-reset-password' ,  ['type_slug' => $type_slug ] ),
           'sent_to' => $sent_to,
           'resend_target' => route('request-reset-password' ,  ['type_slug' => $type_slug ]),
            'expires_after' => Carbon::now()->diffInSeconds(Carbon::parse($challenge->expires_at))
        ]);
    }

    public function verifyRequestResetPassword($store , $lang , $type_slug){
        $result = null;

        $challenge = session("challenge");
        if(!$challenge){ return abort(404); }

        Validator::make(request()->all(), [
            'code' => 'required'
        ])->after(function($validator) use (&$result , $challenge){

            $challenge_code = $challenge->challenge;

            $code = implode("", request()->input('code'));

            $result = $this->OTPRepository->verify($challenge_code , $code , true);

            if(!$result){
                $validator->errors()->add('code', 'Something went wrong, try again later');
            }else {
                if (!$result['verification']) {
                    $validator->errors()->add('code', 'Your pin is incorrect. Please enter a valid one or resend');
                }
            }
        })->validate();

        session(['challenge_verified' => true ]);

        return redirect()->route('account-reset-password' , ['type_slug' => $type_slug]);
    }


    public function renderResetPassword($store , $lang , $type_slug){
        $user = session('auth_login_user');
        $challenge_verified = session('challenge_verified');
        $challenge = session('challenge');

        if(!$user || !$challenge_verified || !$challenge){ return abort(404); }
        if($challenge->ecom_users_id != $user["id"] ){ return abort(404); }

        return view('EcomAuthViews::v1.reset-password' , ['user' => $user]);
    }

    public function resetPassword($store , $lang , $type_slug){

        $user = session('auth_login_user');
        $challenge_verified = session('challenge_verified');
        $challenge = session('challenge');

        if(!$user || !$challenge_verified || !$challenge){ return abort(404); }
        if($challenge->ecom_users_id != $user["id"] ){ return abort(404); }

        $validator = Validator::make(request()->all(), [
            'new_password' => 'required',
            'confirm_password' => 'required|same:new_password'
        ])->validate();

        $user->password = md5(request()->new_password);
        $user->save();

        session([
            "login" => $this->AuthenticateRepository->getProfile($user),
            'challenge_verified' => null,
            'auth_login_user' => null
            ]);

        return redirect()->route('redirect-login');
    }












}
