<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Razorpay\Api\Api;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Booking;
use App\Models\Payment;
use App\Models\User;
use App\Models\CommissionEarning;
use App\Models\Payout;
use App\Models\DirectBookingRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

// ✅ ✅ ✅ ADD ALL REQUIRED NOTIFICATION IMPORTS
use App\Notifications\PaymentSuccessNotification;
use App\Notifications\BookingPaymentReceivedNotification;
use App\Notifications\SuperAdminPaymentNotification;
use App\Notifications\PayoutCreatedNotification;

class PaymentController extends Controller
{
    private $razorpay;

    public function __construct()
    {
        $razorpayKey = config('services.razorpay.key', env('RAZORPAY_KEY'));
        $razorpaySecret = config('services.razorpay.secret', env('RAZORPAY_SECRET'));

        $this->razorpay = new Api($razorpayKey, $razorpaySecret);
    }

    /**
     * Create Razorpay Order for Payment
     */
   public function createRazorpayOrder(Request $request)
{
    Log::info('🎯 CREATE ORDER - Starting for booking: ' . $request->booking_id);

    return DB::transaction(function () use ($request) {
        try {
            if (!Auth::check()) {
                return response()->json([
                    'success' => false,
                    'message' => 'User not authenticated. Please login again.'
                ], 401);
            }

            $request->validate([
                'booking_id' => 'required|exists:bookings,booking_id',
                'payment_method' => 'required|in:razorpay'
            ]);

            $booking = Booking::where('booking_id', $request->booking_id)
                ->where('parent_id', Auth::id())
                ->first();

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

            // Check if booking is already paid
            if ($booking->payment_status === 'paid') {
                return response()->json([
                    'success' => false,
                    'message' => 'This booking is already paid.'
                ], 400);
            }

            // Check if booking is in correct status for payment
            if ($booking->booking_status !== 'pending_payment') {
                return response()->json([
                    'success' => false,
                    'message' => 'Booking is not ready for payment.'
                ], 400);
            }

            // ✅ CHECK FOR EXISTING PAYMENT (PENDING OR FAILED)
            $existingPayment = Payment::where('booking_id', $booking->booking_id)
                ->where('parent_id', Auth::id())
                ->whereIn('payment_status', ['pending', 'failed'])
                ->lockForUpdate()
                ->first();

            Log::info('🔍 CREATE ORDER - Existing payment check:', [
                'booking_id' => $booking->booking_id,
                'existing_payment_id' => $existingPayment ? $existingPayment->payment_id : 'none',
                'existing_status' => $existingPayment ? $existingPayment->payment_status : 'none'
            ]);

            if ($existingPayment) {
                // Use existing payment
                $payment = $existingPayment;
                $message = 'Existing payment order retrieved';

                Log::info('✅ CREATE ORDER - Using existing payment:', [
                    'payment_id' => $payment->payment_id,
                    'status' => $payment->payment_status
                ]);
            } else {
                // ✅ CREATE NEW PAYMENT ONLY IF NO EXISTING PAYMENT
                $amountInPaise = $booking->total_amount * 100;

                // Removed small amount validation - any amount can be processed
                // Only keep maximum limit validation
                if ($amountInPaise > 500000) {
                    return response()->json([
                        'success' => false,
                        'message' => 'Amount exceeds maximum allowed limit. Please contact support for large payments.'
                    ], 400);
                }

                // Create Razorpay order
                $orderData = [
                    'receipt' => 'booking_' . $booking->booking_id,
                    'amount' => $amountInPaise,
                    'currency' => 'CAD',
                    'payment_capture' => 1,
                    'notes' => [
                        'booking_id' => $booking->booking_id,
                        'parent_id' => Auth::id(),
                        'babysitter_id' => $booking->babysitter_id
                    ]
                ];

                Log::info('🆕 CREATE ORDER - Creating new Razorpay order');
                $razorpayOrder = $this->razorpay->order->create($orderData);

                // ✅ CREATE ONLY ONE PAYMENT RECORD
                $payment = Payment::create([
                    'booking_id' => $booking->booking_id,
                    'parent_id' => Auth::id(),
                    'babysitter_id' => $booking->babysitter_id,
                    'amount' => $booking->total_amount,
                    'currency' => 'CAD',
                    'base_currency_amount' => $booking->total_amount,
                    'commission_rate' => $booking->commission_rate,
                    'commission_amount' => $booking->commission_amount,
                    'babysitter_payout_amount' => $booking->babysitter_earnings,
                    'payment_method' => 'razorpay',
                    'payment_gateway' => 'razorpay',
                    'razorpay_order_id' => $razorpayOrder['id'],
                    'payment_status' => 'pending'
                ]);

                $message = 'Payment order created successfully';

                Log::info('🎉 CREATE ORDER - NEW PAYMENT CREATED:', [
                    'payment_id' => $payment->payment_id,
                    'razorpay_order_id' => $razorpayOrder['id'],
                    'booking_id' => $booking->booking_id
                ]);
            }

            // Get or create Razorpay order for the payment
            if (empty($razorpayOrder)) {
                $amountInPaise = $payment->amount * 100;

                $orderData = [
                    'receipt' => 'booking_' . $booking->booking_id . '_' . $payment->payment_id,
                    'amount' => $amountInPaise,
                    'currency' => 'CAD',
                    'payment_capture' => 1,
                    'notes' => [
                        'booking_id' => $booking->booking_id,
                        'parent_id' => Auth::id(),
                        'babysitter_id' => $booking->babysitter_id,
                        'payment_id' => $payment->payment_id
                    ]
                ];

                Log::info('🔄 CREATE ORDER - Creating new Razorpay order for existing payment');
                $razorpayOrder = $this->razorpay->order->create($orderData);

                // Update payment with new order ID
                $payment->update([
                    'razorpay_order_id' => $razorpayOrder['id'],
                    'payment_status' => 'pending',
                    'updated_at' => now()
                ]);

                Log::info('📝 CREATE ORDER - Updated existing payment with new order:', [
                    'payment_id' => $payment->payment_id,
                    'razorpay_order_id' => $razorpayOrder['id']
                ]);
            }

            return $this->prepareSuccessResponse($payment, $booking, $razorpayOrder, $message);
        } catch (\Exception $e) {
            Log::error('❌ CREATE ORDER - Failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Payment initialization failed: ' . $e->getMessage()
            ], 500);
        }
    });
}

    /**
     * ✅ UPDATED: Verify Razorpay Payment - WITH DIRECT BOOKING REQUEST UPDATE & NOTIFICATIONS
     */
    public function verifyRazorpayPayment(Request $request)
    {
        Log::info('🎯 VERIFY PAYMENT - Starting verification');

        return DB::transaction(function () use ($request) {
            try {
                $validator = Validator::make($request->all(), [
                    'razorpay_order_id' => 'required',
                    'razorpay_payment_id' => 'required',
                    'razorpay_signature' => 'required'
                ]);

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

                $validated = $validator->validated();

                Log::info('🔍 VERIFY PAYMENT - Request data:', [
                    'razorpay_order_id' => $request->razorpay_order_id,
                    'razorpay_payment_id' => $request->razorpay_payment_id
                ]);

                // ✅ FIND EXISTING PAYMENT WITH LOCK (NO AUTH CHECK)
                $payment = Payment::where('razorpay_order_id', $request->razorpay_order_id)
                    ->lockForUpdate()
                    ->first();

                if (!$payment) {
                    Log::error('❌ VERIFY PAYMENT - Payment not found for order:', [
                        'razorpay_order_id' => $request->razorpay_order_id
                    ]);

                    return response()->json([
                        'success' => false,
                        'message' => 'Payment record not found for this order.'
                    ], 404);
                }

                Log::info('✅ VERIFY PAYMENT - Found existing payment:', [
                    'payment_id' => $payment->payment_id,
                    'current_status' => $payment->payment_status,
                    'booking_id' => $payment->booking_id,
                    'parent_id' => $payment->parent_id
                ]);

                // ✅ DOUBLE PAYMENT PROTECTION
                if ($payment->payment_status === 'completed') {
                    Log::warning('⚠️ VERIFY PAYMENT - Payment already completed:', [
                        'payment_id' => $payment->payment_id,
                        'razorpay_payment_id' => $request->razorpay_payment_id
                    ]);

                    return response()->json([
                        'success' => false,
                        'message' => 'Payment is already completed.'
                    ], 400);
                }

                // ✅ STATUS CONSISTENCY CHECK
                if (!$payment->canAcceptPayment()) {
                    Log::error('❌ VERIFY PAYMENT - Payment cannot be processed in current status:', [
                        'payment_id' => $payment->payment_id,
                        'status' => $payment->payment_status
                    ]);

                    return response()->json([
                        'success' => false,
                        'message' => 'Payment cannot be processed in current status.'
                    ], 400);
                }

                // Verify payment signature
                $attributes = [
                    'razorpay_order_id' => $request->razorpay_order_id,
                    'razorpay_payment_id' => $request->razorpay_payment_id,
                    'razorpay_signature' => $request->razorpay_signature
                ];

                Log::info('🔐 VERIFY PAYMENT - Verifying signature');
                $this->razorpay->utility->verifyPaymentSignature($attributes);

                // ✅ UPDATE PAYMENT STATUS
                Log::info('📝 VERIFY PAYMENT - Updating payment record:', [
                    'payment_id' => $payment->payment_id,
                    'old_status' => $payment->payment_status,
                    'new_status' => 'completed'
                ]);

                $payment->update([
                    'razorpay_payment_id' => $request->razorpay_payment_id,
                    'razorpay_signature' => $request->razorpay_signature,
                    'payment_status' => 'completed',
                    'paid_at' => now(),
                    'updated_at' => now()
                ]);

                Log::info('🎉 VERIFY PAYMENT - Payment updated successfully:', [
                    'payment_id' => $payment->payment_id
                ]);

                // ✅ UPDATE BOOKING STATUS WITH CONSISTENCY CHECKS
                $booking = Booking::where('booking_id', $payment->booking_id)
                    ->lockForUpdate()
                    ->first();

                if ($booking) {
                    if (!$booking->canConfirmAfterPayment()) {
                        Log::error('❌ VERIFY PAYMENT - Booking cannot be confirmed:', [
                            'booking_id' => $booking->booking_id,
                            'current_status' => $booking->booking_status
                        ]);

                        // Rollback payment update
                        $payment->update(['payment_status' => 'pending']);

                        return response()->json([
                            'success' => false,
                            'message' => 'Booking cannot be confirmed in current status.'
                        ], 400);
                    }

                    $booking->update([
                        'payment_status' => 'paid',
                        'booking_status' => 'confirmed',
                        'payment_made_at' => now(),
                        'confirmed_at' => now(),
                        'updated_at' => now()
                    ]);

                    Log::info('✅ VERIFY PAYMENT - Booking updated:', [
                        'booking_id' => $booking->booking_id,
                        'payment_status' => 'paid',
                        'booking_status' => 'confirmed'
                    ]);

                    // ✅ CREATE COMMISSION EARNING
                    $commissionEarning = $this->createCommissionEarning($booking);

                    // ✅ CREATE AUTOMATIC PAYOUT FOR BABYSITTER
                    $payout = $this->createAutomaticPayout($booking, $payment);

                    // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS TO SUCCESS
                    $this->updateDirectBookingRequestPaymentStatus($booking, 'success');

                    // ✅ ✅ ✅ FIXED: ADD NOTIFICATIONS CALL
                    $this->sendPaymentSuccessNotifications($booking, $payment, $commissionEarning, $payout);
                }

                Log::info('💰 VERIFY PAYMENT - COMPLETED SUCCESSFULLY:', [
                    'payment_id' => $payment->payment_id,
                    'booking_id' => $booking->booking_id,
                    'amount' => $payment->amount,
                    'parent_id' => $payment->parent_id,
                    'notifications_sent' => true
                ]);

                return response()->json([
                    'success' => true,
                    'message' => 'Payment successful! Booking confirmed.',
                    'data' => [
                        'payment_id' => $payment->payment_id,
                        'booking_id' => $booking->booking_id,
                        'amount' => $payment->amount,
                        'transaction_id' => $request->razorpay_payment_id,
                        'parent_id' => $payment->parent_id,
                        'babysitter_id' => $payment->babysitter_id,
                        'direct_booking_payment_status' => 'success',
                        'notifications_sent' => true
                    ]
                ]);
            } catch (\Exception $e) {
                DB::rollBack();
                Log::error('❌ VERIFY PAYMENT - Failed: ' . $e->getMessage());
                Log::error('Stack trace: ' . $e->getTraceAsString());

                // Mark existing payment as failed
                if (isset($payment)) {
                    $payment->update([
                        'payment_status' => 'failed',
                        'gateway_response' => $e->getMessage(),
                        'updated_at' => now()
                    ]);

                    Log::error('⚠️ VERIFY PAYMENT - Marked as failed:', [
                        'payment_id' => $payment->payment_id
                    ]);

                    // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS TO FAILED
                    if (isset($booking)) {
                        $this->updateDirectBookingRequestPaymentStatus($booking, 'failed');
                    }
                }

                return response()->json([
                    'success' => false,
                    'message' => 'Payment verification failed: ' . $e->getMessage()
                ], 400);
            }
        });
    }

    /**
     * ✅ NEW: Send All Payment Success Notifications
     */
    private function sendPaymentSuccessNotifications(Booking $booking, Payment $payment, $commissionEarning, $payout)
    {
        try {
            Log::info('🔔 PAYMENT NOTIFICATIONS - Starting to send notifications');

            // Get all users involved
            $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();

            Log::info('🔔 PAYMENT NOTIFICATIONS - Users found:', [
                'parent_id' => $parent ? $parent->user_id : 'not found',
                'babysitter_id' => $babysitter ? $babysitter->user_id : 'not found',
                'superadmin_id' => $superAdmin ? $superAdmin->user_id : 'not found'
            ]);

            // ✅ 1. Send notification to Parent
            if ($parent) {
                $parent->notify(new PaymentSuccessNotification($payment, $booking));
                Log::info('✅ PAYMENT NOTIFICATION - Sent to parent', [
                    'parent_id' => $parent->user_id,
                    'booking_id' => $booking->booking_id,
                    'parent_name' => $parent->first_name . ' ' . $parent->last_name
                ]);
            } else {
                Log::warning('⚠️ PAYMENT NOTIFICATION - Parent not found', [
                    'parent_id' => $booking->parent_id
                ]);
            }

            // ✅ 2. Send notification to Babysitter
            if ($babysitter) {
                $babysitter->notify(new BookingPaymentReceivedNotification($booking, $payment));
                Log::info('✅ PAYMENT NOTIFICATION - Sent to babysitter', [
                    'babysitter_id' => $babysitter->user_id,
                    'booking_id' => $booking->booking_id,
                    'babysitter_name' => $babysitter->first_name . ' ' . $babysitter->last_name
                ]);
            } else {
                Log::warning('⚠️ PAYMENT NOTIFICATION - Babysitter not found', [
                    'babysitter_id' => $booking->babysitter_id
                ]);
            }

            // ✅ 3. Send notification to SuperAdmin with commission and payout details
            if ($superAdmin) {
                $superAdmin->notify(new SuperAdminPaymentNotification(
                    $payment,
                    $booking,
                    $commissionEarning,
                    $payout
                ));
                Log::info('✅ PAYMENT NOTIFICATION - Sent to superadmin', [
                    'superadmin_id' => $superAdmin->user_id,
                    'booking_id' => $booking->booking_id,
                    'superadmin_name' => $superAdmin->first_name . ' ' . $superAdmin->last_name
                ]);
            } else {
                Log::warning('⚠️ PAYMENT NOTIFICATION - SuperAdmin not found');
            }

            // ✅ 4. Send payout notification to babysitter
            if ($babysitter && $payout) {
                $babysitter->notify(new PayoutCreatedNotification($payout));
                Log::info('✅ PAYOUT NOTIFICATION - Sent to babysitter', [
                    'babysitter_id' => $babysitter->user_id,
                    'payout_id' => $payout->payout_id,
                    'payout_amount' => $payout->amount
                ]);
            }

            Log::info('🎉 PAYMENT NOTIFICATIONS - All notifications sent successfully');
        } catch (\Exception $e) {
            Log::error('❌ PAYMENT NOTIFICATIONS - Failed to send:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            // Don't break payment flow if notifications fail
        }
    }

    /**
     * ✅ NEW: Update Direct Booking Request Payment Status Automatically
     */
    private function updateDirectBookingRequestPaymentStatus(Booking $booking, string $status)
    {
        try {
            if (!$booking->booking_request_id) {
                Log::warning('⚠️ No booking request ID found for booking', [
                    'booking_id' => $booking->booking_id
                ]);
                return;
            }

            // Get the direct booking request associated with this booking
            $directBookingRequest = DirectBookingRequest::where('booking_request_id', $booking->booking_request_id)->first();

            if (!$directBookingRequest) {
                Log::warning('⚠️ Direct booking request not found for booking', [
                    'booking_id' => $booking->booking_id,
                    'booking_request_id' => $booking->booking_request_id
                ]);
                return;
            }

            // Map payment status to direct booking payment status
            $directBookingPaymentStatus = $this->mapPaymentStatus($status);

            // Update the direct booking request payment status
            $directBookingRequest->update([
                'payment_status' => $directBookingPaymentStatus
            ]);

            Log::info('✅ DIRECT BOOKING PAYMENT STATUS - Updated automatically:', [
                'direct_booking_request_id' => $directBookingRequest->booking_request_id,
                'booking_id' => $booking->booking_id,
                'old_status' => $directBookingRequest->getOriginal('payment_status'),
                'new_status' => $directBookingPaymentStatus,
                'triggered_by' => 'payment_' . $status
            ]);

        } catch (\Exception $e) {
            Log::error('❌ DIRECT BOOKING PAYMENT STATUS UPDATE - Failed:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            // Don't throw exception to avoid breaking the main payment flow
        }
    }

    /**
     * ✅ NEW: Map payment status to direct booking payment status
     */
    private function mapPaymentStatus(string $paymentStatus): string
    {
        $statusMap = [
            'success' => 'success',
            'completed' => 'success',
            'failed' => 'failed',
            'pending' => 'pending',
            'refunded' => 'failed' // Refunded payments are considered failed for booking requests
        ];

        return $statusMap[$paymentStatus] ?? 'pending';
    }

    /**
     * ✅ Create Commission Earning
     */
    private function createCommissionEarning($booking)
    {
        try {
            // Check if commission earning already exists
            $existingCommission = CommissionEarning::where('booking_id', $booking->booking_id)->first();

            if (!$existingCommission) {
                $commissionEarning = CommissionEarning::create([
                    'booking_id' => $booking->booking_id,
                    'commission_rate' => $booking->commission_rate,
                    'commission_amount' => $booking->commission_amount,
                    'earning_status' => 'pending'
                ]);

                Log::info('💰 COMMISSION EARNING - Created successfully:', [
                    'earning_id' => $commissionEarning->earning_id,
                    'booking_id' => $booking->booking_id,
                    'commission_amount' => $booking->commission_amount
                ]);

                return $commissionEarning;
            } else {
                Log::info('ℹ️ COMMISSION EARNING - Already exists:', [
                    'earning_id' => $existingCommission->earning_id
                ]);
                return $existingCommission;
            }
        } catch (\Exception $e) {
            Log::error('❌ COMMISSION EARNING - Failed to create:', [
                'booking_id' => $booking->booking_id,
                'error' => $e->getMessage()
            ]);
            return null;
        }
    }

    /**
     * ✅ FIXED: CREATE AUTOMATIC PAYOUT FOR BABYSITTER
     */
    private function createAutomaticPayout($booking, $payment)
    {
        try {
            Log::info('💰 PAYOUT - Creating automatic payout', [
                'booking_id' => $booking->booking_id,
                'payment_id' => $payment->payment_id,
                'babysitter_earnings' => $booking->babysitter_earnings
            ]);

            // Check if payout already exists
            $existingPayout = Payout::where('payment_id', $payment->payment_id)->first();

            if ($existingPayout) {
                Log::info('💰 PAYOUT - Already exists', [
                    'payout_id' => $existingPayout->payout_id
                ]);
                return $existingPayout;
            }

            // ✅ UPDATED: With currency field
            $payout = Payout::create([
                'babysitter_id' => $booking->babysitter_id,
                'payment_id' => $payment->payment_id,
                'amount' => $booking->babysitter_earnings,
                'currency' => 'CAD', // ✅ ADDED
                'payout_method' => 'bank_transfer',
                'payout_status' => 'pending',
                'scheduled_payout_date' => now()->addDays(7),
                'created_at' => now(),
                'updated_at' => now()
            ]);

            Log::info('🎉 PAYOUT - Created successfully', [
                'payout_id' => $payout->payout_id,
                'amount' => $payout->amount,
                'currency' => $payout->currency
            ]);

            return $payout;
        } catch (\Exception $e) {
            Log::error('❌ PAYOUT - Error: ' . $e->getMessage());
            return null;
        }
    }

    /**
     * Prepare success response
     */
    private function prepareSuccessResponse($payment, $booking, $razorpayOrder, $message)
    {
        $babysitter = User::find($booking->babysitter_id);
        $babysitterName = $babysitter ? $babysitter->first_name . ' ' . $babysitter->last_name : 'Babysitter';

        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => [
                'payment_id' => $payment->payment_id,
                'razorpay_order' => [
                    'id' => $razorpayOrder['id'],
                    'amount' => $razorpayOrder['amount'],
                    'currency' => $razorpayOrder['currency'],
                    'key' => config('services.razorpay.key', env('RAZORPAY_KEY'))
                ],
                'booking_details' => [
                    'booking_id' => $booking->booking_id,
                    'total_amount' => $booking->total_amount,
                    'babysitter_name' => $babysitterName,
                    'duration_weeks' => $booking->total_weeks
                ]
            ]
        ]);
    }

    public function getMyPayments(Request $request)
    {
        try {
            $payments = Payment::where('parent_id', Auth::id())
                ->with(['booking', 'babysitter'])
                ->orderBy('created_at', 'desc')
                ->paginate(10);

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

    /**
     * ✅ UPDATED: Razorpay Webhook Handler - WITH DIRECT BOOKING REQUEST UPDATE
     */
    public function razorpayWebhook(Request $request)
    {
        try {
            $webhookBody = $request->getContent();
            $webhookSignature = $request->header('X-Razorpay-Signature');
            $webhookSecret = env('RAZORPAY_WEBHOOK_SECRET');

            // Verify webhook signature
            $this->razorpay->utility->verifyWebhookSignature($webhookBody, $webhookSignature, $webhookSecret);

            $payload = json_decode($webhookBody, true);
            $event = $payload['event'];

            Log::info('Razorpay Webhook Received: ' . $event, $payload);

            // Handle different webhook events
            switch ($event) {
                case 'payment.captured':
                    $this->handlePaymentCaptured($payload);
                    break;

                case 'payment.failed':
                    $this->handlePaymentFailed($payload);
                    break;

                default:
                    Log::info('Unhandled webhook event: ' . $event);
            }

            return response()->json(['success' => true]);
        } catch (\Exception $e) {
            Log::error('Webhook processing failed: ' . $e->getMessage());
            return response()->json(['success' => false], 400);
        }
    }

    /**
     * ✅ UPDATED: Handle Payment Captured - WITH DIRECT BOOKING REQUEST UPDATE
     */
    private function handlePaymentCaptured($payload)
    {
        DB::transaction(function () use ($payload) {
            $paymentEntity = $payload['payload']['payment']['entity'];

            // ✅ Find and UPDATE existing payment record
            $payment = Payment::where('razorpay_order_id', $paymentEntity['order_id'])
                ->first();

            if ($payment && $payment->payment_status === 'pending') {
                // ✅ UPDATE existing record
                $payment->update([
                    'razorpay_payment_id' => $paymentEntity['id'],
                    'payment_status' => 'completed',
                    'paid_at' => now()
                ]);

                // Update booking
                $booking = $payment->booking;
                if ($booking) {
                    $booking->update([
                        'payment_status' => 'paid',
                        'booking_status' => 'confirmed',
                        'payment_made_at' => now(),
                        'confirmed_at' => now()
                    ]);

                    // ✅ CREATE COMMISSION EARNING FOR WEBHOOK TOO
                    $commissionEarning = $this->createCommissionEarning($booking);

                    // ✅ CREATE AUTOMATIC PAYOUT FOR WEBHOOK TOO
                    $payout = $this->createAutomaticPayout($booking, $payment);

                    // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS FOR WEBHOOK
                    $this->updateDirectBookingRequestPaymentStatus($booking, 'success');

                    // ✅ SEND ALL NOTIFICATIONS FOR WEBHOOK TOO
                    $this->sendPaymentSuccessNotifications($booking, $payment, $commissionEarning, $payout);
                }
            }
        });
    }

    /**
     * ✅ UPDATED: Handle failed payment webhook - WITH DIRECT BOOKING REQUEST UPDATE
     */
    private function handlePaymentFailed($payload)
    {
        DB::transaction(function () use ($payload) {
            $paymentEntity = $payload['payload']['payment']['entity'];

            $payment = Payment::where('razorpay_order_id', $paymentEntity['order_id'])
                ->first();

            if ($payment) {
                $payment->update([
                    'payment_status' => 'failed',
                    'gateway_response' => $paymentEntity['error_description'] ?? 'Payment failed'
                ]);

                // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS FOR FAILED PAYMENT
                $booking = $payment->booking;
                if ($booking) {
                    $this->updateDirectBookingRequestPaymentStatus($booking, 'failed');
                }
            }
        });
    }

    /**
     * ✅ UPDATED: Mark payment as completed (manual override) - WITH DIRECT BOOKING REQUEST UPDATE
     */
    public function markAsCompleted($id)
    {
        try {
            $payment = Payment::where('payment_id', $id)
                ->where('parent_id', Auth::id())
                ->firstOrFail();

            DB::transaction(function () use ($payment) {
                $payment->markAsCompleted();

                // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS FOR MANUAL COMPLETION
                $booking = $payment->booking;
                if ($booking) {
                    $this->updateDirectBookingRequestPaymentStatus($booking, 'success');
                }
            });

            return response()->json([
                'success' => true,
                'message' => 'Payment marked as completed.'
            ]);
        } catch (\Exception $e) {
            Log::error('Mark payment as completed failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to update payment status.'
            ], 500);
        }
    }

    /**
     * ✅ UPDATED: Mark payment as refunded - WITH DIRECT BOOKING REQUEST UPDATE
     */
    public function markAsRefunded($id)
    {
        try {
            $payment = Payment::where('payment_id', $id)
                ->where('parent_id', Auth::id())
                ->firstOrFail();

            DB::transaction(function () use ($payment) {
                $payment->markAsRefunded();

                // ✅ NEW: UPDATE DIRECT BOOKING REQUEST PAYMENT STATUS FOR REFUND
                $booking = $payment->booking;
                if ($booking) {
                    $this->updateDirectBookingRequestPaymentStatus($booking, 'failed');
                }
            });

            return response()->json([
                'success' => true,
                'message' => 'Payment marked as refunded.'
            ]);
        } catch (\Exception $e) {
            Log::error('Mark payment as refunded failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to update payment status.'
            ], 500);
        }
    }

    // ... (Other existing methods like getAllPayments, getPaymentById, etc. remain the same)

    /**
     * Get All Payments (Admin/All Users)
     */
    public function getAllPayments(Request $request): JsonResponse
    {
        try {
            $query = Payment::with(['booking', 'parent', 'babysitter']);

            // Get authenticated user
            $user = Auth::user();

            // TEMPORARY: For development, if no user is authenticated, show payments for user_id 12
            if (!$user) {
                $query->where('parent_id', 12); // Show payments for user_id 12
            } else {
                // If user is authenticated, filter by their user type
                if ($user->user_type === 'parent') {
                    $query->where('parent_id', $user->user_id);
                } elseif ($user->user_type === 'babysitter') {
                    $query->where('babysitter_id', $user->user_id);
                }
                // Admin can see all payments
            }

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

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

            // Filter by date range
            if ($request->has('start_date') && $request->has('end_date')) {
                $query->whereBetween('created_at', [
                    $request->get('start_date'),
                    $request->get('end_date')
                ]);
            }

            // Search by booking ID or payment ID
            if ($request->has('search')) {
                $search = $request->get('search');
                $query->where(function ($q) use ($search) {
                    $q->where('payment_id', 'like', "%{$search}%")
                        ->orWhere('razorpay_order_id', 'like', "%{$search}%")
                        ->orWhere('razorpay_payment_id', 'like', "%{$search}%")
                        ->orWhereHas('booking', function ($bookingQuery) use ($search) {
                            $bookingQuery->where('booking_id', 'like', "%{$search}%");
                        });
                });
            }

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

            // Get all or paginate
            if ($request->has('paginate') && !$request->boolean('paginate')) {
                $payments = $query->get();
            } else {
                $perPage = $request->get('per_page', 10);
                $payments = $query->paginate($perPage);
            }

            return response()->json([
                'success' => true,
                'data' => $payments,
                'total_amount' => $payments->sum('amount'),
                'count' => $payments->count()
            ]);
        } catch (\Exception $e) {
            Log::error('Get all payments failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payments',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get Payment by ID
     */
    public function getPaymentById(string $id): JsonResponse
    {
        try {
            $payment = Payment::with(['booking', 'parent', 'babysitter'])->find($id);

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

            // Check authorization
            $user = Auth::user();
            if ($user->user_type === 'parent' && $payment->parent_id !== $user->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to access this payment'
                ], 403);
            }

            if ($user->user_type === 'babysitter' && $payment->babysitter_id !== $user->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to access this payment'
                ], 403);
            }

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

    /**
     * Get Payments by Booking ID
     */
    public function getPaymentsByBooking(string $bookingId): JsonResponse
    {
        try {
            $booking = Booking::find($bookingId);

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

            // Check authorization
            $user = Auth::user();
            if ($user->user_type === 'parent' && $booking->parent_id !== $user->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to access this booking'
                ], 403);
            }

            if ($user->user_type === 'babysitter' && $booking->babysitter_id !== $user->user_id) {
                return response()->json([
                    'success' => false,
                    'message' => 'Unauthorized to access this booking'
                ], 403);
            }

            $payments = Payment::with(['parent', 'babysitter'])
                ->where('booking_id', $bookingId)
                ->orderBy('created_at', 'desc')
                ->get();

            return response()->json([
                'success' => true,
                'data' => $payments,
                'booking' => [
                    'booking_id' => $booking->booking_id,
                    'total_amount' => $booking->total_amount,
                    'payment_status' => $booking->payment_status
                ],
                'total_paid' => $payments->where('payment_status', 'completed')->sum('amount'),
                'count' => $payments->count()
            ]);
        } catch (\Exception $e) {
            Log::error('Get payments by booking failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payments for booking',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get Payment Statistics
     */
    public function getPaymentStatistics(Request $request): JsonResponse
    {
        try {
            $user = Auth::user();
            $query = Payment::query();

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

            // Date range filter
            if ($request->has('start_date') && $request->has('end_date')) {
                $query->whereBetween('created_at', [
                    $request->get('start_date'),
                    $request->get('end_date')
                ]);
            }

            $totalPayments = $query->count();
            $completedPayments = $query->where('payment_status', 'completed')->count();
            $pendingPayments = $query->where('payment_status', 'pending')->count();
            $failedPayments = $query->where('payment_status', 'failed')->count();

            $totalRevenue = $query->where('payment_status', 'completed')->sum('amount');
            $totalCommission = $query->where('payment_status', 'completed')->sum('commission_amount');
            $totalPayout = $query->where('payment_status', 'completed')->sum('babysitter_payout_amount');

            return response()->json([
                'success' => true,
                'data' => [
                    'total_payments' => $totalPayments,
                    'completed_payments' => $completedPayments,
                    'pending_payments' => $pendingPayments,
                    'failed_payments' => $failedPayments,
                    'success_rate' => $totalPayments > 0 ? round(($completedPayments / $totalPayments) * 100, 2) : 0,
                    'revenue' => [
                        'total_revenue' => $totalRevenue,
                        'total_commission' => $totalCommission,
                        'total_payout' => $totalPayout,
                        'net_earnings' => $totalRevenue - $totalPayout
                    ],
                    'average_payment' => $completedPayments > 0 ? round($totalRevenue / $completedPayments, 2) : 0
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Get payment statistics failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payment statistics',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }

    /**
     * Get Payments Summary (for dashboard)
     */
    public function getPaymentsSummary(): JsonResponse
    {
        try {
            $user = Auth::user();
            $query = Payment::query();

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

            // Recent payments (last 30 days)
            $recentPayments = $query->clone()
                ->with(['booking', 'babysitter'])
                ->where('created_at', '>=', now()->subDays(30))
                ->orderBy('created_at', 'desc')
                ->limit(10)
                ->get();

            // Monthly statistics
            $currentMonthRevenue = $query->clone()
                ->where('payment_status', 'completed')
                ->whereYear('created_at', now()->year)
                ->whereMonth('created_at', now()->month)
                ->sum('amount');

            $lastMonthRevenue = $query->clone()
                ->where('payment_status', 'completed')
                ->whereYear('created_at', now()->subMonth()->year)
                ->whereMonth('created_at', now()->subMonth()->month)
                ->sum('amount');

            return response()->json([
                'success' => true,
                'data' => [
                    'recent_payments' => $recentPayments,
                    'monthly_stats' => [
                        'current_month_revenue' => $currentMonthRevenue,
                        'last_month_revenue' => $lastMonthRevenue,
                        'growth_percentage' => $lastMonthRevenue > 0 ?
                            round((($currentMonthRevenue - $lastMonthRevenue) / $lastMonthRevenue) * 100, 2) : 0
                    ],
                    'quick_stats' => [
                        'total_payments' => $query->clone()->count(),
                        'completed_payments' => $query->clone()->where('payment_status', 'completed')->count(),
                        'pending_payments' => $query->clone()->where('payment_status', 'pending')->count()
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('Get payments summary failed: ' . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Failed to fetch payments summary',
                'error' => config('app.debug') ? $e->getMessage() : null
            ], 500);
        }
    }
}
