<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Notifications\ResetPassword as ResetPasswordNotification;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use ReCaptcha\ReCaptcha;
use Throwable;

class AuthController extends Controller
{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function loginView()
    {
        if (Auth::check()) {
            return redirect()->guest('/');
        } else {
            return view('auth.login', [
                'meta_description' => 'Login/Register',
                'meta_keywords' => 'Login/Register',
                'meta_title' => 'Login/Register'
            ]);
        }
    }

    public function doLogin(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->withInput()->with('errors', ['Invalid email or password']);
        }
        $credentials = $request->only('email', 'password');
        if (Auth::attempt($credentials)) {
            Auth::user()->update(['last_login' => Carbon::now()]);
            if (isset($_COOKIE['els_checkout']) && $_COOKIE['els_checkout']) {
                return redirect('/checkout?' . $_COOKIE['els_checkout']);
            }
            return redirect('/account');
        }
        return redirect(url()->previous())->withInput()->with('errors', ['Invalid email or password']);
    }

    public function signupView()
    {
        if (Auth::check()) {
            return redirect()->guest('/');
        } else {
            return view('auth.login', [
                'meta_description' => 'Register',
                'meta_keywords' => 'Register',
                'meta_title' => 'Register'
            ]);
        }
    }

    public function doRegister(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'name' => 'required|string|min:3|max:50',
            'email' => 'required|string|email|unique:users,email|min:3|max:30',
            'password' => 'required|string|min:6|max:20',
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->withInput()->with('rerrors', $validator->messages()->all());
        }
        $recaptcha = new ReCaptcha(env('RECAPTCHA_SECRET_KEY'));
        $response = $recaptcha->verify($request->input('g-recaptcha-response'), $request->ip());
        if (!$response->isSuccess()) {
            return redirect(url()->previous())->with('rerrors', ['reCAPTCHA validation failed.']);
        }
        try {
            \DB::beginTransaction();
            $user = new User();
            $user->name = $request['name'];
            $user->email = $request['email'];
            $user->type = 2;
            $user->password = Hash::make($request['password']);
            $user->save();
            \DB::commit();
        } catch (Throwable $e) {
            \DB::rollback();
            return redirect(url()->previous())->withInput()->with('rerrors', ['Something went wrong, please try again later!']);
//            return redirect(url()->previous())->withInput()->with('errors', [$e->getMessage()]);
        }
        return redirect(url()->previous())->with('rsuccess', "Account created successfully!");
    }

    public function forgotPasswordView()
    {
        if (Auth::check()) {
            return redirect()->guest('/');
        } else {
            return view('auth.forgot-password', [
                'meta_description' => 'Reset Password',
                'meta_keywords' => 'Reset Password',
                'meta_title' => 'Reset Password'
            ]);
        }
    }

    public function doFP(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'email' => 'required|email'
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->withInput()->with('errors', $validator->messages()->all());
        }
        $user = User::where('email', $request['email'])->first();
        if (!$user) {
            return redirect(url()->previous())->withInput()->with('errors', ['Email not found']);
        }
        DB::table('password_reset_tokens')->insert([
            'email' => $request['email'],
            'token' => Str::random(60),
            'created_at' => Carbon::now()
        ]);
        $tokenData = DB::table('password_reset_tokens')
            ->where('email', $request['email'])->first();

        $user->notify(new ResetPasswordNotification($tokenData->token, $user));
        return redirect(url()->previous())->with('success', "A password reset link has been sent to your email. Please click on that link to reset your password.");
    }

    public function resetPasswordView($token = null)
    {
        if (Auth::check()) {
            return redirect('/');
        } else {
            return view('auth.reset-password', [
                'meta_description' => 'Reset Password',
                'meta_keywords' => 'Reset Password',
                'meta_title' => 'Reset Password',
                'token' => $token
            ]);
        }
    }

    public function doRP(Request $request)
    {
        $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
            'password' => 'required|string|confirmed|min:6|max:10'
        ]);
        if ($validator->fails()) {
            return redirect(url()->previous())->withInput()->with('errors', $validator->messages()->all());
        }
        $tokenData = DB::table('password_reset_tokens')
            ->where('token', $request['token'])->first();
        if (!$tokenData) {
            return redirect(url()->previous())->withInput()->with('errors', ['Invalid Token!']);
        }
        $user = User::where('email', $tokenData->email)->first();
        if (!$user) {
            return redirect(url()->previous())->withInput()->with('errors', ['User not found!']);
        }
        $user->update(['password' => Hash::make($request['password'])]);
        DB::table('password_reset_tokens')->where('email', $user->email)
            ->delete();
        return redirect(url()->previous())->with('success', "Password changed successfully.");
    }

    public function doUP(Request $request)
    {
        if (Auth::check()) {
            $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
                'name' => 'required|string|min:3|max:50',
                'city' => 'required|string|min:3|max:50',
                'state' => 'required|string|min:3|max:50',
                'zip' => 'required|string|min:3|max:50',
                'address' => 'required|string|min:3|max:200',
                'phone' => 'required|string|min:7|max:20'
            ]);
            if ($validator->fails()) {
                return redirect(url()->previous())->withInput()->with('perrors', $validator->messages()->all());
            }
            Auth::user()->update([
                'name' => $request['name'],
                'billing_city' => $request['city'],
                'billing_state' => $request['state'],
                'billing_zip' => $request['zip'],
                'billing_address' => $request['address'],
                'phone' => $request['phone'],
            ]);
            return redirect(url()->previous())->with('psuccess', "Profile updated successfully.");
        } else {
            return redirect('/');
        }
    }

    public function doCP(Request $request)
    {
        if (Auth::check()) {
            $validator = \Illuminate\Support\Facades\Validator::make($request->all(), [
                'password' => 'required',
                'new_password' => 'required|string|confirmed|min:6|max:20|different:password'
            ]);
            if ($validator->fails()) {
                return redirect(url()->previous())->withInput()->with('cperrors', $validator->messages()->all());
            }
            if (!Hash::check($request['password'], Auth::user()->password)) {
                return redirect(url()->previous())->withInput()->with('cperrors', ["You've entered incorrect current password"]);
            }
            Auth::user()->update(['password' => Hash::make($request['new_password'])]);
            return redirect(url()->previous())->with('cpsuccess', "Password changed successfully.");
        } else {
            return redirect('/');
        }
    }
}
