<?php

namespace App\Http\Controllers\Auth;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Validation\Rules\Password;

class FirstLoginController extends Controller
{


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create($token, $id)
    {
        return view('auth.first-login', ['token' => $token,'id' => $id]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            //'username' => 'required|email|exists:users',
            'username' => 'required|unique:users,username',
            'password' => [
                'required',
                'string',
                Password::min(8)
                    ->mixedCase()
                    ->numbers()
                    ->symbols(),
                'confirmed'
            ], 
            'password_confirmation' => 'required',
      
        ]);

        $user = User::findorfail($request->id);
      
        $updatePassword = DB::table('password_resets')
                            ->where(['email' => $user->email, 'token' => $request->token])
                            ->first();
      
        if(!$updatePassword)
            return back()->withInput()->with('error', 'Invalid token!'.$request->token);
      
        User::where('id', $user->id)
            ->update([
                'username' => $request->username,
                'password' => Hash::make($request->password)
            ]);
    
        DB::table('password_resets')->where(['email'=> $user->email])->delete();

        $data = array(
            'username' => $request->username,
        );

        Mail::send('mail.welcome', $data, function($message) use($user){
            $message->to($user->email);
            $message->subject('Registration Successful');
        });
    
        return redirect('/login')->with('success', 'Your password has been changed! Please login using your access detail.');
    }

 
}
