<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Models\DirectBookingRequest;
use App\Models\OccupationCategory;
use App\Models\CommissionRate;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

use App\Notifications\BookingStartedNotification;
use App\Notifications\BookingCompletedNotification;
use App\Notifications\SuperAdminBookingNotification;
use App\Models\User;

class BookingController extends Controller
{
    public function index(Request $request): JsonResponse
{
    try {
        $user = $request->user();
        $query = Booking::with([
            'bookingRequest',
            'parent',
            'babysitter',
            'occupationCategory'
        ]);

        // тЬЕ AUTOMATIC FILTERING BY CURRENT USER ROLE
        if ($user->user_type === 'parent') {
            // Parent ko sirf apni hi bookings dikhein
            $query->where('parent_id', $user->user_id);
        } elseif ($user->user_type === 'babysitter') {
            // Babysitter ko sirf apni hi bookings dikhein
            $query->where('babysitter_id', $user->user_id);
        }
        // Admin ko sab bookings dikh sakti hain (no filter)

        // Filter by parent (admin ke liye optional)
        if ($request->has('parent_id') && $user->user_type === 'admin') {
            $query->byParent($request->get('parent_id'));
        }

        // Filter by babysitter (admin ke liye optional)
        if ($request->has('babysitter_id') && $user->user_type === 'admin') {
            $query->byBabysitter($request->get('babysitter_id'));
        }

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

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

        // Filter by date range
        if ($request->has('start_date')) {
            $query->where('start_date', '>=', $request->get('start_date'));
        }

        if ($request->has('end_date')) {
            $query->where('start_date', '<=', $request->get('end_date'));
        }

        // 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', 10);
        $bookings = $query->paginate($perPage);

        return response()->json([
            'success' => true,
            'data' => $bookings->items(),
            'pagination' => [
                'current_page' => $bookings->currentPage(),
                'per_page' => $bookings->perPage(),
                'total' => $bookings->total(),
                'last_page' => $bookings->lastPage(),
            ],
            'meta' => [
                'user_type' => $user->user_type,
                'user_id' => $user->user_id,
                'filtered_by' => $user->user_type // yeh batayega kis basis pe filter hua
            ]
        ]);
    } catch (\Exception $e) {
        Log::error('Failed to fetch bookings: ' . $e->getMessage(), [
            'user_id' => $request->user()->user_id,
            'user_type' => $request->user()->user_type
        ]);

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

    /**
     * Get all bookings for superadmin with comprehensive data
     */
    public function getAllBookingsForSuperAdmin(Request $request): JsonResponse
    {
        try {
            // Check if user is superadmin
            $user = $request->user();
            if (!$user || !$user->isSuperAdmin()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized. Only superadmin can access all bookings.'
                ], 403);
            }

            $query = Booking::with([
                'bookingRequest',
                'parent',
                'babysitter',
                'occupationCategory',
                'payments'
            ]);

            // 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 booking status
            if ($request->has('booking_status')) {
                $query->where('booking_status', $request->get('booking_status'));
            }

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

            // Filter by date range
            if ($request->has('start_date')) {
                $query->where('start_date', '>=', $request->get('start_date'));
            }

            if ($request->has('end_date')) {
                $query->where('start_date', '<=', $request->get('end_date'));
            }

            // Filter by creation date range
            if ($request->has('created_from')) {
                $query->where('created_at', '>=', $request->get('created_from'));
            }

            if ($request->has('created_to')) {
                $query->where('created_at', '<=', $request->get('created_to'));
            }

            // Search by booking ID or related names
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->where('booking_id', 'LIKE', "%{$search}%")
                        ->orWhereHas('parent', function ($q2) use ($search) {
                            $q2->where('first_name', 'LIKE', "%{$search}%")
                                ->orWhere('last_name', 'LIKE', "%{$search}%");
                        })
                        ->orWhereHas('babysitter', function ($q2) use ($search) {
                            $q2->where('first_name', 'LIKE', "%{$search}%")
                                ->orWhere('last_name', 'LIKE', "%{$search}%");
                        });
                });
            }

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

            // Get total counts for statistics
            $totalBookings = (clone $query)->count();
            $totalAmount = (clone $query)->sum('total_amount');
            $totalCommission = (clone $query)->sum('commission_amount');

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

            // Format response with additional statistics
            $response = [
                'success' => true,
                'data' => $bookings->items(),
                'statistics' => [
                    'total_bookings' => $totalBookings,
                    'total_amount' => round($totalAmount, 2),
                    'total_commission' => round($totalCommission, 2),
                    'average_booking_value' => $totalBookings > 0 ? round($totalAmount / $totalBookings, 2) : 0,
                ],
                'pagination' => [
                    'current_page' => $bookings->currentPage(),
                    'per_page' => $bookings->perPage(),
                    'total' => $bookings->total(),
                    'last_page' => $bookings->lastPage(),
                ]
            ];

            Log::info('ЁЯУК SUPERADMIN BOOKINGS - Fetched all bookings:', [
                'total_bookings' => $totalBookings,
                'total_amount' => $totalAmount,
                'requested_by' => $user->user_id
            ]);

            return response()->json($response);
        } catch (\Exception $e) {
            Log::error('тЭМ SUPERADMIN BOOKINGS - Failed to fetch all bookings:', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

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

    /**
     * Get detailed booking view for superadmin
     */
    public function getBookingViewForSuperAdmin(Request $request, string $id): JsonResponse
    {
        try {
            // Check if user is superadmin
            $user = $request->user();
            if (!$user || !$user->isSuperAdmin()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized. Only superadmin can access booking details.'
                ], 403);
            }

            $booking = Booking::with([
                'bookingRequest',
                'parent' => function ($query) {
                    $query->with(['addresses', 'userLanguages.language']);
                },
                'babysitter' => function ($query) {
                    $query->with(['babysitterProfile', 'addresses', 'userLanguages.language']);
                },
                'occupationCategory',
                'payments' => function ($query) {
                    $query->orderBy('created_at', 'desc');
                }
            ])->find($id);

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

            // Format the response with comprehensive data
            $formattedBooking = $this->formatBookingViewData($booking);

            Log::info('ЁЯУК SUPERADMIN BOOKING VIEW - Fetched booking details:', [
                'booking_id' => $booking->booking_id,
                'requested_by' => $user->user_id
            ]);

            return response()->json([
                'success' => true,
                'data' => $formattedBooking
            ]);
        } catch (\Exception $e) {
            Log::error('тЭМ SUPERADMIN BOOKING VIEW - Failed to fetch booking details:', [
                'booking_id' => $id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

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

    /**
     * Format booking data for superadmin view
     */
    private function formatBookingViewData($booking)
    {
        // Basic booking info
        $formatted = [
            'booking_info' => [
                'booking_id' => $booking->booking_id,
                'booking_status' => $booking->booking_status,
                'payment_status' => $booking->payment_status,
                'start_date' => $booking->start_date,
                'end_date' => $booking->end_date,
                'total_weeks' => $booking->total_weeks,
                'expected_hours_per_week' => $booking->expected_hours_per_week,
                'total_hours' => $booking->total_hours,
                'agreed_hourly_rate' => $booking->agreed_hourly_rate,
                'subtotal_amount' => $booking->subtotal_amount,
                'commission_rate' => $booking->commission_rate,
                'commission_amount' => $booking->commission_amount,
                'total_amount' => $booking->total_amount,
                'babysitter_earnings' => $booking->babysitter_earnings,
                'created_at' => $booking->created_at,
                'confirmed_at' => $booking->confirmed_at,
                'started_at' => $booking->started_at,
                'completed_at' => $booking->completed_at,
                'cancelled_at' => $booking->cancelled_at,
                'scheduled_completion_at' => $booking->scheduled_completion_at,
            ],
            'parent_info' => $this->formatUserInfo($booking->parent),
            'babysitter_info' => $this->formatBabysitterInfo($booking->babysitter),
            'occupation_info' => $booking->occupationCategory ? [
                'category_id' => $booking->occupationCategory->occupation_category_id,
                'category_name' => $booking->occupationCategory->category_name,
                'description' => $booking->occupationCategory->description,
                'base_hourly_rate' => $booking->occupationCategory->base_hourly_rate,
            ] : null,
            'booking_request_info' => $booking->bookingRequest ? [
                'booking_request_id' => $booking->bookingRequest->booking_request_id,
                'request_status' => $booking->bookingRequest->request_status,
                'hourly_rate' => $booking->bookingRequest->hourly_rate,
                'expected_hours_per_week' => $booking->bookingRequest->expected_hours_per_week,
                'message_to_babysitter' => $booking->bookingRequest->message_to_babysitter,
                'special_requirements' => $booking->bookingRequest->special_requirements,
                'created_at' => $booking->bookingRequest->created_at,
            ] : null,
            'payment_history' => $booking->payments->map(function ($payment) {
                return [
                    'payment_id' => $payment->payment_id,
                    'razorpay_order_id' => $payment->razorpay_order_id,
                    'razorpay_payment_id' => $payment->razorpay_payment_id,
                    'amount' => $payment->amount,
                    'currency' => $payment->currency,
                    'payment_status' => $payment->payment_status,
                    'payment_method' => $payment->payment_method,
                    'paid_at' => $payment->paid_at,
                    'created_at' => $payment->created_at,
                ];
            }),
            'timeline_events' => $this->getBookingTimeline($booking),
        ];

        return $formatted;
    }

    /**
     * Format user information for parent
     */
    private function formatUserInfo($user)
    {
        if (!$user) return null;

        return [
            'user_id' => $user->user_id,
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'email' => $user->email,
            'phone' => $user->phone,
            'profile_picture' => $user->profile_picture,
            'date_of_birth' => $user->date_of_birth,
            'gender' => $user->gender,
            'is_verified' => $user->is_verified,
            'account_status' => $user->account_status,
            'registration_date' => $user->created_at,
            'addresses' => $user->addresses->map(function ($address) {
                return [
                    'address_line1' => $address->address_line1,
                    'address_line2' => $address->address_line2,
                    'city' => $address->city ? $address->city->city_name : null,
                    'province' => $address->province ? $address->province->province_name : null,
                    'country' => $address->country ? $address->country->country_name : null,
                    'postal_code' => $address->postal_code,
                    'is_primary' => $address->is_primary,
                ];
            }),
            'languages' => $user->userLanguages->map(function ($userLanguage) {
                return [
                    'language' => $userLanguage->language ? $userLanguage->language->language_name : null,
                    'proficiency' => $userLanguage->proficiency_level,
                    'is_primary' => $userLanguage->is_primary,
                ];
            }),
        ];
    }

    /**
     * Format babysitter information with profile details
     */
    private function formatBabysitterInfo($babysitter)
    {
        if (!$babysitter) return null;

        $babysitterProfile = $babysitter->babysitterProfile;

        return [
            'user_id' => $babysitter->user_id,
            'first_name' => $babysitter->first_name,
            'last_name' => $babysitter->last_name,
            'email' => $babysitter->email,
            'phone' => $babysitter->phone,
            'profile_picture' => $babysitter->profile_picture,
            'date_of_birth' => $babysitter->date_of_birth,
            'gender' => $babysitter->gender,
            'is_verified' => $babysitter->is_verified,
            'account_status' => $babysitter->account_status,
            'registration_date' => $babysitter->created_at,
            'profile' => $babysitterProfile ? [
                'years_of_experience' => $babysitterProfile->years_of_experience,
                'bio' => $babysitterProfile->bio,
                'hourly_rate' => $babysitterProfile->hourly_rate,
                'is_available' => $babysitterProfile->is_available,
                'verification_status' => $babysitterProfile->verification_status,
                'rating' => $babysitterProfile->rating,
                'total_reviews' => $babysitterProfile->total_reviews,
            ] : null,
            'addresses' => $babysitter->addresses->map(function ($address) {
                return [
                    'address_line1' => $address->address_line1,
                    'address_line2' => $address->address_line2,
                    'city' => $address->city ? $address->city->city_name : null,
                    'province' => $address->province ? $address->province->province_name : null,
                    'country' => $address->country ? $address->country->country_name : null,
                    'postal_code' => $address->postal_code,
                    'is_primary' => $address->is_primary,
                ];
            }),
            'languages' => $babysitter->userLanguages->map(function ($userLanguage) {
                return [
                    'language' => $userLanguage->language ? $userLanguage->language->language_name : null,
                    'proficiency' => $userLanguage->proficiency_level,
                    'is_primary' => $userLanguage->is_primary,
                ];
            }),
        ];
    }

    /**
     * Get booking timeline events
     */
    private function getBookingTimeline($booking)
    {
        $timeline = [];

        // Booking created
        $timeline[] = [
            'event' => 'booking_created',
            'description' => 'Booking was created',
            'timestamp' => $booking->created_at,
            'status' => 'created',
        ];

        // Booking request accepted (if applicable)
        if ($booking->bookingRequest && $booking->bookingRequest->accepted_at) {
            $timeline[] = [
                'event' => 'request_accepted',
                'description' => 'Booking request was accepted by babysitter',
                'timestamp' => $booking->bookingRequest->accepted_at,
                'status' => 'accepted',
            ];
        }

        // Booking confirmed
        if ($booking->confirmed_at) {
            $timeline[] = [
                'event' => 'booking_confirmed',
                'description' => 'Booking was confirmed',
                'timestamp' => $booking->confirmed_at,
                'status' => 'confirmed',
            ];
        }

        // Payment made
        if ($booking->payment_made_at) {
            $timeline[] = [
                'event' => 'payment_made',
                'description' => 'Payment was completed',
                'timestamp' => $booking->payment_made_at,
                'status' => 'paid',
            ];
        }

        // Booking started
        if ($booking->started_at) {
            $timeline[] = [
                'event' => 'booking_started',
                'description' => 'Booking service started',
                'timestamp' => $booking->started_at,
                'status' => 'active',
            ];
        }

        // Booking completed
        if ($booking->completed_at) {
            $timeline[] = [
                'event' => 'booking_completed',
                'description' => 'Booking service completed',
                'timestamp' => $booking->completed_at,
                'status' => 'completed',
            ];
        }

        // Booking cancelled
        if ($booking->cancelled_at) {
            $timeline[] = [
                'event' => 'booking_cancelled',
                'description' => 'Booking was cancelled',
                'timestamp' => $booking->cancelled_at,
                'status' => 'cancelled',
            ];
        }

        // Sort timeline by timestamp
        usort($timeline, function ($a, $b) {
            return strtotime($a['timestamp']) - strtotime($b['timestamp']);
        });

        return $timeline;
    }

   public function store(Request $request): JsonResponse
{
    try {
        DB::beginTransaction();

        $validator = Validator::make($request->all(), [
            'booking_request_id' => 'required|exists:direct_booking_requests,booking_request_id',
        ]);

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

        $bookingRequest = DirectBookingRequest::with([
            'parent',
            'babysitter',
            'occupationCategory'
        ])->find($request->booking_request_id);

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

        // Check if booking request is accepted
        if ($bookingRequest->request_status !== 'accepted') {
            return response()->json([
                'success' => false,
                'message' => 'Booking request must be accepted first. Current status: ' . $bookingRequest->request_status
            ], 422);
        }

        // ✅ UPDATED: Check if booking already exists for this request - ALLOW RE-BOOKING
        $existingBooking = Booking::where('booking_request_id', $bookingRequest->booking_request_id)->first();
        if ($existingBooking) {
            // ✅ ALLOW RE-BOOKING FOR CANCELLED/FAILED PAYMENTS
            $allowReBookingStatuses = ['cancelled', 'pending_payment'];
            $allowReBookingPaymentStatuses = ['failed', 'pending', 'expired'];

            if (in_array($existingBooking->booking_status, $allowReBookingStatuses) &&
                in_array($existingBooking->payment_status, $allowReBookingPaymentStatuses)) {

                Log::info('🔄 ALLOWING RE-BOOKING - Previous booking was cancelled/failed:', [
                    'previous_booking_id' => $existingBooking->booking_id,
                    'booking_status' => $existingBooking->booking_status,
                    'payment_status' => $existingBooking->payment_status,
                    'new_booking_request_id' => $bookingRequest->booking_request_id
                ]);

                // ✅ RETURN EXISTING BOOKING INSTEAD OF CREATING NEW ONE
                $existingBooking->update([
                    'booking_status' => 'pending_payment',
                    'payment_status' => 'pending',
                    'cancelled_at' => null,
                    'cancellation_reason' => null,
                    'updated_at' => now()
                ]);

                DB::commit();

                Log::info('✅ EXISTING BOOKING REACTIVATED - For re-payment:', [
                    'booking_id' => $existingBooking->booking_id,
                    'booking_request_id' => $bookingRequest->booking_request_id
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Booking reactivated for payment successfully',
                    'data' => $existingBooking,
                    'is_reactivated' => true
                ], 200);
            } else {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking already exists for this request'
                ], 422);
            }
        }

        // Validate occupation category
        if (!$bookingRequest->occupationCategory) {
            return response()->json([
                'success' => false,
                'message' => 'Occupation category not found for this request'
            ], 422);
        }

        // ✅ FIXED: Correct Commission Calculation
        $amounts = $this->calculateBookingAmounts($bookingRequest);

        // Create booking
        $booking = Booking::create([
            'booking_request_id' => $bookingRequest->booking_request_id,
            'parent_id' => $bookingRequest->parent_id,
            'babysitter_id' => $bookingRequest->babysitter_id,
            'occupation_category_id' => $bookingRequest->occupation_category_id,
            'start_date' => $bookingRequest->start_date,
            'end_date' => $bookingRequest->end_date,
            'total_weeks' => $amounts['total_weeks'],
            'expected_hours_per_week' => $bookingRequest->expected_hours_per_week,
            'agreed_hourly_rate' => $amounts['hourly_rate'],
            'total_hours' => $amounts['total_hours'],
            'subtotal_amount' => $amounts['subtotal_amount'],
            'commission_rate' => $amounts['commission_rate'],
            'commission_amount' => $amounts['commission_amount'],
            'total_amount' => $amounts['total_amount'],
            'babysitter_earnings' => $amounts['babysitter_earnings'],
            'booking_status' => 'pending_payment',
            'payment_status' => 'pending',
            'scheduled_completion_at' => $bookingRequest->end_date
                ? Carbon::parse($bookingRequest->end_date)->addDay()
                : null,
        ]);

        DB::commit();

        $booking->load(['bookingRequest', 'parent', 'babysitter', 'occupationCategory']);

        Log::info('✅ BOOKING CREATED - Successfully:', [
            'booking_id' => $booking->booking_id,
            'booking_request_id' => $bookingRequest->booking_request_id,
            'total_amount' => $amounts['total_amount'],
            'commission_amount' => $amounts['commission_amount'],
            'babysitter_earnings' => $amounts['babysitter_earnings']
        ]);

        return response()->json([
            'success' => true,
            'message' => 'Booking created successfully',
            'data' => $booking,
            'is_reactivated' => false
        ], 201);
    } catch (\Exception $e) {
        DB::rollBack();
        Log::error('❌ BOOKING CREATION - Failed:', [
            'booking_request_id' => $request->booking_request_id,
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

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

    /**
     * тЬЕ FIXED: Correct Commission Calculation Logic
     */
    /**
 * ✅ FIXED: Correct Commission Calculation Logic WITH DEBUG
 */
private function calculateBookingAmounts($bookingRequest)
{
    try {
        Log::info('💰 CALCULATION DEBUG - START:', [
            'booking_request_id' => $bookingRequest->booking_request_id,
            'hourly_rate_raw' => $bookingRequest->hourly_rate,
            'hours_per_week_raw' => $bookingRequest->expected_hours_per_week,
            'start_date' => $bookingRequest->start_date,
            'end_date' => $bookingRequest->end_date,
            'start_date_type' => gettype($bookingRequest->start_date),
            'end_date_type' => gettype($bookingRequest->end_date)
        ]);

        // ✅ DEBUG: Check if dates are Carbon instances or strings
        if (!($bookingRequest->start_date instanceof \Carbon\Carbon)) {
            Log::warning('⚠️ start_date is not Carbon instance:', [
                'type' => gettype($bookingRequest->start_date),
                'value' => $bookingRequest->start_date
            ]);
            
            try {
                $startDate = Carbon::parse($bookingRequest->start_date);
            } catch (\Exception $e) {
                Log::error('❌ Failed to parse start_date:', ['error' => $e->getMessage()]);
                $startDate = Carbon::now();
            }
        } else {
            $startDate = $bookingRequest->start_date;
        }

        if (!($bookingRequest->end_date instanceof \Carbon\Carbon)) {
            Log::warning('⚠️ end_date is not Carbon instance:', [
                'type' => gettype($bookingRequest->end_date),
                'value' => $bookingRequest->end_date
            ]);
            
            try {
                $endDate = Carbon::parse($bookingRequest->end_date);
            } catch (\Exception $e) {
                Log::error('❌ Failed to parse end_date:', ['error' => $e->getMessage()]);
                $endDate = Carbon::now()->addWeeks(4);
            }
        } else {
            $endDate = $bookingRequest->end_date;
        }

        // ✅ Calculate total weeks
        $totalWeeks = 1; // Default
        if ($endDate && $startDate) {
            $diffInDays = $startDate->diffInDays($endDate);
            $totalWeeks = ceil($diffInDays / 7);
            Log::info('📅 DATE CALCULATION:', [
                'start_date' => $startDate->toDateString(),
                'end_date' => $endDate->toDateString(),
                'diff_days' => $diffInDays,
                'total_weeks' => $totalWeeks
            ]);
        }

        // ✅ Ensure at least 1 week
        $totalWeeks = max(1, $totalWeeks);

        $totalHours = $bookingRequest->expected_hours_per_week * $totalWeeks;

        // ✅ FIX: Ensure hourly rate is reasonable but not zero
        $hourlyRate = max(1, $bookingRequest->hourly_rate);
        
        // ✅ FIX: Check if values are valid
        if ($bookingRequest->expected_hours_per_week <= 0) {
            throw new \Exception('Hours per week must be greater than 0. Current value: ' . $bookingRequest->expected_hours_per_week);
        }
        
        $subtotalAmount = $hourlyRate * $totalHours;

        Log::info('💰 CALCULATION DEBUG - INTERMEDIATE:', [
            'hourly_rate_used' => $hourlyRate,
            'hours_per_week' => $bookingRequest->expected_hours_per_week,
            'total_weeks' => $totalWeeks,
            'total_hours' => $totalHours,
            'subtotal_calculation' => "{$hourlyRate} × {$bookingRequest->expected_hours_per_week} × {$totalWeeks}",
            'subtotal_amount' => $subtotalAmount
        ]);

        // Get commission rate
        $commissionRate = $this->getCommissionRate($bookingRequest->occupation_category_id);

        // ✅ FIXED: Commission is deducted from subtotal
        $commissionAmount = $subtotalAmount * ($commissionRate / 100);
        $totalAmount = $subtotalAmount; // Parent pays the subtotal
        $babysitterEarnings = $subtotalAmount - $commissionAmount; // Babysitter gets subtotal minus commission

        // ✅ FIX: Ensure amounts are positive
        if ($totalAmount <= 0) {
            throw new \Exception('Calculated amount is zero or negative. Subtotal: ' . $subtotalAmount);
        }

        Log::info('💰 CALCULATION DEBUG - FINAL:', [
            'commission_rate' => $commissionRate . '%',
            'commission_amount' => $commissionAmount,
            'total_amount' => $totalAmount,
            'babysitter_earnings' => $babysitterEarnings,
            'calculation_breakdown' => [
                'base' => $subtotalAmount,
                'commission' => $commissionAmount,
                'babysitter_share' => $babysitterEarnings,
                'platform_earnings' => $commissionAmount
            ]
        ]);

        return [
            'total_weeks' => $totalWeeks,
            'total_hours' => $totalHours,
            'hourly_rate' => $hourlyRate,
            'subtotal_amount' => round($subtotalAmount, 2),
            'commission_rate' => $commissionRate,
            'commission_amount' => round($commissionAmount, 2),
            'total_amount' => round($totalAmount, 2),
            'babysitter_earnings' => round($babysitterEarnings, 2)
        ];
    } catch (\Exception $e) {
        Log::error('❌ CALCULATION ERROR:', [
            'error' => $e->getMessage(),
            'booking_request_id' => $bookingRequest->booking_request_id,
            'hourly_rate' => $bookingRequest->hourly_rate,
            'hours_per_week' => $bookingRequest->expected_hours_per_week,
            'trace' => $e->getTraceAsString()
        ]);
        throw $e;
    }
}

    private function getCommissionRate($occupationCategoryId)
    {
        try {
            $commissionRate = CommissionRate::getRateByOccupationCategory($occupationCategoryId);
            $finalRate = $commissionRate ? $commissionRate->commission_value : 15.00;

            Log::info('ЁЯУК COMMISSION RATE - Selected:', [
                'occupation_category_id' => $occupationCategoryId,
                'final_commission_rate' => $finalRate,
                'source' => $commissionRate ? ($commissionRate->category_id ? 'direct_category' : 'applicable_all') : 'default'
            ]);

            return $finalRate;
        } catch (\Exception $e) {
            Log::error('тЭМ COMMISSION RATE - Error:', [
                'error' => $e->getMessage()
            ]);
            return 15.00;
        }
    }


   public function show(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::with([
                'bookingRequest',
                'parent',
                'babysitter',
                'occupationCategory',
                'reviews.reviewer', // Add reviews with reviewer details
                'reviews.reviewedUser' // Add reviewed user details
            ])->find($id);

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

            return response()->json([
                'success' => true,
                'data' => $booking
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to fetch booking: ' . $e->getMessage());

            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch booking',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
    public function updateStatus(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::find($id);

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

            $validator = Validator::make($request->all(), [
                'booking_status' => 'required|in:pending_payment,confirmed,active,completed,cancelled,refunded',
                'payment_status' => 'sometimes|in:pending,processing,paid,failed,refunded',
            ]);

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

            $validated = $validator->validated();

            // Update status with appropriate timestamps
            if ($validated['booking_status'] === 'confirmed' && !$booking->confirmed_at) {
                $validated['confirmed_at'] = now();
            } elseif ($validated['booking_status'] === 'active' && !$booking->started_at) {
                $validated['started_at'] = now();
            } elseif ($validated['booking_status'] === 'completed' && !$booking->completed_at) {
                $validated['completed_at'] = now();
            } elseif ($validated['booking_status'] === 'cancelled' && !$booking->cancelled_at) {
                $validated['cancelled_at'] = now();
            }

            if (isset($validated['payment_status']) && $validated['payment_status'] === 'paid' && !$booking->payment_made_at) {
                $validated['payment_made_at'] = now();
            }

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

            return response()->json([
                'success' => true,
                'message' => 'Booking status updated successfully',
                'data' => $booking
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to update booking status: ' . $e->getMessage());

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

    public function confirmBooking(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::find($id);

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

            if ($booking->booking_status !== 'pending_payment') {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking is not in pending payment status'
                ], 422);
            }

            $booking->markAsConfirmed();

            return response()->json([
                'success' => true,
                'message' => 'Booking confirmed successfully',
                'data' => $booking->load(['bookingRequest', 'parent', 'babysitter', 'occupationCategory'])
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to confirm booking: ' . $e->getMessage());

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

     public function startBooking(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::with(['parent', 'babysitter'])->find($id);

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

            // Check if user has permission to start this booking
            $user = $request->user();
            if (!in_array($user->user_type, ['babysitter', 'super_admin']) ||
                ($user->user_type === 'babysitter' && $booking->babysitter_id !== $user->user_id)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to start this booking'
                ], 403);
            }

            if ($booking->booking_status !== 'confirmed') {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking must be confirmed before starting'
                ], 422);
            }

            DB::transaction(function () use ($booking) {
                $booking->update([
                    'booking_status' => 'in_progress',
                    'started_at' => now(),
                    'updated_at' => now()
                ]);

                // ✅ SEND BOOKING STARTED NOTIFICATIONS
                $this->sendBookingStartedNotifications($booking);
            });

            return response()->json([
                'success' => true,
                'message' => 'Booking started successfully',
                'data' => $booking
            ]);

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

    /**
     * ✅ UPDATED: Complete Booking with Notifications
     */
    public function completeBooking(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::with(['parent', 'babysitter'])->find($id);

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

            // Check if user has permission to complete this booking
            $user = $request->user();
            if (!in_array($user->user_type, ['babysitter', 'super_admin']) ||
                ($user->user_type === 'babysitter' && $booking->babysitter_id !== $user->user_id)) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to complete this booking'
                ], 403);
            }

            if ($booking->booking_status !== 'in_progress') {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking must be in progress before completing'
                ], 422);
            }

            DB::transaction(function () use ($booking) {
                $booking->update([
                    'booking_status' => 'completed',
                    'completed_at' => now(),
                    'updated_at' => now()
                ]);

                // ✅ SEND BOOKING COMPLETED NOTIFICATIONS
                $this->sendBookingCompletedNotifications($booking);
            });

            return response()->json([
                'success' => true,
                'message' => 'Booking completed successfully',
                'data' => $booking
            ]);

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

    /**
     * ✅ NEW: Send Booking Started Notifications
     */
    private function sendBookingStartedNotifications(Booking $booking)
    {
        try {
            Log::info('🔔 BOOKING STARTED NOTIFICATIONS - Starting to send notifications');

            $parent = User::find($booking->parent_id);
            $babysitter = User::find($booking->babysitter_id);
            $superAdmin = User::whereHas('role', function ($query) {
                $query->where('role_name', 'super_admin');
            })->first();

            // Send notification to Parent
            if ($parent) {
                $parent->notify(new BookingStartedNotification($booking, 'parent'));
                Log::info('✅ BOOKING STARTED NOTIFICATION - Sent to parent', [
                    'parent_id' => $parent->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            // Send notification to Babysitter
            if ($babysitter) {
                $babysitter->notify(new BookingStartedNotification($booking, 'babysitter'));
                Log::info('✅ BOOKING STARTED NOTIFICATION - Sent to babysitter', [
                    'babysitter_id' => $babysitter->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            // Send notification to SuperAdmin
            if ($superAdmin) {
                $superAdmin->notify(new SuperAdminBookingNotification($booking, 'started'));
                Log::info('✅ BOOKING STARTED NOTIFICATION - Sent to superadmin', [
                    'superadmin_id' => $superAdmin->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            Log::info('🎉 BOOKING STARTED NOTIFICATIONS - All notifications sent successfully');

        } catch (\Exception $e) {
            Log::error('❌ BOOKING STARTED NOTIFICATIONS - Failed to send:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage()
            ]);
        }
    }

    /**
     * ✅ NEW: Send Booking Completed Notifications
     */
    private function sendBookingCompletedNotifications(Booking $booking)
    {
        try {
            Log::info('🔔 BOOKING COMPLETED NOTIFICATIONS - Starting to send notifications');

            $parent = User::find($booking->parent_id);
            $babysitter = User::find($booking->babysitter_id);
            $superAdmin = User::whereHas('role', function ($query) {
                $query->where('role_name', 'super_admin');
            })->first();

            // Send notification to Parent
            if ($parent) {
                $parent->notify(new BookingCompletedNotification($booking, 'parent'));
                Log::info('✅ BOOKING COMPLETED NOTIFICATION - Sent to parent', [
                    'parent_id' => $parent->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            // Send notification to Babysitter
            if ($babysitter) {
                $babysitter->notify(new BookingCompletedNotification($booking, 'babysitter'));
                Log::info('✅ BOOKING COMPLETED NOTIFICATION - Sent to babysitter', [
                    'babysitter_id' => $babysitter->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            // Send notification to SuperAdmin
            if ($superAdmin) {
                $superAdmin->notify(new SuperAdminBookingNotification($booking, 'completed'));
                Log::info('✅ BOOKING COMPLETED NOTIFICATION - Sent to superadmin', [
                    'superadmin_id' => $superAdmin->user_id,
                    'booking_id' => $booking->booking_id
                ]);
            }

            Log::info('🎉 BOOKING COMPLETED NOTIFICATIONS - All notifications sent successfully');

        } catch (\Exception $e) {
            Log::error('❌ BOOKING COMPLETED NOTIFICATIONS - Failed to send:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage()
            ]);
        }
    }


    /**
     * тЬЕ NEW: Create Review Eligibility after Booking Completion
     */
    private function createReviewEligibility($booking)
    {
        try {
            // Check if reviews already exist for this booking
            $existingReviews = \App\Models\Review::where('booking_id', $booking->booking_id)->count();

            if ($existingReviews === 0) {
                Log::info('ЁЯУЭ REVIEW ELIGIBILITY - Created for completed booking:', [
                    'booking_id' => $booking->booking_id,
                    'parent_id' => $booking->parent_id,
                    'babysitter_id' => $booking->babysitter_id
                ]);
            }
        } catch (\Exception $e) {
            Log::error('тЭМ REVIEW ELIGIBILITY - Failed to create:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage()
            ]);
        }
    }

   public function getMyBookings(Request $request): JsonResponse
    {
        try {
            // Check if user is authenticated
            if (!$request->user()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthenticated. Please login first.'
                ], 401);
            }

            $user = $request->user();
            $type = $request->get('type', 'all'); // 'as_parent' or 'as_babysitter'

            $query = Booking::with([
                'bookingRequest',
                'parent',
                'babysitter',
                'occupationCategory',
                'reviews' // Add reviews relationship
            ]);

            if ($type === 'as_parent') {
                $query->byParent($user->user_id);
            } elseif ($type === 'as_babysitter') {
                $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('booking_status')) {
                $query->where('booking_status', $request->get('booking_status'));
            }

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

            return response()->json([
                'success' => true,
                'data' => $bookings->items(),
                'pagination' => [
                    'current_page' => $bookings->currentPage(),
                    'per_page' => $bookings->perPage(),
                    'total' => $bookings->total(),
                    'last_page' => $bookings->lastPage(),
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to fetch bookings: ' . $e->getMessage());

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

    public function forceCompleteBooking(Request $request, string $id): JsonResponse
    {
        try {
            $booking = Booking::find($id);

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

            // Only admin or specific roles can force complete
            $user = $request->user();
            if (!$user->isAdmin()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Only administrators can force complete bookings'
                ], 403);
            }

            $reason = $request->get('reason', 'admin_force_complete');
            $booking->forceComplete($reason);

            return response()->json([
                'success' => true,
                'message' => 'Booking force completed successfully',
                'data' => $booking->load(['bookingRequest', 'parent', 'babysitter', 'occupationCategory'])
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to force complete booking: ' . $e->getMessage());

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