<?php

namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;
use App\Models\User;
use App\Models\Meeting;
use Carbon\Carbon;
use App\Models\PrayerLog;
use App\Models\PrayerPoint;

class LeaderController extends Controller
{
    public function LeaderLogin(Request $request){

        $validator = Validator::make($request->all(), [
            'email_or_phone' => [
                'required',
                function ($attribute, $value, $fail) {
                    if (!filter_var($value, FILTER_VALIDATE_EMAIL) && !preg_match('/^\d{10,12}$/', $value)) {
                        $fail('The email or phone number must be a valid email or a phone number with 10-12 digits.');
                    }
                }
            ],
            'password' => 'required',
        ]);
    
         if ($validator->fails()) {
            $errors = $validator->errors()->all(); 
        
            return response()->json([
                'status' => 422,
                'message' => $errors, 
            ], 422);
        }
            

        $validatedData = $validator->validated();
        
        $user = User::where('email', $validatedData['email_or_phone'] ?? null)
                ->orWhere('phone_no', $validatedData['email_or_phone'] ?? null)
                ->first();
        
        // Check if user exists, password matches, and 
        if (!$user || !Hash::check($validatedData['password'], $user->password)) {
            return response()->json([
                'status' => 401,
                'message' => 'Invalid email ,phone_no or password',
            ], 401); 
        }

        if (!in_array($user->user_role, ['Pastor', 'Prayer (Leader)', 'Senior Prayer Warrior (Leader)'])) {
            return response()->json([
                'status' => 403,
                'message' => 'Unauthorized access. Only users with the Leader role are authorized.',
            ], 403);
        }
        
        if ($user->user_status == 'Inactive User') {
            return response()->json([
                'status' => 403,
                'message' => 'Your Account is Inactive, please contact to administrator.',
            ], 403);
        }
            
        // Generate authentication token
         $token = $user->createToken($user->email . 'Token')->plainTextToken;
         $church_name = $user->church ? $user->church->church_name : null;
         $church_logo = $user->church ? asset($user->church->church_logo) : null;


        return response()->json([
            'status' => 200,
            'message' => 'Login successful',
            'user' => [
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'phone_no' => $user->phone_no,
                'email'=> $user->email,
                'user_role'=> $user->user_role,
                'user_status'=> $user->user_status,
                'church_name' => $church_name,
                'profile_photo' => asset($user->profile_photo),
                'church_logo' => $church_logo,
            ],
            
            'token' => $token,
        ], 200);
    }

    public function ViewProfile(Request $request)
    {
        try {
            $user = Auth::user();
    
            if (!$user) {
                return response()->json([
                    'status' => 401,
                    'message' => 'Unauthorized: User not authenticated',
                ], 401);
            }
    
            return response()->json([
                'status' => 200,
                'message' => 'Profile retrieved successfully',
                'user' => [
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'phone_no' => $user->phone_no,
                    'email' => $user->email,
                    'user_role' => $user->user_role,
                    'user_status' => $user->user_status,
                    'profile_photo' =>  $user->profile_photo 
                    ? asset($user->profile_photo) 
                    : asset('user_profile/profile.png')
                ],
            ], 200);
        } catch (\Exception $e) {
            \Log::error('Error in UpdateThemePoint function: ' . $e->getMessage());
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }
    
    public function UpdateProfile(Request $request)
    {
        try {
            $user = Auth::user();
    
            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 404);
            }
    
            // Validate request data
            $validator = Validator::make($request->all(), [
                'first_name' => 'required|string|max:255',
                'last_name' => 'required|string|max:255',
                'phone_no' => 'required|digits:10|unique:users,phone_no,' . $user->id,
     
            ]);
    
             if ($validator->fails()) {
                $errors = $validator->errors()->all(); 
            
                return response()->json([
                    'status' => 422,
                    'message' => $errors, 
                ], 422);
            }
            
    
            // Update user profile using validated data
            $user->update($validator->validated());

                     // Update user profile
                $user->first_name = $request->input('first_name');
                $user->last_name = $request->input('last_name');
                $user->phone_no = $request->input('phone_no');
                $user->save();
         
    
            return response()->json([
                'status' => 200,
                'message' => 'Profile updated successfully',
                'user' => [
                    'first_name' => $user->first_name,
                    'last_name' => $user->last_name,
                    'phone_no' => $user->phone_no,
                    'email' => $user->email,
                    'user_role' => $user->user_role,
                    'user_status' => $user->user_status,
                    'profile_photo' => $user->profile_photo 
                    ? asset($user->profile_photo) 
                    : asset('user_profile/profile.png')
                ],
            ], 200);
        } catch (\Exception $e) {
             \Log::error('Error in UpdateThemePoint function: ' . $e->getMessage());
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

     public function UpdateProfilePic(Request $request)
    {
        try {
            $user = Auth::user();
         
            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 401);
            }
        
            $validator = Validator::make($request->all(), [
                'profile_photo' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', 
            ]);
        
             if ($validator->fails()) {
                $errors = $validator->errors()->all(); 
            
                return response()->json([
                    'status' => 422,
                    'message' => $errors, 
                ], 422);
            }
            

    
            if ($request->hasFile('profile_photo')) {
      
                $file = $request->file('profile_photo');
                $filename = 'profile_' . uniqid() . '.' . $file->getClientOriginalExtension(); 
        
    
                $path = public_path('images/user_profile/' . $filename);
                $file->move(public_path('images/user_profile'), $filename); 
        
            
                $user->profile_photo = 'images/user_profile/' . $filename; 
                $user->save();
        
                return response()->json([
                    'status' => 200,
                    'message' => 'Profile photo updated successfully',
                    'profile_photo' => asset('images/user_profile/' . $filename), 
                ], 200);
            }
      
            return response()->json([
                'status' => 400,
                'message' => 'No file uploaded',
            ], 400);
        } catch (\Exception $e) {
            \Log::error('Error updating profile picture: ' . $e->getMessage());
    
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

   public function Progress()
   {
        try {
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'status' => 401,
                'message' => 'Unauthorized: User not authenticated',
            ], 401);
        }

        //My progress
            $meetingCount = PrayerLog::where('user_id', $user->id)->count();
           $user_id_prayed = PrayerLog::where('user_id', $user->id)->where('status','Prayed')->count();

        // is_prayed_by
       $total_my_prayed_prayer_points = PrayerLog::where('church_id', $user->church_id)
                                    ->where('user_id', $user->id)
                                    ->where('status','Prayed')
                                    ->count();
        
        //Interaceessory Army app[records on the basis of church
        $TotalChurchPrayerMeetings = Meeting::where('church_id', $user->church_id)->count();
        $TotalPrayerWarriors = User::where('church_id',$user->church_id)
        ->where('user_role','Prayer Warrior')->count();
        
        $prayer_points_prayed_count = PrayerLog::where('user_id',$user->id)
                                    ->where('status','Prayed')->count(); 
      
        //My Prayercell scorecard
        $TotalPrayerWarriorsstatus = User::where('church_id',$user->church_id)
                                         ->where('user_status','Prayer Warrior')->count();
          
        $TotalChampionWarriorsstatus = User::where('church_id',$user->church_id)
                                        ->where('user_status','Champion Warrior')->count();
          
        $TotalEliteWarriorsstatus = User::where('church_id',$user->church_id)
                                        ->where('user_status','Elite Warrior')->count();
          
        // Prayer Warrior count for the current month
        $CurrentMonthPrayerWarriors = User::where('church_id', $user->church_id)
                                        ->where('user_role', 'Prayer Warrior')
                                        ->whereMonth('created_at', Carbon::now()->month)
                                        ->whereYear('created_at', Carbon::now()->year)
                                        ->count();

        // Prayer Warrior count for the last month
        $LastMonthPrayerWarriors = User::where('church_id', $user->church_id)
                                   ->where('user_role', 'Prayer Warrior')
                                   ->whereMonth('created_at', Carbon::now()->subMonth()->month)
                                   ->whereYear('created_at', Carbon::now()->subMonth()->year)
                                   ->count();
            
        //Last two month
        $LastToLastMonthPrayerWarriors = User::where('church_id', $user->church_id)
                                    ->where('user_role', 'Prayer Warrior')
                                    ->whereMonth('created_at', Carbon::now()->subMonths(2)->month)
                                    ->whereYear('created_at', Carbon::now()->subMonths(2)->year)
                                    ->count();
        
        // Church prayer meetings count for the current month
        $CurrentMonthChurchMeetings = Meeting::where('church_id', $user->church_id)
                                    ->whereMonth('created_at', Carbon::now()->month)
                                    ->whereYear('created_at', Carbon::now()->year)
                                    ->count();

        // Church prayer meetings count for the last month
        $LastMonthChurchMeetings = Meeting::where('church_id', $user->church_id)
                                    ->whereMonth('created_at', Carbon::now()->subMonth()->month)
                                    ->whereYear('created_at', Carbon::now()->subMonth()->year)
                                    ->count();

        // Church prayer meetings count for the last-to-last month
        $LastToLastMonthChurchMeetings = Meeting::where('church_id', $user->church_id)
                            ->whereMonth('created_at', Carbon::now()->subMonths(2)->month)
                            ->whereYear('created_at', Carbon::now()->subMonths(2)->year)
                            ->count();
                            
                            
        //current month prayed points in church             
         $CurrentMonthPrayedPoints = 
            $this->getMonthlyPrayedPoints(PrayerLog::class, $user->church_id, 0);
    

        $LastMonthPrayedPoints = 
            $this->getMonthlyPrayedPoints(PrayerLog::class, $user->church_id, 1);
   

        $LastToLastMonthPrayedPoints = 
            $this->getMonthlyPrayedPoints(PrayerLog::class, $user->church_id, 2);
          
        return response()->json([
            'status' => 200,
            'message' => 'Progress retrieved successfully',
            'data' => [
                'intercessory_army' => [
                    'TotalChurchPrayerMeetings' => $TotalChurchPrayerMeetings,
                    'total_prayer_warriors' => $TotalPrayerWarriors,
                    'prayer_points_prayed_count'=>$prayer_points_prayed_count,
                ],
                'progress' => [
                    'user_role' => $user->user_role,
                    'user_status' => $user->user_status,
                    'meeting_count' => $meetingCount,
                    'my_prayed_prayer_points'=>$total_my_prayed_prayer_points,
                ],
                'Prayercellscorecard'=>[
                    'TotalChampionWarriorstatus'=>$TotalChampionWarriorsstatus,
                    'TotalEliteWarriorsstatus'=>$TotalEliteWarriorsstatus,
                    'TotalPrayerWarriorsstatus'=>$TotalPrayerWarriorsstatus,
                    
                    'CurrentMonthPrayerWarriors'=>$CurrentMonthPrayerWarriors,
                    'LastMonthPrayerWarriors'=>$LastMonthPrayerWarriors,
                    'LastToLastMonthPrayerWarriors'=>$LastToLastMonthPrayerWarriors,
                    
                    'CurrentMonthChurchMeetings'=>$CurrentMonthChurchMeetings,
                    'LastMonthChurchMeetings'=>$LastMonthChurchMeetings,
                    'LastToLastMonthChurchMeetings'=>$LastToLastMonthChurchMeetings,
                    
                    'CurrentMonthPrayedPoints'=>$CurrentMonthPrayedPoints,
                    'LastMonthPrayedPoints'=>$LastMonthPrayedPoints,
                    'LastToLastMonthPrayedPoints'=>$LastToLastMonthPrayedPoints,
                ],
            ],
        ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }
    
    public function getMonthlyPrayedPoints($table, $churchId, $monthsAgo = 0)
    {
        return $table::where('church_id', $churchId)
            ->where('status', 'Prayed')
            ->whereMonth('created_at', Carbon::now()->subMonths($monthsAgo)->month)
            ->whereYear('created_at', Carbon::now()->subMonths($monthsAgo)->year)
            ->count();
    }
}
