<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\LoginLog;
use App\Models\PasswordLog;
use App\Mail\RegisterMail;
use App\Services\UserService;
use Illuminate\Auth\Events\Registered;

class AuthController extends Controller
{
    private $UserService;

    public function __construct(UserService $UserService)
    {
        $this->UserService = $UserService;
    }

    public function register(Request $request): \Illuminate\Http\JsonResponse
    {
        try {
            $messages = [
                'email.email' => 'Email格式不正確。',
                'email.unique' => 'Email無法使用。',
                'password.min' => '密碼至少需要8碼。',
                'password.confirmed' => '確認密碼有誤。',
            ];

            //Validated
            $validateUser = Validator::make($request->all(),
            [
                'name' => ['required', 'string', 'max:255'],
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'string', 'min:8', 'confirmed'],
            ], $messages);

            if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    'message' => '驗證錯誤',
                    'errors' => $validateUser->errors()
                ], 500);
            }

            $user = User::create([
                'name' => $request->name,
                'email' => $request->email,
                'permission' => '100',
                'contact_name' => $request->contact_name,
                'phone' => $request->phone,
                'tax_number' => $request->tax_number,
                'password' => Hash::make($request->password),
                'api_token' => Str::random(64),
                'uuid' => Str::random(64),
            ], 201);

            event(new Registered($user));

            return response()->json([
                'status' => true,
                'message' => 'User Created Successfully',
                'token' => $user->api_token
            ], 200);

        } catch (\Throwable $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    protected function guard()
    {
        return Auth::guard();
    }

    protected function credentials(Request $request)
    {
        return $request->only('email', 'password');
    }

    protected function attemptLogin(Request $request)
    {
        return $this->guard()->attempt(
            $this->credentials($request), $request->boolean('remember')
        );
    }

    public function login(Request $request): \Illuminate\Http\JsonResponse
    {
        $key = Str::lower($request->input('email')).'|'.$request->ip();

        if (RateLimiter::tooManyAttempts($key, 5)) {
            $seconds = RateLimiter::availableIn($key);
            $errors = ["login" => ["嘗試登入失敗多次，請在 {$seconds} 秒後重試。"]];
            return response()->json([
                'status' => false,
                'message' => "嘗試登入失敗多次，請在 {$seconds} 秒後重試。",
                'errors' => $errors
            ], 429);
        }

        try {
            //Validated
            $validateUser = Validator::make($request->all(),
                [
                    'email' => ['required', 'email'],
                    'password' => ['required'],
                    'captcha' => ['required', 'captcha'],
                ]);

            if($validateUser->fails()){
                return response()->json([
                    'status' => false,
                    'message' => '驗證失敗！',
                    'errors' => $validateUser->errors()
                ], 500);
            }

            if ($this->attemptLogin($request)) {
                if ($request->hasSession()) {
                    $request->session()->put('auth.password_confirmed_at', time());
                }

                $request->session()->regenerate();

                $user = Auth::user();

                if (!$user->hasVerifiedEmail()) {
                    $errors = ["email" => ["尚未進行信箱驗證！"]];
                    return response()->json([
                        'status' => false,
                        'message' => '尚未進行信箱驗證！',
                        'errors' => $errors
                    ], 400);
                }

                if($user->passwordLog()->max('created_at') == null) {
                    PasswordLog::create([
                        'user_id' => $user->id,
                        'password' => $user->password
                    ]);
                }

                $user->load('group.items');

                $user->system_role = $this->UserService->getUserHasSubSystem($user->id);

                LoginLog::create([
                    'ip_location' => $request->ip(),
                    'user_id' => Auth::user()->id,
                ]);

                RateLimiter::clear($key);
                
                return response()->json([
                    'status' => true,
                    'message' => 'Logged In Successfully',
                    'data' => $user
                ], 200);
            }

            RateLimiter::hit($key, 60);
            $errors = ["account" => ["帳號或密碼錯誤！"]];
            return response()->json([
                'status' => false,
                'message' => '帳號或密碼錯誤',
                'errors' => $errors
            ], 500);

            /*if(!Auth::attempt($request->only(['account', 'password']), true)){
                
            }*/

        } catch (\Throwable $e) {
            return response()->json([
                'status' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }

    public function logout(Request $request)
    {
        session()->flush();
        Auth::logout();
    }

    protected function send(array $data)
    {
        try {
            $data['subject'] = 'WOOBOBEE驗證信';
            $data['msg'] = '您好，歡迎使用WOOBOBEE，請點擊下方連結前往驗證！';
            $data['url'] = redirect('/home')->getTargetUrl();
    
            Mail::to($data['email'])->cc(["robby@kinghan.com"])->send(new RegisterMail($data));
            Log::info($data);

        } catch (\Exception $e) {

            Log::info($e);

        }
    }
}
