<?php

namespace App\Http\Controllers\Web;

use App\User;
use App\Verification;
use Illuminate\View\View;
use App\Jobs\VerifyCodeJob;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Contracts\View\Factory;

class VerificationController extends Controller
{


    private $view = 'web.verification.';

    /**
     * check verify code for all type verifications
     * like ['login', 'register', 'password']
     * @param Request $request
     * @return Factory|View
     */
    public function verifyCode(Request $request)
    {
        // dd($request->all());
        $code = Verification::where('code', $request->code);

        if(session()->get('type')){
            $code= $code->where('type', session()->get('type'));
        }
        $code= $code->first();

        // dd(session()->get('type'));
        // dd($code->toArray());
        // $user = User::where('email', $request->email)->where('role', 'user')->firstOrFail();
        // dd($request->user()->toArray());
        $user = $request->user() ?? User::where('role', 'user')
        ->where(function($query) use ($request) {
                $query->where('email', $request->email)
                ->orWhere('phone', $request->email);
        })->firstOrFail();
        // dd($user->toArray());
        if ($code && $user && $user->id == $code->user_id){
            // dd($request->email, $code->toArray(), $user->toArray());
            session()->forget('type');
            // check verify type
            $type= $code->type;
            if ($type == 'login' || $type == 'register'){
                Auth::login($user, true);
                $code->delete();
                return view($this->view.'success_verify', ['route'=> route('loops.available')]);
            } elseif($type == 'password'){
                session()->put('code', $request->code);
                return redirect()->route('user.newPasswordForm');
            } else {
                $user->verifications()->where('type', $type)->where('user_id', $user->id)->delete();
                $meta= $code->metadata ? json_decode($code->metadata, true) : [] ;
                // dd($meta);
                $request->loop_id= $meta['loop_id'] ?? 0;
                if($request->loop_id){
                    if ('cancel' == $type) {
                        return LoopChangeController::doCancel($request);
                    }
                    if ('subscribe' == $type) {
                        $request->share= $meta['share'] ?? 0;
                        $request->period= $meta['period'] ?? 0;
                        $request->month= $meta['month'] ?? 0;
                        # REDIRECT TO WALLET PAGE TO PAY AMOUNT, AND FROM THERE SUBSCRIBE
                        session()->put('verfication_code', $request->code);
                        session()->put('pay_data', $meta);
                        return redirect()->route('userswallet.pay', ['type'=> 'subscribe']);

                    }
                } else {
                    return view($this->view.'success_verify', ['route'=> route('loops.index')]);
                }
            }
        } else {
            return view($this->view.'failed_verify', ['email' => $request->email]);
        }

    }


    /**
     * Remaining Verification operation for user
     * @param $request
     * @return bool
     */
    public static function verificationOperation($request)
    {
        // Check verify type via url
        preg_match('/login|register|password/', URL::current(), $match);
        // dd(URL::current());
        $type = array_shift($match);
        $type=  $type ? $type : $request->type;
        $meta= $request->meta ? json_decode($request->meta, true ) : [];
        // dd($meta);
        if(session()->get('meta')) {
            $meta= $meta + session()->get('meta');
        }
        // dd($type);
        $status = false;
        session()->put('type', $type);

        $user = User::where('role', 'user')
            ->where('email', $request->email)
            ->orWhere('phone', $request->email)->withTrashed()->first();

         if (!$user){
             session()->flash('error', 'auth.failed');
             return false;
         }

         if ($user && $user->deleted_at){
             session()->flash('error', 'users.user_disabled');
             return  false;
         }

        // $code = rand(1111, 9999);
        $code = 1234;
        $data['user'] = $user->name;
        $data['email'] = $user->email;
        $data['code'] = "$code";

        $user->verifications()->whereIn('type', ['login', 'register', 'password', $type, ''])->where('user_id', $user->id)->delete();
        // $user->verifications()->where('user_id', $user->id)->delete();
        // check verify type
        // if ($type == 'login' || $type == 'register'){
        //     $status = Hash::check($request->password, $user->password) ? true : false;
        // } elseif($type == 'password'){
        //     $status = true;
        // } else{
        //     $status = true;
        // }
        // dd($status);
        $status= true;
        // if ($status){
            $data= [
                'user_id' => $user->id,
                'type' => $type,
                'metadata' => json_encode($meta),
                'code' => $code,
            ];
            // dd($data);
            Verification::create($data);
            $data['message']="Code {$code} ";
            $data['phone']=$user->phone;
            VerifyCodeJob::dispatch($data, 'web.verification.email');
        // }
        // dd($type);

        return $status;

    }
}
