<?php

namespace App\Http\Controllers\Api;
use Illuminate\Support\Facades\Validator;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Models\PrayerPoint;
use App\Models\PrayerCategory;
use App\Models\PrayerSubCategory;

class ChurchPointController extends Controller
{
    public function AddChurchPoint(Request $request)
    {
        try {
            $user = Auth::user();
    
            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 404);
            }
    
            $user_id = $user->id;
            $church_id = $user->church_id;
    
            // Validating fields
            $validator = Validator::make($request->all(), [
                'prayer_point' => 'required|string|max:250',
            ]);
    
              if ($validator->fails()) {
                $errors = $validator->errors()->all(); 
            
                return response()->json([
                    'status' => 422,
                    'message' => $errors, 
                ], 422);
            }
    
            // Fetching the prayer category ID
            $prayer_category_id = PrayerCategory::where('prayer_category_name', 'Pray for my Church')->pluck('id')->first();
    
            if (!$prayer_category_id) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Prayer category not found',
                ], 404);
            }
    
            // Creating a new prayer point
            $Prayerpoint = new PrayerPoint();
            $Prayerpoint->user_id = $user_id;
            $Prayerpoint->church_id = $church_id;
            $Prayerpoint->prayer_category_id = $prayer_category_id;
            $Prayerpoint->prayer_point = $request->prayer_point;
            $Prayerpoint->status = "Active";
            $Prayerpoint->save();
    
            return response()->json([
                'status' => 200,
                'message' => 'Prayer Point Added Successfully',
                // 'Prayerpoint' => $Prayerpoint,
            ], 200);
    
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }
    
    
    public function ShowsChurchPoint()
    {
        try {
             $user = Auth::user();

            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 404);
            }
            
            $prayer_category_id = PrayerCategory::where('prayer_category_name', 'Pray for my Church')->pluck('id')->first();

            $church_prayer_points = PrayerPoint::where('church_id',$user->church_id)
                            ->where('prayer_category_id',$prayer_category_id)
                            ->where('status','Active')
                            ->OrderBy('start_date','desc')
                             ->select('id', 'prayer_point')
                            ->get();
    
            return response()->json([
                'status' => 200,
                'message' => 'Prayer Points retrieved successfully',
                'church_prayer_points' =>$church_prayer_points,
                
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }
    
    public function EditChurchpoint($id)
    {
        try {
            $prayerpoint = PrayerPoint::find($id);
            if (!$prayerpoint) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Prayer Point record not found',
                ], 404);
            }
            return response()->json([
                'status' => 200,
                'message' => 'Prayer Point Data retrieved successfully',
                'prayerpoint' => [
                    'id'=>$prayerpoint->id,
                    'prayer_point' => $prayerpoint->prayer_point,
          
                ],

            ], 200);
        } catch (\Exception $e) {
           
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }

    }

    public function UpdateChurchpoint(Request $request, $id)
    {
        try {
     
                $churchprayerpoint = PrayerPoint::find($id);
                if (!$churchprayerpoint) {
                 return response()->json([
                     'status' => 404,
                     'message' => 'Prayer Point not found',
                 ], 404);
             }
    
             // Validate incoming data
             $validator = Validator::make($request->all(), [
                'prayer_point' => 'required|string|max:250',
             ]);
     
              if ($validator->fails()) {
                $errors = $validator->errors()->all(); 
            
                return response()->json([
                    'status' => 422,
                    'message' => $errors, 
                ], 422);
            }
     
             $churchprayerpoint->prayer_point = $request->input('prayer_point');
             $churchprayerpoint->save();
     
             return response()->json([
                 'status' => 200,
                 'message' => 'Prayer point updated successfully',
                'churchprayerpoint' => [
                     'id'=>$churchprayerpoint->id,
                     'prayer_point' => $churchprayerpoint->prayer_point,
                 ],
             ], 200);
     
         } catch (\Exception $e) {
             return response()->json([
               'status' => 500,
                'message' => 'Internal Server Error',
             ], 500);
         }
    }

    public function DeleteChurchpoint($id)
    {
        try {
            $churchprayerpoint = PrayerPoint::find($id);
    
            if (!$churchprayerpoint) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Church Prayer Point not found',
                ], 404);
            }
            
            $churchprayerpoint->status = 'Inactive';
            $churchprayerpoint->save();
    
            return response()->json([
                'status' => 200,
                'message' => 'Church Prayer point deleted successfully',
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
               'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

    public function FilteredPrayerPoint(Request $request)
    {
        try {
            
            $user = Auth::user();

            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 404);
            }
            
            
            // Fetch the prayer category ID where the name is 'Pray for my Church'
            $prayer_category_id = PrayerCategory::where('prayer_category_name', 'Pray for my Church')->pluck('id')->first();
            
            // Check if the category exists
            if (!$prayer_category_id) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Prayer category "Pray for my Church" not found.',
                ], 404);
            }
    
            // Initialize query for prayer points with the specified category
            $Churchpoint = PrayerPoint::where('prayer_category_id', $prayer_category_id)
                          ->where('church_id',$user->church_id)      
                          ->where('status','Active')
                           ->select('id', 'prayer_point');
                          
            $statsMessage = 'Showing prayer points for the "Pray for my Church" category.';
    
            // Apply additional filters
            if ($request->has('view_all')) {
                
                $prayerPoints = $Churchpoint->get();
                $statsMessage = 'Showing all prayer points.';
                
            } elseif ($request->has('prayed_prayers')) {
                
                 $prayerPoints = $Churchpoint->whereHas('prayerLogs', function($query) {
                    $query->where('status', 'Prayed');
                })
                ->get();
                $statsMessage = 'Showing prayed prayers only.';
                
            } elseif ($request->has('unprayed_prayers')) {
                
               $prayerPoints = $Churchpoint->whereDoesntHave('prayerLogs', function($query) {
                 $query->where('status', 'Prayed');
                 })
                ->get(); 
                $statsMessage = 'Showing unprayed prayers only.';
                
            } elseif ($request->has('new_prayer_points')) {
                
                $prayerPoints = 
                $Churchpoint->where('created_at', '>=', now()->subDays(30))
                    ->orderBy('created_at', 'desc')
                    ->get();
                    $statsMessage = 'Showing The Most recent prayer points.';
                    
            } else {
                $prayerPoints = $Churchpoint->get();
            }
            
            return response()->json([
                'status' => 200,
                'message' => $statsMessage,
                'PrayerPoints' => $prayerPoints,
            ], 200);
    
        } catch (\Exception $e) {
            return response()->json([
               'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }
    
     public function ShowsThemePrayerPoint($id)
    {
        try {
            $user = Auth::user();
    
            if (!$user) {
                return response()->json([
                    'status' => 404,
                    'message' => 'User not found',
                ], 404);
            }
    
            $prayer_category_id = PrayerCategory::where('prayer_category_name', 'Prayer Theme')->pluck('id')->first();
    
            if (!$prayer_category_id) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Prayer category not found',
                ], 404);
            }
    
            $theme_church_prayer_points = PrayerPoint::where('church_id', $user->church_id)
                ->where('prayer_category_id', $prayer_category_id)
                ->where('prayer_sub_category_id', $id) 
                ->where('status', 'Active')
                ->orderBy('created_at', 'desc')
                ->get();
    
            if ($theme_church_prayer_points->isEmpty()) {
                return response()->json([
                    'status' => 404,
                    'message' => 'No prayer points found for this sub-category',
                ], 404);
            }
    
            return response()->json([
                'status' => 200,
                'message' => 'Prayer Points retrieved successfully',
                'data' => $theme_church_prayer_points->map(function ($prayer) {
                    return [
                        'id' => $prayer->id,
                        'prayer_point' => $prayer->prayer_point,
                    ];
                }),
            ], 200);
    
        } catch (\Exception $e) {
            return response()->json([
               'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

    
    public function ShowThemePrayerSubCategory()
    {
    try {
        $user = Auth::user();
    
        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found',
            ], 404);
        }

        $prayer_category_id = PrayerCategory::where('prayer_category_name', 'Prayer Theme')->pluck('id')->first();

        if (!$prayer_category_id) {
            return response()->json([
                'status' => 404,
                'message' => 'Prayer category not found',
            ], 404);
        }
    
        $prayer_sub_category = PrayerSubCategory::where('prayer_category_id', $prayer_category_id)->get();
    
            if(!$prayer_sub_category){
                  return response()->json([
                        'status' => 404,
                        'message' => 'No theme prayer category found',
                    ], 404);
                
            }

          return response()->json([
                'status' => 'success',
                'message' => 'Theme Prayer Sub Category Retrived successfully',
                'data' => $prayer_sub_category->map(function ($prayer_sub_category) {
                    return [
                        'id' => $prayer_sub_category->id,
                        'prayer_sub_cat_name' => $prayer_sub_category->prayer_sub_cat_name,
                    ];
                }),
            ], 200);

        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

}
