<?php

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

class PrayerRequestController extends Controller
{
    
 public function AddPrayerRequest(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',
            'date' => [
                'required',
                'date_format:d-m-Y',
            ],
        ]);

     if ($validator->fails()) {
            $errors = $validator->errors()->all(); 
        
            return response()->json([
                'status' => 422,
                'message' => $errors, 
            ], 422);
        }

        $formattedDate = Carbon::parse($request->date)->format('Y-m-d');

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

        $PrayerPoint = new PrayerPoint();
        $PrayerPoint->user_id = $user_id;
        $PrayerPoint->church_id = $church_id;
        $PrayerPoint->prayer_category_id = $prayer_category_id;
        $PrayerPoint->prayer_sub_category_id = $prayer_sub_category_id;
        $PrayerPoint->start_date = $formattedDate;
        $PrayerPoint->prayer_point = $request->prayer_point;
        $PrayerPoint->save();

        return response()->json([
            'status' => 200,
            'message' => 'PrayerRequest Created successfully',
            // 'PrayerRequest' => $PrayerPoint,
        ], 200);
    } catch (\Exception $e) {
        \Log::error('Error in AddPrayerRequest function: ' . $e->getMessage()); 

        return response()->json([
            'status' => 500,
            'message' => 'Internal Server Error',
        ], 500);
    }
}


   public function PrayerRequest()
  {
    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 Request')->pluck('id')->first();
    
            // Fetch prayer requests with user details
            $prayer_requests = PrayerPoint::where('church_id', $user->church_id)
                ->where('prayer_category_id', $prayer_category_id)
                ->where(function ($query) {
                $query->where('created_at', '>=', Carbon::now()->subDays(30))
                      ->orWhere('Start_Date', '>=', Carbon::now()->subDays(30));
                })
                ->where('Start_Date', '<=', Carbon::now())
                ->with('user') 
                ->orderBy('created_at', 'desc')
                ->get()
                ->map(function ($prayer) {
                    return [
                        'id' => $prayer->id,
                        // 'date' => $prayer->date,
                        'prayer_point' => $prayer->prayer_point,
                        'date' => $prayer->created_at->format('Y-m-d'),
                        'name' => $prayer->user ? $prayer->user->first_name . ' ' . $prayer->user->last_name : '', 
                        'role' => $prayer->user ? $prayer->user->user_role : '', 
                         'profile_photo' => $prayer->user && $prayer->user->profile_photo
                        ? asset($prayer->user->profile_photo)  
                        : asset('user_profile/profile.png'), 
                    ];
                });
    
            return response()->json([
                'status' => 200,
                'message' => 'Prayer requests retrieved successfully',
                'prayer_requests' => $prayer_requests,
            ], 200);
        } catch (\Exception $e) {
            \Log::error('Error in IPrayed function: ' . $e->getMessage());
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

    
    public function IPrayed(Request $request, $id)
    {
        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;
    
            $prayerpoint = PrayerPoint::find($id);
            if (!$prayerpoint) {
                return response()->json([
                    'status' => 404,
                    'message' => 'Church Prayer Point not found',
                ], 404);
            }
    
            $prayer_status = "Prayed";
    
            $Prayerlog = new PrayerLog();
            $Prayerlog->user_id = $user_id;
            $Prayerlog->church_id = $church_id;
            $Prayerlog->prayer_points_id = $prayerpoint->id;
            $Prayerlog->status = $prayer_status;
            $Prayerlog->save();
    
            return response()->json([
                'status' => 200,
                'message' => 'PrayerRequest Prayed successfully',
            ], 200);
        } catch (\Exception $e) {
            \Log::error('Error in IPrayed function: ' . $e->getMessage());
    
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }

}
