<?php
// app/Http/Controllers/ParentProfileController.php
namespace App\Http\Controllers;

use App\Models\ParentProfile;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\ParentProfileResource;
use App\Models\User;
use App\Events\ParentProfileCreated;
use App\Events\ParentProfileUpdated;
use App\Notifications\ParentProfileNotification;
use Illuminate\Support\Facades\Log;

class ParentProfileController extends Controller
{

    /**
     * Get parent profiles with pagination
     */
    public function paginated(Request $request): JsonResponse
    {
        try {
            $perPage = $request->get('per_page', 10); // Default 10 per page
            $page = $request->get('page', 1); // Default page 1

            // Validate pagination parameters
            if ($perPage < 1 || $perPage > 100) {
                $perPage = 10;
            }

            if ($page < 1) {
                $page = 1;
            }

            $profiles = ParentProfile::with(['user', 'careRecipients'])
                ->orderBy('created_at', 'desc')
                ->paginate($perPage, ['*'], 'page', $page);

            // ✅ Transform data to include full URL for profile pictures
            $transformedData = $profiles->getCollection()->map(function ($profile) {
                if ($profile->user && $profile->user->profile_picture_url) {
                    $profile->user->profile_picture_url = url('storage/' . $profile->user->profile_picture_url);
                }
                return $profile;
            });

            return response()->json([
                'success' => true,
                'data' => $transformedData,
                'pagination' => [
                    'current_page' => $profiles->currentPage(),
                    'per_page' => $profiles->perPage(),
                    'total' => $profiles->total(),
                    'last_page' => $profiles->lastPage(),
                    'from' => $profiles->firstItem(),
                    'to' => $profiles->lastItem(),
                    'has_more_pages' => $profiles->hasMorePages(),
                    'next_page_url' => $profiles->nextPageUrl(),
                    'previous_page_url' => $profiles->previousPageUrl()
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch parent profiles',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }


    /**
     * Get all parent profiles (Admin only)
     */
    public function index(Request $request): JsonResponse
    {
        try {
            // Optional: Add admin check if needed
            // if (!$request->user()->is_admin) {
            //     return response()->json([
            //         'success' => false,
            //         'message' => 'Unauthorized access'
            //     ], 403);
            // }

            $profiles = ParentProfile::with(['user', 'careRecipients'])->get();

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

    /**
     * Get parent profile
     */
    public function show($id): JsonResponse
    {
        try {
            $profile = ParentProfile::with(['user', 'careRecipients'])->where('profile_id', $id)->first();

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

            // ✅ Transform profile picture URL to full path
            if ($profile->user && $profile->user->profile_picture_url) {
                $profile->user->profile_picture_url = url('storage/' . $profile->user->profile_picture_url);
            }

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

    // ... other methods remain the same (index, store, update, destroy)

    /**
     * Get current user's parent profile
     */
    public function myProfile(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $profile = ParentProfile::with(['user', 'careRecipients'])->where('user_id', $user->user_id)->first();

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

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

    /**
     * Create or update parent profile
     */
    public function store(Request $request): JsonResponse
    {
        try {
            $user = $request->user();

            $validator = Validator::make($request->all(), [
                'family_description' => 'nullable|string|max:1000',
                'household_rules' => 'nullable|string|max:1000',
                'emergency_contacts' => 'nullable|string|max:500',
                'preferred_communication' => 'nullable|in:phone,email,in_app'
            ]);

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

            $validated = $validator->validated();

            // Check if profile already exists
            $existingProfile = ParentProfile::where('user_id', $user->user_id)->first();
            $isUpdate = $existingProfile !== null;

            // Create or update profile
            $profile = ParentProfile::updateOrCreate(
                ['user_id' => $user->user_id],
                $validated
            );

            $profile->load('user');

            // ✅ Send notification to SuperAdmin
            if ($isUpdate) {
                $this->notifySuperAdminProfileUpdated($profile);
            } else {
                $this->notifySuperAdminProfileCreated($profile);
            }

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

    // ParentProfileController.php mein yeh methods add karein

/**
 * Notify SuperAdmin when parent profile is created
 */
private function notifySuperAdminProfileCreated(ParentProfile $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 ParentProfileNotification($profile, 'created'));
        }

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

        Log::info('Parent 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 parent profile creation notification: ' . $e->getMessage());
    }
}

/**
 * Notify SuperAdmin when parent profile is updated
 */
private function notifySuperAdminProfileUpdated(ParentProfile $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 ParentProfileNotification($profile, 'updated'));
        }

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

        Log::info('Parent profile update 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 parent profile update notification: ' . $e->getMessage());
    }
}

    /**
     * Update parent profile
     */
    public function update(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $profile = ParentProfile::where('user_id', $user->user_id)->first();

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

            $validator = Validator::make($request->all(), [
                'family_description' => 'sometimes|string|max:1000',
                'household_rules' => 'sometimes|string|max:1000',
                'emergency_contacts' => 'sometimes|string|max:500',
                'preferred_communication' => 'sometimes|in:phone,email,in_app'
            ]);

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

            $validated = $validator->validated();
            $profile->update($validated);

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

    /**
     * Delete parent profile
     */
    public function destroy(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $profile = ParentProfile::where('user_id', $user->user_id)->first();

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

            // Optional: Check if there are care recipients before deleting
            if ($profile->careRecipients()->count() > 0) {
                return response()->json([
                    'success' => false,
                    'message' => 'Cannot delete profile with existing care recipients. Please delete care recipients first.'
                ], 422);
            }

            $profile->delete();

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