<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Hash;

use App\Mail\NewUserNotification;
use Illuminate\Support\Facades\Mail;

use App\Models\PendingUser;
use App\Models\User;
use App\Models\TypeUser;

class Pending_UserController extends Controller
{
    public function ListPendingUsers()
    {
        $pend_users = PendingUser::all();
         return view('email/pendingUsers', compact('pend_users'));
    }

    public function ShowFormUser($id){
        $pend_user = PendingUser::findOrFail($id);
        $types = TypeUser::all();
        return view ('Admin.CrudUsers.createUser', compact('pend_user','types'));
    }


    public function store(Request $request){   
        
     $request->validate([
        'name' => 'required',
        'lastName' => 'required',
        'pending_email' => 'required|email|unique:pending_users,pending_user_email|unique:users,email',
        'pending_phone' => 'required',
        'pending_nif' => 'required',
        'pending_password' => 'required|min:8|confirmed',
     ]);

     $joinName = $request->get('name') . ' ' . $request->get('lastName');

    //  $pendingUser = new PendingUser([
    //     'pending_user_name' => $joinName,
    //      'pending_user_email' => $request->get('pending_email'),
    //      'pending_user_phone' => $request->get('pending_phone'),
    //      'pending_user_nif' => $request->get('pending_nif'),
    //      'pending_user_password' => Hash::make($request->get('pending_password')),
    //  ]);

     $pendingUser = new PendingUser();
     $pendingUser->pending_user_name = $joinName;
     $pendingUser->pending_user_email = $request->get('pending_email');
     $pendingUser->pending_user_phone = $request->get('pending_phone');
     $pendingUser->pending_user_nif = $request->get('pending_nif');
     $pendingUser->pending_user_password = Hash::make($request->get('pending_password'));

     $pendingUser->save();

      // Enviar email de notificação para todos os Super_Administrador
    $superAdmins = User::where('type_users', 'Super_Administrador')->get();
    $newUserNotification = new NewUserNotification();
    
    foreach ($superAdmins as $superAdmin) {
        Mail::to($superAdmin->email)->send($newUserNotification);
    }

    return redirect('/formulario')->with('success', 'O seu registro foi enviado e aguarda aprovação.');
}

}
