<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class UserManagementController extends Controller
{
    public function User(){
        
        $users = User::with('church')->OrderBy('created_at','desc')->get();
        return view('admin.user',compact('users'));
    }
    
    public function EditLeader($id){
        
        $user = User::find($id);
        return view('admin.edit_user',compact('user'));
    }
    
    public function UpdateUser($id,Request $request){
        
        $user = User::find($id);
        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email',
            'user_role' => 'required',
            'user_status'=>'required',
     
        ]);    

        $user->first_name = $request->input('first_name');
        $user->last_name = $request->input('last_name');
        $user->email = $request->input('email');    
        $user->user_role = $request->input('user_role');
        $user->user_status = $request->input('user_status');
        $user->save();

        return redirect()->back()->with('success','User Updated Successfully!');
    }
    
    public function DeleteUser($id){
        try {
            $user = User::find($id);
            if (!$user) {
                return back()->with('error', 'User not found.');
            }
            $user->delete();
            return back()->with('success', 'User Deleted Successfully');
        } catch (Exception $e) {
            
            return back()->with('error', 'An error occurred while deleting the user.');
        }
    }
}
