<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Str;
use App\Models\User;
use App\Models\Church;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Exception;
use Mail; 

class LeaderController extends Controller
{
    public function Leaders(){
        
        $leaders = User::with('church')
                ->where('user_role', '!=','Prayer Warrior')
                ->OrderBy('created_at','desc')->get();
                
        return view('admin.leader',compact('leaders'));
    }

    public function AddLeader(Request $request){
        
        $churches = Church::select('id', 'church_name')->get();
         return view('admin.add_leader',compact('churches'));
    }

    public function StoreLeader(Request $request){
        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email|unique:users,email',
            'phone_no' => 'required|digits:10',
            'user_role' => 'required|string',
            'user_status' => 'required|string',
            'church_id' => 'required|exists:churches,id'
        ]);    

        $randomChars = Str::random(4); 
        $specialChars = '!@#$%^&*()'; 
        $randomSpecialChars = substr(str_shuffle($specialChars), 0, 4); 
        $uniquePassword = 'church' . $randomChars . $randomSpecialChars . 'leader';

        // Hash the password before saving
        $hashedPassword = Hash::make($uniquePassword);
        
        $user = new User();
        $user->first_name = $request->first_name;
        $user->last_name = $request->last_name;
        $user->email = $request->email;
        $user->phone_no = $request->phone_no;
        $user->user_role = $request->user_role;
        $user->user_status = $request->user_status;
        $user->church_id = $request->church_id;
        $user->password = $hashedPassword;
        $user->save();
        
         if ($user) {
                // Send Email to User
                Mail::send('emails.invitation', ['email' => $user->email, 'password' => $uniquePassword], function ($message) use ($user) {
                    $message->to($user->email);
                    $message->subject('Invitation to Join Church');
                });
            }
                    
        

        return redirect()->back()->with('success','Leader Added Successfully And Invitation is sent to Leader email address');
    }

    public function UpdateLeader(Request $request,$id){

        $leader =User::find($id);

        $request->validate([
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'email' => 'required|email',
            'phone_no' => 'required|digits:10',
            'user_role' => 'required',
            'user_status' => 'required',
            'church_id' => 'required|exists:churches,id'
        ]);    
        $leader->first_name = $request->input('first_name');
        $leader->last_name = $request->input('last_name');
        $leader->email = $request->input('email');
        $leader->phone_no = $request->input('phone_no');
        $leader->user_role = $request->input('user_role');    
        $leader->user_status = $request->input('user_status');
        $leader->church_id = $request->input('church_id');
        $leader->save();

        return redirect()->back()->with('success','Leader Updated Successfully!');

    }

    public function EditLeader($id){
        
        $leader = User::findOrfail($id);
        $churches = Church::select('id', 'church_name')->get();
        return view('admin.edit_leader',compact('leader','churches'));
    }

    public function DeleteLeader($id){
    try {
            $leader = User::find($id);
            if (!$leader) {

                return back()->with('error', 'Leader not found.');
            }
            $leader->delete();
            return back()->with('success', 'Leader Deleted Successfully');
        } catch (Exception $e) {
            
            return back()->with('error', 'An error occurred while deleting the leader.');
        }
    }
}
