<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Models\PasswordReset;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class UserRegisterController extends Controller
{
    function userRegisterView()
    {
        return view('user.auth.register');
    }

    public function showResetLinkView()
    {
        return view('user.email.reset-ps-link-sent-form');
    }

    /*public function userRegister(Request $request)
    {
        //Validate Inputs
        $request->validate([
            'first_name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:5|max:30',
        ]);

        $user = new User();
        $user->first_name = $request->first_name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->assignRole('user');
        $save = $user->save();
        // $last_id = $user->id;
        // $token = $last_id . hash('sha256', \Str::random(120));
        // $actionLink = route('user.verify', ['token' => $token, 'service' => 'Email_verification']);

        // EmailVerify::create([
        //     'user_id' => $last_id,
        //     'token' => $token,
        // ]);

        // $body = "Dear <b>' . $request->first_name . '</b> " ." Thanks for signing up, we just need you to verify your email address to complete setting up your account.";

        // $view = view('user.email.email-template', compact(['actionLink', 'body']))->render();

        // $data = [
        //     'from' => 'Support@Theclubhouse.Com',
        //     'to' => $request->email,
        //     'subject' => "Email Verification",
        //     'body' => $view,
        // ];

        // $mailer = new GeniusMailer();
        // $mailer->sendCustomMail($data);


        if ($save) {
            return redirect()->route('user.login')->with('success', 'User Register Successfully');
        } else {
            return redirect()->back()->with('error', 'Something went wrong, failed to register');
        }
    }*/

    public function userRegister(Request $request)
    {
        // Validate inputs
        $validator = \Validator::make($request->all(), [
            'first_name' => 'required',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:5|max:30',
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        // Save the user
        $user = new User();
        $user->first_name = $request->first_name;
        $user->email = $request->email;
        $user->password = Hash::make($request->password);
        $user->assignRole('user');

        if ($user->save()) {
            return redirect()->route('user.login-view')->with('success', 'Register Successfully');
        } else {
            return response()->json(['success' => false, 'message' => 'Failed to register user.']);
        }
    }



    // public function verify(Request $request)
    // {
    //     $token = $request->token;
    //     $verifyUser = EmailVerify::where('token', $token)->first();
    //     if (!is_null($verifyUser)) {
    //         $user = $verifyUser->user;

    //         if (!$user->email_verified) {
    //             $verifyUser->user->email_verified = 1;
    //             $verifyUser->user->save();

    //             return redirect()->route('user.login')->with('success', 'Your email is verified successfully. You can now login')->with('verifiedEmail', $user->email);
    //         } else {
    //             return redirect()->route('user.login')->with('error', 'Your email is already verified. You can now login')->with('verifiedEmail', $user->email);
    //         }
    //     }
    // }


    public function sentPasswordResetLink(Request $request)
    {

        if ($request->email == '') {
            return redirect()->back()->with('error', 'Please Required Your Email');
        }
        $check_email_not_exists = User::where('email', $request->email)->get();

        if (isset($check_email_not_exists[0])) {

            $token = \Str::random(64);
            $resetpassword = new PasswordReset;
            $resetpassword->email = $request->email;
            $resetpassword->token = $token;
            $resetpassword->save();
            $actionLink = route('user.show-reset-update-view', ['token' => $token, 'email' => $request->email]);

            $body = "We are received a request to reset the password for <b>Your app Name </b> account associated with " . $request->email . ". You can reset your password by clicking the link below";

            $view = view('user.email.sent-to-reset-template', compact(['actionLink', 'body']))->render();

            $data = [
                'from' => 'Support@theBigBearRecovery.Com',
                'to' => $request->email,
                'subject' => "Email Verification",
                'body' => $view,
            ];

            return redirect()->back()->with('success', 'We have e-mailed your password reset link!.');

        } else {
            return redirect()->back()->with('error', 'Your Email not registered');

        }

    }


    public function showResetUpdateView(Request $request, $token = null)
    {
        return view('user.email.password-update-form')->with(['token' => $token, 'email' => $request->email]);
    }

    public function resetPasswordUpdate(Request $request)
    {

        $request->validate([

            'email' => 'required|email|exists:users,email',
            'password' => 'required|min:8',
            'confirm_password' => 'required|min:8|same:password',
        ]);

        $check_token = PasswordReset::where([
            'email' => $request->email,
            'token' => $request->token,
        ])->first();


        if (!$check_token) {
            return back()->with('error', 'Invalid token');
        } else {

            User::where(['email' => $request->email])
                ->update(['password' => Hash::make($request->password),]);
            PasswordReset::where(['email' => $request->email])->delete();

            return redirect()->back()->with('success', 'Your password has been changed! You can login with new password')->with('verifiedEmail', $request->email);

        }


    }


}
