<?php

namespace App\Http\Controllers;

use App\Models\BabysitterProfile;
use App\Models\User;
use App\Models\OccupationCategory;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use App\Events\BabysitterProfileCreated;
use App\Events\BabysitterProfileUpdated;
use App\Notifications\BabysitterProfileNotification;

class BabysitterProfileController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        try {
            $query = BabysitterProfile::with([
                'user', // ✅ User relation load karein
                'occupationCategory',
                'addresses.city',
                'addresses.province',
                'addresses.country',
                'primaryAddress.city',
                'primaryAddress.province',
                'primaryAddress.country'
            ]);

            // ✅ TEMPORARY: Comment out filters for testing
            // $query->public()->verified()->active();

            Log::info('Babysitter Profile Count - Before Filters: ' . $query->count());

            // Filter by category type
            if ($request->has('category_type')) {
                $query->byCategoryType($request->get('category_type'));
                Log::info('After category_type filter: ' . $query->count());
            }

            // Filter by availability type
            if ($request->has('availability_type')) {
                $query->where('availability_type', $request->get('availability_type'));
                Log::info('After availability_type filter: ' . $query->count());
            }

            // Filter by immediate availability
            if ($request->has('immediate_availability')) {
                $query->where('immediate_availability', $request->boolean('immediate_availability'));
                Log::info('After immediate_availability filter: ' . $query->count());
            }

            // Search by user name or about me
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->whereHas('user', function ($userQuery) use ($search) {
                        $userQuery->where('first_name', 'like', "%{$search}%")
                            ->orWhere('last_name', 'like', "%{$search}%");
                    })->orWhere('about_me', 'like', "%{$search}%")
                        ->orWhere('why_babysit', 'like', "%{$search}%");
                });
                Log::info('After search filter: ' . $query->count());
            }

            // Filter by hourly rate range
            if ($request->has('min_hourly_rate')) {
                $query->where('hourly_rate', '>=', $request->get('min_hourly_rate'));
                Log::info('After min_hourly_rate filter: ' . $query->count());
            }
            if ($request->has('max_hourly_rate')) {
                $query->where('hourly_rate', '<=', $request->get('max_hourly_rate'));
                Log::info('After max_hourly_rate filter: ' . $query->count());
            }

            // Filter by experience
            if ($request->has('min_experience')) {
                $query->where('experience_years', '>=', $request->get('min_experience'));
                Log::info('After min_experience filter: ' . $query->count());
            }

            // Filter by rating
            if ($request->has('min_rating')) {
                $query->where('average_rating', '>=', $request->get('min_rating'));
                Log::info('After min_rating filter: ' . $query->count());
            }

            // Order by
            $orderBy = $request->get('order_by', 'created_at');
            $orderDirection = $request->get('order_direction', 'desc');
            $query->orderBy($orderBy, $orderDirection);

            // Get total count before pagination
            $totalCount = $query->count();
            Log::info('Total records before pagination: ' . $totalCount);

            // Pagination
            $perPage = $request->get('per_page', 10);
            $profiles = $query->paginate($perPage);

            Log::info('Final paginated records: ' . $profiles->count());

            // ✅ Full public URL provide karein for ALL users in babysitter profiles
            $profiles->getCollection()->transform(function ($profile) {
                return $this->formatBabysitterProfileResponse($profile);
            });

            return response()->json([
                'success' => true,
                'data' => $profiles->items(),
                'pagination' => [
                    'current_page' => $profiles->currentPage(),
                    'per_page' => $profiles->perPage(),
                    'total' => $profiles->total(),
                    'last_page' => $profiles->lastPage(),
                ],
                'debug' => [ // ✅ Temporary debug info
                    'total_records' => $totalCount,
                    'filters_applied' => $request->all()
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Babysitter Profile Index Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch babysitter profiles',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Display the specified resource.
     */
    public function show(Request $request, string $id): JsonResponse
    {
        try {
            $profile = BabysitterProfile::with([
                'user', // ✅ User relation load karein
                'occupationCategory',
                'skills',
                'addresses.city',
                'addresses.province',
                'addresses.country',
                'primaryAddress.city',
                'primaryAddress.province',
                'primaryAddress.country'
            ])->find($id);

            if (!$profile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile not found'
                ], 404);
            }

            // ✅ Full public URL provide karein
            $profile = $this->formatBabysitterProfileResponse($profile);

            return response()->json([
                'success' => true,
                'data' => $profile,
                'profile_visibility' => $profile->is_profile_public ? 'public' : 'private'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Format babysitter profile response with full profile picture URL
     */
    private function formatBabysitterProfileResponse($profile)
    {
        // ✅ Check if user relation exists and has profile picture
        if ($profile->user && $profile->user->profile_picture_url) {
            // ✅ Full public URL provide karein
            $profile->user->profile_picture_url = url('storage/' . $profile->user->profile_picture_url);
        }

        // ✅ Ensure other relationships are properly loaded
        if (!$profile->relationLoaded('occupationCategory')) {
            $profile->load('occupationCategory');
        }
        if (!$profile->relationLoaded('addresses')) {
            $profile->load('addresses');
        }
        if (!$profile->relationLoaded('primaryAddress')) {
            $profile->load('primaryAddress');
        }

        return $profile;
    }

    /**
     * Get current user's babysitter profile
     */
    public function showCurrentUser(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $profile = BabysitterProfile::with(['user', 'occupationCategory', 'skills'])
                ->where('user_id', $user->user_id)
                ->first();

            if (!$profile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile not found'
                ], 404);
            }

            // ✅ Full public URL provide karein
            $profile = $this->formatBabysitterProfileResponse($profile);

            return response()->json([
                'success' => true,
                'data' => $profile
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }


    // BabysitterProfileController.php - store method mein update karein

    public function store(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            // Check if user already has a babysitter profile
            $existingProfile = BabysitterProfile::where('user_id', $user->user_id)->first();
            if ($existingProfile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile already exists for this user'
                ], 422);
            }

            $validator = Validator::make($request->all(), [
                'occupation_category_id' => 'required|exists:occupation_categories,category_id',
                'hourly_rate' => 'required|numeric|min:0',
                'hourly_rates' => 'nullable|array',
                'experience_years' => 'nullable|integer|min:0',
                'availability_type' => 'required|in:full_time,part_time,occasional,flexible',
                'immediate_availability' => 'boolean',
                'willing_to_travel' => 'boolean',
                'has_vehicle' => 'boolean',
                'has_drivers_license' => 'boolean',
                'about_me' => 'nullable|string|max:2000',
                'why_babysit' => 'nullable|string|max:1000',
                'is_profile_public' => 'boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();
            $validated['user_id'] = $user->user_id;

            $profile = BabysitterProfile::create($validated);
            $profile->load(['user', 'occupationCategory']);

            // ✅ Send notification to SuperAdmin
            $this->notifySuperAdminProfileCreated($profile);

            return response()->json([
                'success' => true,
                'message' => 'Babysitter profile created successfully',
                'data' => $profile
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    // private function notifySuperAdminProfileCreated(BabysitterProfile $profile)
    // {
    //     try {
    //         // Find SuperAdmin users by role_id = 1
    //         $superAdmins = User::where('role_id', 1)->get();

    //         // Send notification to each SuperAdmin
    //         foreach ($superAdmins as $superAdmin) {
    //             $superAdmin->notify(new BabysitterProfileNotification($profile, 'created'));
    //         }

    //         // Broadcast event for real-time notifications
    //         event(new BabysitterProfileCreated($profile));

    //         Log::info('Babysitter profile creation notification sent to SuperAdmin', [
    //             'profile_id' => $profile->profile_id,
    //             'user_id' => $profile->user_id,
    //             'superadmin_count' => $superAdmins->count()
    //         ]);
    //     } catch (\Exception $e) {
    //         Log::error('Failed to send babysitter profile creation notification: ' . $e->getMessage());
    //     }
    // }

    // Temporary debug code - Notification method mein add karein
private function notifySuperAdminProfileCreated(BabysitterProfile $profile)
{
    try {
        // Find SuperAdmin users by role_id = 1
        $superAdmins = User::where('role_id', 1)->get();

        // ✅ TEMPORARY DEBUG: SuperAdmin details log karein
        Log::info('SuperAdmin Users Found:', [
            'count' => $superAdmins->count(),
            'superadmin_ids' => $superAdmins->pluck('user_id')->toArray(),
            'superadmin_emails' => $superAdmins->pluck('email')->toArray()
        ]);

        // Send notification to each SuperAdmin
        foreach ($superAdmins as $superAdmin) {
            $superAdmin->notify(new BabysitterProfileNotification($profile, 'created'));
            Log::info('Notification sent to SuperAdmin:', [
                'superadmin_id' => $superAdmin->user_id,
                'superadmin_email' => $superAdmin->email
            ]);
        }

        // ... rest of the code
    } catch (\Exception $e) {
        Log::error('Failed to send babysitter profile creation notification: ' . $e->getMessage());
    }
}

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $profile = BabysitterProfile::find($id);

            if (!$profile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile not found'
                ], 404);
            }

            // Check if user owns this profile
            $currentUser = $request->user();
            if ($currentUser->user_id != $profile->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to update this profile'
                ], 403);
            }

            $validator = Validator::make($request->all(), [
                'occupation_category_id' => 'sometimes|exists:occupation_categories,category_id',
                'hourly_rate' => 'sometimes|numeric|min:0',
                'hourly_rates' => 'nullable|array',
                'experience_years' => 'nullable|integer|min:0',
                'availability_type' => 'sometimes|in:full_time,part_time,occasional,flexible',
                'immediate_availability' => 'boolean',
                'willing_to_travel' => 'boolean',
                'has_vehicle' => 'boolean',
                'has_drivers_license' => 'boolean',
                'about_me' => 'nullable|string|max:2000',
                'why_babysit' => 'nullable|string|max:1000',
                'is_profile_public' => 'boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();

            $profile->update($validated);
            $profile->load(['user', 'occupationCategory']);

            return response()->json([
                'success' => true,
                'message' => 'Babysitter profile updated successfully',
                'data' => $profile
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to update babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request, string $id): JsonResponse
    {
        try {
            $profile = BabysitterProfile::find($id);

            if (!$profile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile not found'
                ], 404);
            }

            // Check if user owns this profile or has permission to delete
            $currentUser = $request->user();
            if ($currentUser->user_id != $profile->user_id && !$currentUser->hasPermission('users.delete')) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to delete this profile'
                ], 403);
            }

            $profile->delete();

            return response()->json([
                'success' => true,
                'message' => 'Babysitter profile deleted successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to delete babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Create or update current user's babysitter profile
     */
    public function storeCurrentUser(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            // Check if profile already exists
            $existingProfile = BabysitterProfile::where('user_id', $user->user_id)->first();
            if ($existingProfile) {
                return $this->update($request, $existingProfile->profile_id);
            }

            $validator = Validator::make($request->all(), [
                'occupation_category_id' => 'required|exists:occupation_categories,category_id',
                'hourly_rate' => 'required|numeric|min:0',
                'hourly_rates' => 'nullable|array',
                'experience_years' => 'nullable|integer|min:0',
                'availability_type' => 'required|in:full_time,part_time,occasional,flexible',
                'immediate_availability' => 'boolean',
                'willing_to_travel' => 'boolean',
                'has_vehicle' => 'boolean',
                'has_drivers_license' => 'boolean',
                'about_me' => 'nullable|string|max:2000',
                'why_babysit' => 'nullable|string|max:1000',
                'is_profile_public' => 'boolean'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Validation failed',
                    'errors' => $validator->errors()
                ], 422);
            }

            $validated = $validator->validated();
            $validated['user_id'] = $user->user_id;

            $profile = BabysitterProfile::create($validated);
            $profile->load(['user', 'occupationCategory']);

            return response()->json([
                'success' => true,
                'message' => 'Babysitter profile created successfully',
                'data' => $profile
            ], 201);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create babysitter profile',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Search babysitter profiles with filters
     */
    public function search(Request $request): JsonResponse
    {
        try {
            $query = BabysitterProfile::with([
                'user',
                'occupationCategory',
                'addresses.city',
                'addresses.province',
                'addresses.country',
                'primaryAddress.city',
                'primaryAddress.province',
                'primaryAddress.country'
            ]);

            // 1. User ID Filter - Specific user ka data get karein
            if ($request->has('user_id')) {
                $userId = (int)$request->get('user_id');
                $query->where('user_id', $userId);
            }

            // 2. Occupation Category Filter
            if ($request->has('occupation_category_id') && $request->get('occupation_category_id') != '') {
                $categoryId = (int)$request->get('occupation_category_id');
                $query->where('occupation_category_id', $categoryId);
            }

            // 3. Experience Filter - Direct match with experience_years
            if ($request->has('experience_years')) {
                $experience = (int)$request->get('experience_years');
                $query->where('experience_years', '>=', $experience);
            }

            // 4. Distance Filter (Current Location - 5km radius)
            if ($request->has(['latitude', 'longitude', 'radius_km'])) {
                $latitude = $request->get('latitude');
                $longitude = $request->get('longitude');
                $radiusKm = $request->get('radius_km', 5); // Default 5km

                $query->whereHas('primaryAddress', function ($q) use ($latitude, $longitude, $radiusKm) {
                    $q->withinRadius($latitude, $longitude, $radiusKm);
                });
            }

            // 5. Province Filter
            if ($request->has('province_id')) {
                $query->whereHas('primaryAddress', function ($q) use ($request) {
                    $q->where('province_id', $request->get('province_id'));
                });
            }

            // 6. City Filter
            if ($request->has('city_id')) {
                $query->whereHas('primaryAddress', function ($q) use ($request) {
                    $q->where('city_id', $request->get('city_id'));
                });
            }

            // 7. Hourly Rate Filter
            if ($request->has('min_hourly_rate')) {
                $query->where('hourly_rate', '>=', $request->get('min_hourly_rate'));
            }
            if ($request->has('max_hourly_rate')) {
                $query->where('hourly_rate', '<=', $request->get('max_hourly_rate'));
            }

            // 8. Rating Filter
            if ($request->has('min_rating')) {
                $query->where('average_rating', '>=', $request->get('min_rating'));
            }

            // 9. Availability Type Filter
            if ($request->has('availability_type')) {
                $query->where('availability_type', $request->get('availability_type'));
            }

            // 10. Immediate Availability Filter
            if ($request->has('immediate_availability')) {
                $query->where('immediate_availability', $request->boolean('immediate_availability'));
            }

            // 11. Search by name or description
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->whereHas('user', function ($userQuery) use ($search) {
                        $userQuery->where('first_name', 'like', "%{$search}%")
                            ->orWhere('last_name', 'like', "%{$search}%");
                    })->orWhere('about_me', 'like', "%{$search}%")
                        ->orWhere('why_babysit', 'like', "%{$search}%");
                });
            }

            // ✅ FIXED: Distance calculation aur ordering ko optimize karein
            $hasCoordinates = $request->has(['latitude', 'longitude']);
            $latitude = $hasCoordinates ? $request->get('latitude') : null;
            $longitude = $hasCoordinates ? $request->get('longitude') : null;

            if ($hasCoordinates) {
                // Pehle distance ke hisaab se filter karein, phir consistent ordering karein
                $query->whereHas('primaryAddress', function ($q) use ($latitude, $longitude) {
                    $q->whereNotNull('latitude')
                        ->whereNotNull('longitude');
                });
            }

            // // Default ordering - Pehle fixed field se order karein
            // $orderBy = $request->get('order_by', 'average_rating');
            // $orderDirection = $request->get('order_direction', 'desc');

            // // ✅ FIXED: Secondary order by bhi add karein taaki har page pe consistency rahe
            // $query->orderBy($orderBy, $orderDirection)
            //       ->orderBy('babysitter_profile_id', 'asc'); // Ya koi unique field

            // Pagination
            $perPage = $request->get('per_page', 10);
            $profiles = $query->paginate($perPage);

            // ✅ FIXED: Distance calculation ko pagination ke baad karein
            if ($hasCoordinates) {
                $profiles->getCollection()->transform(function ($profile) use ($latitude, $longitude) {
                    if ($profile->primaryAddress && $profile->primaryAddress->hasCoordinates()) {
                        $profile->distance = $profile->primaryAddress->calculateDistance($latitude, $longitude);
                    } else {
                        $profile->distance = null;
                    }
                    return $profile;
                });

                // ✅ FIXED: Ab distance ke hisaab se client side pe sort karein
                $profiles->getCollection()->sortBy('distance')->values();
            }

            // ✅ Use the same formatBabysitterProfileResponse method as index function
            $profiles->getCollection()->transform(function ($profile) {
                return $this->formatBabysitterProfileResponse($profile);
            });

            return response()->json([
                'success' => true,
                'data' => $profiles->items(),
                'pagination' => [
                    'current_page' => $profiles->currentPage(),
                    'per_page' => $profiles->perPage(),
                    'total' => $profiles->total(),
                    'last_page' => $profiles->lastPage(),
                ],
                'filters' => $request->all()
            ]);
        } catch (\Exception $e) {
            Log::error('Babysitter Search Error: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to search babysitter profiles',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * ✅ Helper method to get full image URL
     */
    private function getFullImageUrl($path)
    {
        if (!$path) {
            return null;
        }

        // Agar URL already full hai toh wahi return karein
        if (str_starts_with($path, 'http')) {
            return $path;
        }

        // Agar relative path hai toh full URL banayein
        return asset('storage/' . $path);
    }
}
