<?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 App\Models\Attendance;
use App\Models\PrayerPoint;
use App\Models\PrayerCategory;

class UserMeetingController extends Controller
{
    
   public function GetMeeting()
  {
    try {
        $user = Auth::user();

        if (!$user) {
            return response()->json([
                'status' => 404,
                'message' => 'User not found',
            ], 404);
        }
        
    
        $meetings = Meeting::where('user_id', $user->added_by) 
            ->where('church_id', $user->church_id)
            ->where('status', 'Upcoming')
            ->orderBy('created_at', 'desc')
            ->get(['id', 'meeting_title','meeting_date', 'meeting_start_time','meeting_end_time','mode_of_meeting']);

        if ($meetings->isEmpty()) {
            return response()->json([
                'status' => 404,
                'message' => 'No upcoming meetings found for this user.',
            ], 404);
        }
    
        // Return meetings
        return response()->json([
            'status' => 200,
            'message' => 'All Meetings retrieved successfully',
            'meetings' => $meetings,
        ], 200);
        
        } catch (\Exception $e) {
            return response()->json([
                'status' => 500,
                'message' => 'Internal Server Error',
            ], 500);
        }
    }   
    
    
    public function JoinMeeting($id, Request $request)
    {
        try {
            $user = auth()->user();
    
            // Find the meeting for the user
            $meeting = Meeting::where('id', $id)
                              ->where('user_id', $user->added_by)
                              ->first(['id', 'key_prayer_points', 'prayer_requests', 'church_prayer_points', 'theme_prayer_points']);
    
            if (!$meeting) {
                return response()->json([
                    'status' => 400,
                    'message' => 'The Meeting not found.',
                ], 400);
            }
    
            // Fetch and merge all prayer points
            $prayerPoints = [];
    
            // Church Prayer Points
            $churchPrayerPointIds = !empty($meeting->church_prayer_points) ? json_decode($meeting->church_prayer_points, true) : [];
            $churchPrayerPoints = PrayerPoint::whereIn('id', $churchPrayerPointIds)->get(['id', 'prayer_point'])->toArray();
            $prayerPoints = array_merge($prayerPoints, $churchPrayerPoints);
    
            // Theme Prayer Points
            $themePrayerPointIds = !empty($meeting->theme_prayer_points) ? json_decode($meeting->theme_prayer_points, true) : [];
            $themePrayerPoints = PrayerPoint::whereIn('id', $themePrayerPointIds)->get(['id', 'prayer_point'])->toArray();
            $prayerPoints = array_merge($prayerPoints, $themePrayerPoints);
    
            // Prayer Requests
            $prayerCategoryIdChurch = PrayerCategory::where('prayer_category_name', 'Pray for my Church')->pluck('id')->first();
            $prayerRequestCount = $meeting->prayer_requests;
            $prayerRequests = PrayerPoint::where('prayer_category_id', $prayerCategoryIdChurch)
                                         ->limit($prayerRequestCount)
                                         ->get(['id', 'prayer_point'])
                                         ->toArray();
            $prayerPoints = array_merge($prayerPoints, $prayerRequests);
    
            // Key Prayer Points
            $prayerCategoryIdRequest = PrayerCategory::where('prayer_category_name', 'Prayer Request')->pluck('id')->first();
            $keyPrayerCount = $meeting->key_prayer_points;
            $keyPrayerPoints = PrayerPoint::where('prayer_category_id', $prayerCategoryIdRequest)
                                          ->limit($keyPrayerCount)
                                          ->get(['id', 'prayer_point'])
                                          ->toArray();
            $prayerPoints = array_merge($prayerPoints, $keyPrayerPoints);
    
            // Handle attendance
            $attendance = Attendance::where('meeting_id', $meeting->id)
                                    ->where('meeting_started_by', $meeting->user_id)
                                    ->first();
    
            if ($attendance) {
                $userIds = json_decode($attendance->user_ids, true) ?? [];
                if (!in_array($user->id, $userIds)) {
                    $userIds[] = $user->id;
                    $attendance->user_ids = json_encode($userIds);
                    $attendance->save();
                }
            }
    
            return response()->json([
                'status' => 200,
                'message' => 'You have successfully joined the meeting.',
                'prayer_points' => $prayerPoints, // Merged prayer points
            ], 200);
        } catch (\Exception $e) {
            return response()->json([
                 'status' => 500,
                    'message' => 'Internal Server Error',
            ], 500);
        }
    }

}
    
    