<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use App\Models\PasswordReset;

use Carbon\Carbon; 
use App\Models\User; 
#use Illuminate\Mail; 
use Illuminate\Support\Facades\Hash;
use DB; 
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Mail;


use App\Events\NotificationEvent;
use App\Models\AdminNotification;
use App\Events\AdminNotificationEvent;


class PasswordResetController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth:admin', ['except' => ['create', 'submitForgetPasswordForm', 'submitResetPasswordForm', 'showResetPasswordForm']]);

        //
        // $this->middleware('auth:admin');

        // $adminUser = auth()->guard('admin')->user();

        // if (!$adminUser)
        // {
        //     return response()->json(['error' => 'Unauthorized.'], 401);
        // }

    }

    public function showResetPasswordForm($token) { 
       return view('auth.forgetPasswordLink', ['token' => $token]);
    }

    /**
     *
     * @return response()
     */
    public function submitForgetPasswordForm(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users',
        ]);
    
        $token = Str::random(64);
    
        DB::table('password_resets')->insert([
            'email' => $request->email, 
            'token' => $token, 
            'created_at' => Carbon::now()
          ]);
    
        Mail::send('email.forgetPassword', ['token' => $token], function($message) use($request){
            $message->to($request->email);
            $message->subject('AVIO Interiors - Reset Password');
        });
    

        $notification = AdminNotification::create(['cta_label' => 'view']);

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

        if($user){

            $notification->instigator_id = $user->id;
            $notification->message = $user->first_name.' '.$user->last_name.' requests a password reset.';
            $notification->href = 'users/'.$user->id;

            $notification->save();

            $notification = $notification->toArray();
            $notification['instigator'] = $user;

            event(new AdminNotificationEvent($notification));
        }


        return response()->json(['status' => 'ok',  'info' => 'We have e-mailed your password reset link!'], 200);
    }

    
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function submitResetPasswordForm(Request $request)
    {
         $validator = Validator::make($request->all(), [
            'email' => 'required|email|exists:users',
            'password' => [
                'required',
                'string',
                'min:6',
                'confirmed',
                'regex:/[A-Z]/',    // Almeno una lettera maiuscola
                'regex:/[0-9]/'     // Almeno un numero
            ],
            'password_confirmation' => 'required'
        ], [
            'password.regex' => 'Password must contain at least one uppercase letter and one number.'
        ]);
        
        if ($validator->fails()) {
            if ($request->expectsJson() || $request->ajax()) {
                return response()->json(['status' => 'error', 'errors' => $validator->errors()], 422);
            } else {
                // In case of a normal web request, show errors
                $token = $request->token;
                $errors = $validator->errors();
                return view('auth.forgetPasswordLink', compact('token', 'errors'));
            }
        }
    
        $updatePassword = DB::table('password_resets')
                            ->where([
                              'email' => $request->email, 
                              'token' => $request->token
                            ])
                            ->first();
    
        if(!$updatePassword){
            return response()->json(['status' => 'error', 'message' => 'Invalid token!'], 400);
        }
    
        $user = User::where('email', $request->email)
                    ->update(['password' => Hash::make($request->password)]);
    
        DB::table('password_resets')->where(['email'=> $request->email])->delete();
        
        // Check if the request is an AJAX/API request or a normal web request
        if ($request->expectsJson() || $request->ajax()) {
            return response()->json(['status' => 'ok', 'info' => 'Password updated successfully!'], 200);
        } else {
            // Redirect the user to the /user/ page after password reset
            return response('Password updated successfully!', 302)
                ->header('Location', '/user/');
        }
    }



}
