<?php

namespace App\Http\Controllers;

use App\Models\CareRecipient;
use App\Models\ParentProfile;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class CareRecipientController extends Controller
{
    public function index(Request $request): JsonResponse
{
    try {
        $user = $request->user();
        $query = CareRecipient::with('parentProfile.user');

        // ✅ STRICT: SIRF AUTHENTICATED PARENT KE OWN CARE RECIPIENTS
        if ($user->role_id == 2) { // Parent role
            $parentProfile = $user->parentProfile;

            // ✅ Agar parent profile nahi hai toh DEFINITELY EMPTY return
            if (!$parentProfile) {
                return response()->json([
                    'success' => true,
                    'data' => []
                ]);
            }

            // ✅ STRICT: Sirf isi specific parent ke records
            $query->where('parent_id', $parentProfile->profile_id);

            $recipients = $query->get();

            return response()->json([
                'success' => true,
                'data' => $recipients
            ]);
        }
        // ✅ Admin ke liye bhi strict filtering
        else if ($user->role_id == 1 && $request->has('parent_id')) {
            $query->where('parent_id', $request->get('parent_id'));
            $recipients = $query->get();

            return response()->json([
                'success' => true,
                'data' => $recipients
            ]);
        }
        // ✅ Koi bhi aur role ya admin without filter - EMPTY return
        else {
            return response()->json([
                'success' => true,
                'data' => []
            ]);
        }
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch care recipients',
            'error' => config('app.debug') ? $e->getMessage() : null
        ], 500);
    }
}

    /**
     * Create or update care recipient using PUT
     */
    public function createOrUpdate(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'recipient_id' => 'sometimes|exists:care_recipients,recipient_id',
                'parent_id' => 'required|exists:parent_profiles,profile_id',
                'recipient_type' => 'required|in:child,elderly,special_needs,pet',
                'name' => 'required|string|max:100',
                'age' => 'nullable|integer|min:0|max:120',
                'gender' => 'nullable|in:male,female,other,any',
                'health_mobility_details' => 'nullable|string',
                'special_instructions' => 'nullable|string',
                'allergies' => 'nullable|string',
                'medications' => 'nullable|string',
                'is_active' => 'sometimes|boolean'
            ]);

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

            $validated = $validator->validated();
            $recipientId = $request->get('recipient_id');

            if ($recipientId) {
                // Update existing record
                $recipient = CareRecipient::find($recipientId);

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

                $recipient->update($validated);
                $message = 'Care recipient updated successfully';
            } else {
                // Create new record
                $recipient = CareRecipient::create($validated);
                $message = 'Care recipient created successfully';
            }

            $recipient->load('parentProfile.user');

            return response()->json([
                'success' => true,
                'message' => $message,
                'data' => $recipient
            ], $recipientId ? 200 : 201);

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

    public function show(Request $request, string $id): JsonResponse
    {
        try {
            $recipient = CareRecipient::with('parentProfile.user')->find($id);

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

            return response()->json([
                'success' => true,
                'data' => $recipient
            ]);

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

    public function destroy(Request $request, string $id): JsonResponse
    {
        try {
            $recipient = CareRecipient::find($id);

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

            $recipient->delete();

            return response()->json([
                'success' => true,
                'message' => 'Care recipient deleted successfully'
            ]);

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