<?php

namespace App\Http\Controllers;

use App\Models\DirectBookingRequest;
use App\Models\User;
use App\Models\BookingType;
use App\Models\OccupationCategory;
use App\Models\BabysitterProfile;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Carbon\Carbon;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Log;
use App\Events\NewDirectBookingRequest;
use App\Notifications\DirectBookingRequestNotification;


class DirectBookingRequestController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $query = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ]);

            // Filter by parent
            if ($request->has('parent_id')) {
                $query->byParent($request->get('parent_id'));
            }

            // Filter by babysitter
            if ($request->has('babysitter_id')) {
                $query->byBabysitter($request->get('babysitter_id'));
            }

            // Filter by status
            if ($request->has('status')) {
                $query->where('request_status', $request->get('status'));
            }

            // ✅ NEW: Filter by payment status
            if ($request->has('payment_status')) {
                $query->where('payment_status', $request->get('payment_status'));
            }

            // Filter by care type
            if ($request->has('care_type')) {
                $query->where('care_type', $request->get('care_type'));
            }

            // Show only active/pending requests
            if ($request->boolean('active_only', false)) {
                $query->active();
            }

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

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

            // ✅ Full public URL provide karein for ALL booking requests
            $requests->getCollection()->transform(function ($request) {
                return $this->formatBookingRequestResponse($request);
            });

            return response()->json([
                'success' => true,
                'data' => $requests->items(),
                'pagination' => [
                    'current_page' => $requests->currentPage(),
                    'per_page' => $requests->perPage(),
                    'total' => $requests->total(),
                    'last_page' => $requests->lastPage(),
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch booking requests',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    public function show(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ])->find($id);

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

            // Auto-expire if needed before returning data
            if ($bookingRequest->shouldAutoExpire()) {
                $bookingRequest->expire();
                $bookingRequest->refresh();
            }

            // Mark as viewed if babysitter is viewing
            $currentUser = $request->user();
            if ($currentUser->user_id === $bookingRequest->babysitter_id && !$bookingRequest->babysitter_viewed_at) {
                $bookingRequest->markAsViewed();
            }

            // ✅ Format the response with full URLs
            $formattedRequest = $this->formatBookingRequestResponse($bookingRequest);

            return response()->json([
                'success' => true,
                'data' => $formattedRequest,
                'meta' => [
                    'is_expired' => $bookingRequest->isExpired(),
                    'is_about_to_expire' => $bookingRequest->isAboutToExpire(),
                    'remaining_hours' => $bookingRequest->getRemainingHours(),
                    'has_start_date_passed' => $bookingRequest->hasStartDatePassed(),
                    // ✅ NEW: Payment status info
                    'payment_status' => $bookingRequest->payment_status,
                    'is_payment_successful' => $bookingRequest->isPaymentSuccessful(),
                    'is_payment_pending' => $bookingRequest->isPaymentPending(),
                    'is_payment_failed' => $bookingRequest->isPaymentFailed()
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    // DirectBookingRequestController.php

    public function store(Request $request): JsonResponse
    {
        try {
            $validator = Validator::make($request->all(), [
                'babysitter_id' => 'required|exists:babysitter_profiles,profile_id',
                'occupation_category_id' => 'required|exists:occupation_categories,category_id',
                'start_date' => 'required|date|after_or_equal:today',
                'end_date' => 'nullable|date|after_or_equal:start_date',
                'expected_hours_per_week' => 'required|integer|min:1|max:168',
                'hourly_rate' => 'required|numeric|min:1',
                'care_type' => 'required|in:child_care,elderly_care,special_needs_care,pet_care',
                'number_of_recipients' => 'required|integer|min:1',
                'recipient_names' => 'nullable|string',
                'recipient_ages' => 'nullable|string',
                'gender_preference' => 'nullable|in:male,female,any',
                'health_mobility_details' => 'nullable|string',
                'special_instructions_allergies' => 'nullable|string',
                'payment_status' => 'sometimes|in:pending,success,failed'
            ]);

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

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

            // Convert profile_id to user_id
            $babysitterProfile = BabysitterProfile::find($validated['babysitter_id']);
            if (!$babysitterProfile) {
                return response()->json([
                    'success' => false,
                    'message' => 'Babysitter profile not found'
                ], 404);
            }

            $validated['babysitter_id'] = $babysitterProfile->user_id;

            // Set expiry (72 hours from now)
            $validated['expires_at'] = Carbon::now()->addHours(72);

            // Set default payment status if not provided
            if (!isset($validated['payment_status'])) {
                $validated['payment_status'] = 'pending';
            }

            // Create the booking request first
            $bookingRequest = DirectBookingRequest::create($validated);

            // Now calculate total amount with actual model instance
            $bookingRequest->total_expected_amount = $bookingRequest->calculateTotalAmount();
            $bookingRequest->save();

            $bookingRequest->load(['parent', 'babysitter', 'babysitter.babysitterProfile', 'bookingType', 'occupationCategory']);

            // ✅ NEW: Send notification to babysitter
            $this->sendBookingRequestNotification($bookingRequest);

            return response()->json([
                'success' => true,
                'message' => 'Booking request created successfully',
                'data' => [
                    'booking_request_id' => $bookingRequest->booking_request_id,
                    'parent_id' => $bookingRequest->parent_id,
                    'babysitter_id' => $bookingRequest->babysitter_id,
                    'babysitter_profile_id' => $babysitterProfile->profile_id,
                    'occupation_category_id' => $bookingRequest->occupation_category_id,
                    'start_date' => $bookingRequest->start_date,
                    'end_date' => $bookingRequest->end_date,
                    'expected_hours_per_week' => $bookingRequest->expected_hours_per_week,
                    'hourly_rate' => $bookingRequest->hourly_rate,
                    'care_type' => $bookingRequest->care_type,
                    'number_of_recipients' => $bookingRequest->number_of_recipients,
                    'recipient_names' => $bookingRequest->recipient_names,
                    'recipient_ages' => $bookingRequest->recipient_ages,
                    'gender_preference' => $bookingRequest->gender_preference,
                    'health_mobility_details' => $bookingRequest->health_mobility_details,
                    'special_instructions_allergies' => $bookingRequest->special_instructions_allergies,
                    'request_status' => $bookingRequest->request_status,
                    'payment_status' => $bookingRequest->payment_status,
                    'total_expected_amount' => $bookingRequest->total_expected_amount,
                    'expires_at' => $bookingRequest->expires_at,
                    'created_at' => $bookingRequest->created_at,
                    'updated_at' => $bookingRequest->updated_at,
                    'parent' => $bookingRequest->formatted_parent,
                    'babysitter' => $bookingRequest->formatted_babysitter,
                    'booking_type' => $bookingRequest->bookingType,
                    'occupation_category' => $bookingRequest->occupation_category
                ]
            ], 201);
        } catch (\Exception $e) {
            Log::error('Failed to create booking request: ' . $e->getMessage(), [
                'parent_id' => $request->user()->user_id,
                'babysitter_profile_id' => $request->babysitter_id ?? 'unknown'
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to create booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Send notification to babysitter when new booking request is created
     */
    private function sendBookingRequestNotification(DirectBookingRequest $bookingRequest)
    {
        try {
            // Get babysitter user
            $babysitter = User::find($bookingRequest->babysitter_id);

            if (!$babysitter) {
                Log::error('Babysitter not found for booking request notification', [
                    'booking_request_id' => $bookingRequest->booking_request_id,
                    'babysitter_id' => $bookingRequest->babysitter_id
                ]);
                return;
            }

            // Send notification to babysitter
            $babysitter->notify(new DirectBookingRequestNotification($bookingRequest));

            // Broadcast event for real-time notification
            event(new NewDirectBookingRequest($bookingRequest));

            Log::info('Direct booking request notification sent to babysitter', [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id,
                'babysitter_id' => $bookingRequest->babysitter_id,
                'babysitter_name' => $babysitter->first_name . ' ' . $babysitter->last_name
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send booking request notification: ' . $e->getMessage(), [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'babysitter_id' => $bookingRequest->babysitter_id
            ]);
        }
    }
    public function update(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::find($id);

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

            $validator = Validator::make($request->all(), [
                'start_date' => 'sometimes|date|after:today',
                'end_date' => 'nullable|date|after:start_date',
                'expected_hours_per_week' => 'sometimes|integer|min:1|max:168',
                'hourly_rate' => 'sometimes|numeric|min:1',
                'number_of_recipients' => 'sometimes|integer|min:1',
                'recipient_names' => 'nullable|string',
                'recipient_ages' => 'nullable|string',
                'gender_preference' => 'nullable|in:male,female,any',
                'health_mobility_details' => 'nullable|string',
                'special_instructions_allergies' => 'nullable|string',
                // ✅ NEW: Payment status validation for update
                'payment_status' => 'sometimes|in:pending,success,failed'
            ]);

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

            $validated = $validator->validated();

            // Recalculate total amount if relevant fields changed
            if (
                isset($validated['start_date']) || isset($validated['end_date']) ||
                isset($validated['expected_hours_per_week']) || isset($validated['hourly_rate'])
            ) {
                $tempRequest = new DirectBookingRequest(array_merge($bookingRequest->toArray(), $validated));
                $validated['total_expected_amount'] = $tempRequest->calculateTotalAmount();
            }

            $bookingRequest->update($validated);
            $bookingRequest->load(['parent', 'babysitter', 'bookingType', 'occupationCategory']);

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

    // ✅ NEW: Update Payment Status Method
    public function updatePaymentStatus(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::find($id);

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

            $validator = Validator::make($request->all(), [
                'payment_status' => 'required|in:pending,success,failed'
            ]);

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

            $bookingRequest->update([
                'payment_status' => $request->payment_status
            ]);

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

    // ✅ NEW: Get Booking Requests by Payment Status
    public function getByPaymentStatus(Request $request, string $status): JsonResponse
    {
        try {
            $validator = Validator::make(['status' => $status], [
                'status' => 'required|in:pending,success,failed'
            ]);

            if ($validator->fails()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Invalid payment status'
                ], 422);
            }

            $user = $request->user();
            $query = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ])->where('payment_status', $status);

            // Filter by user role
            if ($user->user_type === 'parent') {
                $query->where('parent_id', $user->user_id);
            } elseif ($user->user_type === 'babysitter') {
                $query->where('babysitter_id', $user->user_id);
            }

            $perPage = $request->get('per_page', 15);
            $requests = $query->orderBy('created_at', 'desc')->paginate($perPage);

            // Format responses
            $requests->getCollection()->transform(function ($request) {
                return $this->formatBookingRequestResponse($request);
            });

            return response()->json([
                'success' => true,
                'data' => $requests->items(),
                'pagination' => [
                    'current_page' => $requests->currentPage(),
                    'per_page' => $requests->perPage(),
                    'total' => $requests->total(),
                    'last_page' => $requests->lastPage(),
                ],
                'payment_status_summary' => [
                    'status' => $status,
                    'count' => $requests->total(),
                    'description' => $this->getPaymentStatusDescription($status)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch booking requests by payment status',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    // ✅ NEW: Get Payment Status Statistics
    public function getPaymentStatistics(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $query = DirectBookingRequest::query();

            // Filter by user role
            if ($user->user_type === 'parent') {
                $query->where('parent_id', $user->user_id);
            } elseif ($user->user_type === 'babysitter') {
                $query->where('babysitter_id', $user->user_id);
            }

            $totalRequests = $query->count();
            $pendingPayments = $query->clone()->where('payment_status', 'pending')->count();
            $successfulPayments = $query->clone()->where('payment_status', 'success')->count();
            $failedPayments = $query->clone()->where('payment_status', 'failed')->count();

            return response()->json([
                'success' => true,
                'data' => [
                    'total_requests' => $totalRequests,
                    'payment_statistics' => [
                        'pending' => [
                            'count' => $pendingPayments,
                            'percentage' => $totalRequests > 0 ? round(($pendingPayments / $totalRequests) * 100, 2) : 0
                        ],
                        'success' => [
                            'count' => $successfulPayments,
                            'percentage' => $totalRequests > 0 ? round(($successfulPayments / $totalRequests) * 100, 2) : 0
                        ],
                        'failed' => [
                            'count' => $failedPayments,
                            'percentage' => $totalRequests > 0 ? round(($failedPayments / $totalRequests) * 100, 2) : 0
                        ]
                    ],
                    'success_rate' => $totalRequests > 0 ? round(($successfulPayments / $totalRequests) * 100, 2) : 0
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payment statistics',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    // ✅ NEW: Helper method for payment status description
    private function getPaymentStatusDescription(string $status): string
    {
        $descriptions = [
            'pending' => 'Payment is pending or not yet processed',
            'success' => 'Payment was successfully completed',
            'failed' => 'Payment failed or was declined'
        ];

        return $descriptions[$status] ?? 'Unknown payment status';
    }

    public function getMyRequests(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $type = $request->get('type', 'all'); // 'sent' or 'received'

            $query = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ]);

            if ($type === 'sent') {
                $query->byParent($user->user_id);
            } elseif ($type === 'received') {
                $query->byBabysitter($user->user_id);
            } else {
                $query->where(function ($q) use ($user) {
                    $q->where('parent_id', $user->user_id)
                        ->orWhere('babysitter_id', $user->user_id);
                });
            }

            if ($request->has('status')) {
                $query->where('request_status', $request->get('status'));
            }

            // ✅ NEW: Filter by payment status in my requests
            if ($request->has('payment_status')) {
                $query->where('payment_status', $request->get('payment_status'));
            }

            $perPage = $request->get('per_page', 10);

            if ($perPage < 1 || $perPage > 50) {
                $perPage = 10;
            }

            $requests = $query->orderBy('created_at', 'desc')->paginate($perPage);

            // ✅ Full public URL provide karein for ALL booking requests
            $requests->getCollection()->transform(function ($request) {
                return $this->formatBookingRequestResponse($request);
            });

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

    // Existing formatBookingRequestResponse and getFullPublicUrl methods remain the same
    private function formatBookingRequestResponse($bookingRequest)
    {
        $formatted = $bookingRequest->toArray();

        // Convert parent profile picture URL to full path
        if (!empty($formatted['parent']['profile_picture_url'])) {
            $formatted['parent']['profile_picture_url'] = $this->getFullPublicUrl($formatted['parent']['profile_picture_url']);
        }

        // Convert babysitter profile picture URL to full path
        if (!empty($formatted['babysitter']['profile_picture_url'])) {
            $formatted['babysitter']['profile_picture_url'] = $this->getFullPublicUrl($formatted['babysitter']['profile_picture_url']);
        }

        return $formatted;
    }

    private function getFullPublicUrl($path)
    {
        if (empty($path)) {
            return null;
        }

        // If it's already a full URL, return as is
        if (filter_var($path, FILTER_VALIDATE_URL)) {
            return $path;
        }

        // Remove any existing storage path if present
        $path = str_replace('storage/', '', $path);

        // Return full public URL
        return url('storage/' . $path);
    }

    public function accept(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ])->find($id);

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

            $currentUser = $request->user();

            // ✅ DEBUG: Log user information for troubleshooting
            Log::info('Accept Booking Request Attempt', [
                'booking_request_id' => $id,
                'current_user_id' => $currentUser->user_id,
                'current_user_type' => $currentUser->user_type,
                'booking_babysitter_id' => $bookingRequest->babysitter_id,
                'booking_parent_id' => $bookingRequest->parent_id
            ]);

            // ✅ FIXED: Check user role through role relationship
            if (!$currentUser->role || $currentUser->role->role_name !== 'babysitter') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only babysitters can accept booking requests',
                    'debug' => [
                        'user_role' => $currentUser->role ? $currentUser->role->role_name : 'no_role',
                        'user_type' => $currentUser->user_type
                    ]
                ], 403);
            }

            // ✅ FIXED: Compare IDs properly (handle string vs integer)
            $currentUserId = (int)$currentUser->user_id;
            $bookingBabysitterId = (int)$bookingRequest->babysitter_id;

            if ($currentUserId !== $bookingBabysitterId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to accept this booking request. You are not the assigned babysitter.',
                    'debug' => [
                        'current_user_id' => $currentUserId,
                        'booking_babysitter_id' => $bookingBabysitterId
                    ]
                ], 403);
            }

            // Check if request is in pending status
            if ($bookingRequest->request_status !== 'pending') {
                $currentStatus = $bookingRequest->request_status;
                $statusMessages = [
                    'accepted' => 'Booking request has already been accepted',
                    'rejected' => 'Booking request has already been rejected',
                    'cancelled' => 'Booking request has been cancelled',
                    'expired' => 'Booking request has expired'
                ];

                return response()->json([
                    'success' => false,
                    'message' => $statusMessages[$currentStatus] ?? 'Booking request is not in pending status',
                    'current_status' => $currentStatus
                ], 422);
            }

            // Check if request has expired
            if ($bookingRequest->isExpired()) {
                if (!$bookingRequest->expired_at) {
                    $bookingRequest->expire();
                    $bookingRequest->refresh();
                }

                return response()->json([
                    'success' => false,
                    'message' => 'Booking request has expired and cannot be accepted',
                    'expired_at' => $bookingRequest->expired_at
                ], 422);
            }

            // Check if start date has passed
            if ($bookingRequest->hasStartDatePassed()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking start date has already passed'
                ], 422);
            }

            // ✅ Accept the booking request
            $bookingRequest->accept();
            $bookingRequest->refresh();

            // ✅ NEW: Send notification to parent when booking is accepted
            $this->sendBookingAcceptedNotification($bookingRequest);

            // ✅ Format response with full URLs
            $formattedRequest = $this->formatBookingRequestResponse($bookingRequest);

            return response()->json([
                'success' => true,
                'message' => 'Booking request accepted successfully',
                'data' => $formattedRequest,
                'meta' => [
                    'accepted_at' => $bookingRequest->accepted_at,
                    'request_status' => $bookingRequest->request_status,
                    'payment_status' => $bookingRequest->payment_status,
                    'is_expired' => $bookingRequest->isExpired(),
                    'has_start_date_passed' => $bookingRequest->hasStartDatePassed()
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to accept booking request: ' . $e->getMessage(), [
                'booking_request_id' => $id,
                'user_id' => $request->user()->user_id,
                'user_type' => $request->user()->user_type,
                'role' => $request->user()->role ? $request->user()->role->role_name : 'no_role'
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to accept booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Send notification to parent when booking request is accepted
     */
    private function sendBookingAcceptedNotification(DirectBookingRequest $bookingRequest)
    {
        try {
            // Get parent user
            $parent = User::find($bookingRequest->parent_id);

            if (!$parent) {
                Log::error('Parent not found for booking accepted notification', [
                    'booking_request_id' => $bookingRequest->booking_request_id,
                    'parent_id' => $bookingRequest->parent_id
                ]);
                return;
            }

            // Send notification to parent
            $parent->notify(new \App\Notifications\BookingAcceptedNotification($bookingRequest));

            Log::info('Booking accepted notification sent to parent', [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id,
                'babysitter_id' => $bookingRequest->babysitter_id,
                'parent_name' => $parent->first_name . ' ' . $parent->last_name,
                'babysitter_name' => $bookingRequest->babysitter->first_name . ' ' . $bookingRequest->babysitter->last_name
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send booking accepted notification: ' . $e->getMessage(), [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id
            ]);
        }
    }

    public function reject(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::find($id);

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

            $currentUser = $request->user();

            // ✅ DEBUG: Log user information for troubleshooting
            Log::info('Reject Booking Request Attempt', [
                'booking_request_id' => $id,
                'current_user_id' => $currentUser->user_id,
                'current_user_type' => $currentUser->user_type,
                'booking_babysitter_id' => $bookingRequest->babysitter_id,
                'booking_parent_id' => $bookingRequest->parent_id
            ]);

            // ✅ FIXED: Check user role through role relationship (same as accept method)
            if (!$currentUser->role || $currentUser->role->role_name !== 'babysitter') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only babysitters can reject booking requests',
                    'debug' => [
                        'user_role' => $currentUser->role ? $currentUser->role->role_name : 'no_role',
                        'user_type' => $currentUser->user_type
                    ]
                ], 403);
            }

            // ✅ FIXED: Compare IDs properly (same as accept method)
            $currentUserId = (int)$currentUser->user_id;
            $bookingBabysitterId = (int)$bookingRequest->babysitter_id;

            if ($currentUserId !== $bookingBabysitterId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to reject this booking request. You are not the assigned babysitter.',
                    'debug' => [
                        'current_user_id' => $currentUserId,
                        'booking_babysitter_id' => $bookingBabysitterId
                    ]
                ], 403);
            }

            if ($bookingRequest->request_status !== 'pending') {
                $currentStatus = $bookingRequest->request_status;
                $statusMessages = [
                    'accepted' => 'Booking request has already been accepted',
                    'rejected' => 'Booking request has already been rejected',
                    'cancelled' => 'Booking request has been cancelled',
                    'expired' => 'Booking request has expired'
                ];

                return response()->json([
                    'success' => false,
                    'message' => $statusMessages[$currentStatus] ?? 'Booking request is not in pending status',
                    'current_status' => $currentStatus
                ], 422);
            }

            // Check if request has expired (same as accept method)
            if ($bookingRequest->isExpired()) {
                if (!$bookingRequest->expired_at) {
                    $bookingRequest->expire();
                    $bookingRequest->refresh();
                }

                return response()->json([
                    'success' => false,
                    'message' => 'Booking request has expired and cannot be rejected',
                    'expired_at' => $bookingRequest->expired_at
                ], 422);
            }

            $bookingRequest->reject();
            $bookingRequest->refresh();

            // ✅ NEW: Send notification to parent when booking is rejected
            $this->sendBookingRejectedNotification($bookingRequest);

            // ✅ Format response with full URLs (same as accept method)
            $formattedRequest = $this->formatBookingRequestResponse($bookingRequest);

            return response()->json([
                'success' => true,
                'message' => 'Booking request rejected successfully',
                'data' => $formattedRequest,
                'meta' => [
                    'rejected_at' => $bookingRequest->rejected_at,
                    'request_status' => $bookingRequest->request_status,
                    'is_expired' => $bookingRequest->isExpired(),
                    'has_start_date_passed' => $bookingRequest->hasStartDatePassed()
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to reject booking request: ' . $e->getMessage(), [
                'booking_request_id' => $id,
                'user_id' => $request->user()->user_id,
                'user_type' => $request->user()->user_type,
                'role' => $request->user()->role ? $request->user()->role->role_name : 'no_role'
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to reject booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Send notification to parent when booking request is rejected
     */
    private function sendBookingRejectedNotification(DirectBookingRequest $bookingRequest)
    {
        try {
            // Get parent user
            $parent = User::find($bookingRequest->parent_id);

            if (!$parent) {
                Log::error('Parent not found for booking rejected notification', [
                    'booking_request_id' => $bookingRequest->booking_request_id,
                    'parent_id' => $bookingRequest->parent_id
                ]);
                return;
            }

            // Send notification to parent
            $parent->notify(new \App\Notifications\BookingRejectedNotification($bookingRequest));

            Log::info('Booking rejected notification sent to parent', [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id,
                'babysitter_id' => $bookingRequest->babysitter_id,
                'parent_name' => $parent->first_name . ' ' . $parent->last_name,
                'babysitter_name' => $bookingRequest->babysitter->first_name . ' ' . $bookingRequest->babysitter->last_name
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send booking rejected notification: ' . $e->getMessage(), [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id
            ]);
        }
    }
    public function cancel(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::find($id);

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

            $currentUser = $request->user();

            // ✅ DEBUG: Log user information for troubleshooting
            Log::info('Cancel Booking Request Attempt', [
                'booking_request_id' => $id,
                'current_user_id' => $currentUser->user_id,
                'current_user_type' => $currentUser->user_type,
                'booking_parent_id' => $bookingRequest->parent_id,
                'current_status' => $bookingRequest->request_status
            ]);

            // ✅ FIXED: Compare IDs properly with type casting
            $currentUserId = (int)$currentUser->user_id;
            $bookingParentId = (int)$bookingRequest->parent_id;

            // ✅ ONLY parent can cancel the booking request
            if ($currentUserId !== $bookingParentId) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to cancel this booking request. Only the parent can cancel.',
                    'debug' => [
                        'current_user_id' => $currentUserId,
                        'booking_parent_id' => $bookingParentId
                    ]
                ], 403);
            }

            // ✅ Check if parent can cancel (only pending status)
            if ($bookingRequest->request_status !== 'pending') {
                $statusMessages = [
                    'accepted' => 'Cannot cancel an accepted booking request. Please contact the babysitter directly.',
                    'rejected' => 'Booking request has already been rejected by the babysitter',
                    'cancelled' => 'Booking request has already been cancelled',
                    'expired' => 'Booking request has expired and cannot be cancelled'
                ];

                return response()->json([
                    'success' => false,
                    'message' => $statusMessages[$bookingRequest->request_status] ?? 'Only pending booking requests can be cancelled',
                    'current_status' => $bookingRequest->request_status
                ], 422);
            }

            // Check if request has expired
            if ($bookingRequest->isExpired()) {
                if (!$bookingRequest->expired_at) {
                    $bookingRequest->expire();
                    $bookingRequest->refresh();
                }

                return response()->json([
                    'success' => false,
                    'message' => 'Booking request has expired and cannot be cancelled',
                    'expired_at' => $bookingRequest->expired_at
                ], 422);
            }

            $bookingRequest->cancel();
            $bookingRequest->refresh();

            // ✅ NEW: Send notification to babysitter when parent cancels booking
            $this->sendBookingCancelledNotification($bookingRequest);

            // ✅ Format response with full URLs
            $formattedRequest = $this->formatBookingRequestResponse($bookingRequest);

            return response()->json([
                'success' => true,
                'message' => 'Booking request cancelled successfully',
                'data' => $formattedRequest,
                'meta' => [
                    'cancelled_by' => 'parent',
                    'cancelled_at' => $bookingRequest->cancelled_at,
                    'request_status' => $bookingRequest->request_status,
                    'is_expired' => $bookingRequest->isExpired(),
                    'has_start_date_passed' => $bookingRequest->hasStartDatePassed()
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to cancel booking request: ' . $e->getMessage(), [
                'booking_request_id' => $id,
                'user_id' => $request->user()->user_id,
                'user_type' => $request->user()->user_type
            ]);

            return response()->json([
                'success' => false,
                'message' => 'Failed to cancel booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Send notification to babysitter when parent cancels booking request
     */
    private function sendBookingCancelledNotification(DirectBookingRequest $bookingRequest)
    {
        try {
            // Get babysitter user
            $babysitter = User::find($bookingRequest->babysitter_id);

            if (!$babysitter) {
                Log::error('Babysitter not found for booking cancelled notification', [
                    'booking_request_id' => $bookingRequest->booking_request_id,
                    'babysitter_id' => $bookingRequest->babysitter_id
                ]);
                return;
            }

            // Send notification to babysitter
            $babysitter->notify(new \App\Notifications\BookingCancelledNotification($bookingRequest));

            Log::info('Booking cancelled notification sent to babysitter', [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'parent_id' => $bookingRequest->parent_id,
                'babysitter_id' => $bookingRequest->babysitter_id,
                'parent_name' => $bookingRequest->parent->first_name . ' ' . $bookingRequest->parent->last_name,
                'babysitter_name' => $babysitter->first_name . ' ' . $babysitter->last_name
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to send booking cancelled notification: ' . $e->getMessage(), [
                'booking_request_id' => $bookingRequest->booking_request_id,
                'babysitter_id' => $bookingRequest->babysitter_id
            ]);
        }
    }

    public function getExpiringRequests(Request $request): JsonResponse
    {
        try {
            $user = $request->user();
            $type = $request->get('type', 'received'); // 'sent' or 'received'

            $query = DirectBookingRequest::with([
                'parent',
                'babysitter',
                'bookingType',
                'occupationCategory'
            ])->aboutToExpire(24); // Requests expiring in next 24 hours

            if ($type === 'sent') {
                $query->byParent($user->user_id);
            } else {
                $query->byBabysitter($user->user_id);
            }

            $requests = $query->get();

            // ✅ Full public URL provide karein for ALL booking requests
            $formattedRequests = $requests->map(function ($request) {
                return $this->formatBookingRequestResponse($request);
            });

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


    public function forceExpire(Request $request, string $id): JsonResponse
    {
        try {
            $bookingRequest = DirectBookingRequest::find($id);

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

            if ($bookingRequest->request_status !== 'pending') {
                return response()->json([
                    'success' => false,
                    'message' => 'Only pending requests can be expired'
                ], 422);
            }

            $bookingRequest->expire();

            return response()->json([
                'success' => true,
                'message' => 'Booking request expired successfully',
                'data' => $bookingRequest->load(['parent', 'babysitter', 'bookingType', 'occupationCategory'])
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to expire booking request',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
