<?php

use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Models\Payment;
use App\Models\Booking;
use App\Models\Payout;
use App\Models\CommissionEarning;
use App\Events\NewUserRegistered;
use App\Http\Controllers\AuthController;
use App\Models\User;
use Illuminate\Support\Facades\Validator;
use Razorpay\Api\Api;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

// Payment Verification Dashboard
Route::get('/payment-verification', function () {
    return view('payment-verification');
});
// Password Reset Page Route
Route::get('/reset-password', function () {
    return view('reset-password'); // ✅ Removed auth. prefix
})->name('password.reset');

Route::get('/test-notifications', function () {
    return view('test-notifications');
});

// Private Channel Authentication for Pusher
Route::post('/broadcasting/auth', function (Request $request) {
    try {
        // For private-superadmin.notifications channel
        if ($request->channel_name == 'private-superadmin.notifications') {
            // In real app, check if user is super admin
            // For testing, allow all authenticated users
            $user = auth()->user();

            if ($user) {
                return response()->json([
                    'auth' => 'authorized'
                ]);
            }
        }

        // For user-specific channels
        if (str_starts_with($request->channel_name, 'private-App.Models.User.')) {
            $user = auth()->user();
            $channelUserId = str_replace('private-App.Models.User.', '', $request->channel_name);

            if ($user && $user->user_id == $channelUserId) {
                return response()->json([
                    'auth' => 'authorized'
                ]);
            }
        }

        return response()->json(['error' => 'Unauthorized'], 403);
    } catch (\Exception $e) {
        return response()->json(['error' => 'Authentication failed'], 500);
    }
})->middleware('web'); // Use web middleware for session



// web.php - Add these routes

// Test route for public channel
Route::get('/test-public-event', function () {
    $user = \App\Models\User::latest()->first();

    if (!$user) {
        return response()->json(['error' => 'No user found'], 404);
    }

    // Fire event
    event(new \App\Events\NewUserRegistered($user, 'Public-Test'));

    return response()->json([
        'success' => true,
        'message' => 'Public event fired successfully',
        'channel' => 'public-notifications',
        'user' => $user->email,
        'timestamp' => now()
    ]);
});



// Example: routes/api.php ya jahan bhi register route hai
Route::post('/register', function (Request $request) {
    // Existing registration code...

    // User create karne ke baad
    $user = User::create([
        'email' => $request->email,
        'password' => bcrypt($request->password),
        'first_name' => $request->first_name,
        'last_name' => $request->last_name,
        'role_id' => 2, // parent role
        // ... other fields
    ]);

    // ✅ TOKEN CREATE KARO - Add this line
    $token = $user->createToken('auth-token')->plainTextToken;

    // ✅ YEH LINE ADD KARO - Event fire karo
    event(new \App\Events\NewUserRegistered($user, 'Parent'));

    return response()->json([
        'success' => true,
        'message' => 'User registered successfully',
        'data' => [
            'user' => $user,
            'access_token' => $token, // ✅ NOW THIS VARIABLE EXISTS
            'token_type' => 'Bearer'
        ]
    ]);
});


// web.php mein yeh corrected route add karo
Route::post('/test-real-registration', function (Request $request) {
    try {
        $validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:6|confirmed',
            'first_name' => 'required',
            'last_name' => 'required',
        ]);

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

        // ✅ CORRECT PASSWORD FIELD SET KARO
        $userData = [
            'email' => $request->email,
            'first_name' => $request->first_name,
            'last_name' => $request->last_name,
            'role_id' => 2, // parent role
            'phone_number' => $request->phone_number ?? '+1234567890',
            'date_of_birth' => $request->date_of_birth ?? '1990-01-01',
            'gender' => $request->gender ?? 'male',
            'is_active' => true,
            'password_hash' => Hash::make($request->password), // ✅ YEH IMPORTANT HAI
        ];

        $user = \App\Models\User::create($userData);

        // Create token
        $token = $user->createToken('auth-token')->plainTextToken;

        // ✅ REAL-TIME EVENT FIRE KARO
        event(new \App\Events\NewUserRegistered($user, 'Parent'));

        return response()->json([
            'success' => true,
            'message' => 'User registered successfully WITH REAL-TIME NOTIFICATION',
            'data' => [
                'user_id' => $user->user_id,
                'email' => $user->email,
                'name' => $user->first_name . ' ' . $user->last_name,
                'access_token' => $token,
                'token_type' => 'Bearer',
                'real_time_notification_sent' => true
            ]
        ], 201);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Registration failed: ' . $e->getMessage()
        ], 500);
    }
});

Route::get('/test-event-broadcast', function () {
    $user = \App\Models\User::latest()->first();

    // Method 1: event() helper
    event(new \App\Events\NewUserRegistered($user, 'Event-Test'));

    // Method 2: broadcast() helper
    broadcast(new \App\Events\NewUserRegistered($user, 'Broadcast-Test'));

    // Method 3: Facade
    \Illuminate\Support\Facades\Event::dispatch(new \App\Events\NewUserRegistered($user, 'Facade-Test'));

    return response()->json([
        'success' => true,
        'message' => '3 Laravel events fired',
        'methods_used' => ['event()', 'broadcast()', 'Event::dispatch()']
    ]);
});

// Update existing test-real-event route
Route::get('/test-real-event', function () {
    $user = \App\Models\User::latest()->first();

    if (!$user) {
        return response()->json(['error' => 'No user found'], 404);
    }

    // Fire to public channel
    event(new \App\Events\NewUserRegistered($user, 'Real-Time-Test'));

    return response()->json([
        'success' => true,
        'message' => 'Real event fired on PUBLIC channel',
        'channel' => 'public-notifications',
        'event' => 'user.registered',
        'user' => $user->email,
        'timestamp' => now()
    ]);
});
Route::get('/test-event', function () {
    try {
        $user = \App\Models\User::latest()->first();
        if ($user) {
            event(new \App\Events\NewUserRegistered($user, 'Test'));
            return response()->json([
                'success' => true,
                'message' => 'Test event fired successfully',
                'user' => $user->email
            ]);
        }
        return response()->json(['success' => false, 'message' => 'No user found']);
    } catch (\Exception $e) {
        return response()->json(['success' => false, 'message' => $e->getMessage()]);
    }
});

// web.php mein yeh route add karo
Route::get('/test-pusher-direct', function () {
    try {
        $user = \App\Models\User::latest()->first();

        // Direct Pusher PHP library use karo
        $pusher = new Pusher\Pusher(
            config('broadcasting.connections.pusher.key'),
            config('broadcasting.connections.pusher.secret'),
            config('broadcasting.connections.pusher.app_id'),
            [
                'cluster' => config('broadcasting.connections.pusher.options.cluster'),
                'useTLS' => true
            ]
        );

        $data = [
            'user_id' => $user->user_id,
            'user_name' => $user->first_name . ' ' . $user->last_name,
            'user_email' => $user->email,
            'user_type' => 'Direct-Pusher-Test',
            'message' => 'Direct Pusher test',
            'timestamp' => now()->toDateTimeString()
        ];

        $result = $pusher->trigger('public-notifications', 'user.registered', $data);

        return response()->json([
            'success' => true,
            'message' => 'Direct Pusher broadcast attempted',
            'pusher_result' => $result,
            'data_sent' => $data
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Direct Pusher failed: ' . $e->getMessage()
        ], 500);
    }
});
// web.php mein yeh route add karo
Route::get('/check-pusher-connection', function () {
    try {
        $pusherConfig = config('broadcasting.connections.pusher');

        // Test Pusher connection
        $pusher = new Pusher\Pusher(
            $pusherConfig['key'],
            $pusherConfig['secret'],
            $pusherConfig['app_id'],
            $pusherConfig['options']
        );

        $result = $pusher->get('/channels/public-notifications');

        return response()->json([
            'success' => true,
            'pusher_config' => [
                'key' => $pusherConfig['key'],
                'app_id' => $pusherConfig['app_id'],
                'cluster' => $pusherConfig['options']['cluster'],
                'secret_exists' => !empty($pusherConfig['secret'])
            ],
            'channel_info' => $result
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'error' => $e->getMessage(),
            'pusher_config' => [
                'key' => config('broadcasting.connections.pusher.key'),
                'app_id' => config('broadcasting.connections.pusher.app_id'),
                'cluster' => config('broadcasting.connections.pusher.options.cluster')
            ]
        ], 500);
    }
});
// web.php mein yeh debug route add karo
Route::get('/debug-event-now', function () {
    $user = \App\Models\User::latest()->first();

    if (!$user) {
        return response()->json(['error' => 'No user found'], 404);
    }

    // Method 1: event() helper
    event(new \App\Events\NewUserRegistered($user, 'Debug-Test'));

    // Method 2: broadcast() helper
    broadcast(new \App\Events\NewUserRegistered($user, 'Broadcast-Test'));

    // Method 3: Direct dispatch
    \App\Events\NewUserRegistered::dispatch($user, 'Dispatch-Test');

    return response()->json([
        'debug' => true,
        'message' => '3 events fired manually',
        'user' => $user->email,
        'events_fired' => 3
    ]);
});

// ✅ UPDATED: Test API route for payments for USER 45
Route::get('/test/payments/user/45', function (Request $request) {
    try {
        $query = Payment::with(['booking', 'parent', 'babysitter'])
            ->where('parent_id', 45); // Only payments for user_id 45

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

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

        return response()->json([
            'success' => true,
            'data' => $payments->items(),
            'pagination' => [
                'current_page' => $payments->currentPage(),
                'per_page' => $payments->perPage(),
                'total' => $payments->total(),
                'last_page' => $payments->lastPage(),
            ],
            'total_amount' => $payments->sum('amount'),
            'count' => $payments->count()
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch payments',
            'error' => $e->getMessage()
        ], 500);
    }
});

// ✅ UPDATED: Get specific payment details for USER 45
Route::get('/test/payments/{paymentId}', function ($paymentId) {
    try {
        $payment = Payment::with(['booking', 'parent', 'babysitter'])
            ->where('payment_id', $paymentId)
            ->where('parent_id', 45) // Only payments for user 45
            ->first();

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

        return response()->json([
            'success' => true,
            'data' => $payment
        ]);
    } catch (\Exception $e) {
        return response()->json([
            'success' => false,
            'message' => 'Failed to fetch payment details',
            'error' => $e->getMessage()
        ], 500);
    }
});

// ✅ UPDATED: Create payment order for USER 45
Route::post('/test/payments/create-order', function (Request $request) {
    return DB::transaction(function () use ($request) {
        try {
            $validator = Validator::make($request->all(), [
                'booking_id' => 'required|exists:bookings,booking_id',
            ]);

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

            $booking = Booking::with(['parent', 'babysitter'])
                ->where('booking_id', $request->booking_id)
                ->where('parent_id', 45) // ✅ UPDATED: Ensure it belongs to user 45
                ->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. Current status: ' . $booking->booking_status
                ], 400);
            }

            // Check for existing pending payment
            $existingPayment = Payment::where('booking_id', $booking->booking_id)
                ->where('parent_id', 45) // ✅ UPDATED
                ->whereIn('payment_status', ['pending', 'failed'])
                ->lockForUpdate()
                ->first();

            if ($existingPayment) {
                $payment = $existingPayment;
                $message = 'Existing payment order retrieved';
            } else {
                // Create new payment
                $razorpayKey = config('services.razorpay.key', env('RAZORPAY_KEY'));
                $razorpaySecret = config('services.razorpay.secret', env('RAZORPAY_SECRET'));
                $razorpay = new Api($razorpayKey, $razorpaySecret);

                $amountInPaise = $booking->total_amount * 100;

                $orderData = [
                    'receipt' => 'booking_' . $booking->booking_id,
                    'amount' => $amountInPaise,
                    'currency' => 'CAD',
                    'payment_capture' => 1,
                    'notes' => [
                        'booking_id' => $booking->booking_id,
                        'parent_id' => 45, // ✅ UPDATED
                        'babysitter_id' => $booking->babysitter_id
                    ]
                ];

                $razorpayOrder = $razorpay->order->create($orderData);

                // Create payment record
                $payment = Payment::create([
                    'booking_id' => $booking->booking_id,
                    'parent_id' => 45, // ✅ UPDATED
                    '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';
            }

            // Get or create Razorpay order
            if (empty($razorpayOrder)) {
                $razorpayKey = config('services.razorpay.key', env('RAZORPAY_KEY'));
                $razorpaySecret = config('services.razorpay.secret', env('RAZORPAY_SECRET'));
                $razorpay = new Api($razorpayKey, $razorpaySecret);

                $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' => 45,
                        'babysitter_id' => $booking->babysitter_id
                    ]
                ];

                $razorpayOrder = $razorpay->order->create($orderData);
            }

            // Update payment with Razorpay order ID if needed
            $payment->update([
                'razorpay_order_id' => $razorpayOrder['id']
            ]);

            return response()->json([
                'success' => true,
                'message' => $message,
                'data' => [
                    'razorpay_order_id' => $razorpayOrder['id'],
                    'amount' => $booking->total_amount,
                    'currency' => 'CAD',
                    'payment_id' => $payment->payment_id,
                    'razorpay_key' => config('services.razorpay.key')
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to create payment order',
                'error' => $e->getMessage()
            ], 500);
        }
    });
});

// ✅ UPDATED: Verify payment for USER 45
Route::post('/test/payments/verify', function (Request $request) {
    try {
        $validator = Validator::make($request->all(), [
            'razorpay_order_id' => 'required|string',
            'razorpay_payment_id' => 'required|string',
            'razorpay_signature' => 'required|string'
        ]);

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

        // Find payment
        $payment = Payment::where('razorpay_order_id', $request->razorpay_order_id)
            ->where('parent_id', 45)
            ->where('payment_status', 'pending')
            ->first();

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

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

        // Initialize Razorpay for verification
        $razorpayKey = config('services.razorpay.key', env('RAZORPAY_KEY'));
        $razorpaySecret = config('services.razorpay.secret', env('RAZORPAY_SECRET'));
        $razorpay = new Api($razorpayKey, $razorpaySecret);

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

        $razorpay->utility->verifyPaymentSignature($attributes);

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

        // Update booking status
        $booking = Booking::where('booking_id', $payment->booking_id)
            ->where('parent_id', 45)
            ->first();

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

            // Create commission earning
            try {
                $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'
                    ]);
                }
            } catch (\Exception $commissionError) {
                // Commission creation failed silently
            }

            // ✅ ✅ ✅ NEW: CREATE PAYOUT IN TEST ROUTE
            $payout = null;
            try {
                // Check if payout already exists
                $existingPayout = Payout::where('payment_id', $payment->payment_id)->first();

                if ($existingPayout) {
                    $payout = $existingPayout;
                } else {
                    // Create new payout
                    $payout = Payout::create([
                        'babysitter_id' => $booking->babysitter_id,
                        'payment_id' => $payment->payment_id,
                        'amount' => $booking->babysitter_earnings,
                        'currency' => 'CAD',
                        'payout_method' => 'bank_transfer',
                        'payout_status' => 'pending',
                        'scheduled_payout_date' => now()->addDays(7),
                        'created_at' => now(),
                        'updated_at' => now()
                    ]);
                }
            } catch (\Exception $payoutError) {
                $payout = null;
            }

            // ✅ ✅ ✅ NEW: ADD NOTIFICATIONS TO TEST ROUTE WITH PAYOUT
            try {
                // Get users
                $parent = \App\Models\User::find($booking->parent_id);
                $babysitter = \App\Models\User::find($booking->babysitter_id);
                $superAdmin = \App\Models\User::whereHas('role', function ($query) {
                    $query->where('role_name', 'super_admin');
                })->first();

                // Send notifications
                if ($parent) {
                    $parent->notify(new \App\Notifications\PaymentSuccessNotification($payment, $booking));
                }

                if ($babysitter) {
                    $babysitter->notify(new \App\Notifications\BookingPaymentReceivedNotification($booking, $payment));
                }

                if ($superAdmin) {
                    $superAdmin->notify(new \App\Notifications\SuperAdminPaymentNotification(
                        $payment,
                        $booking,
                        $commissionEarning ?? null,
                        $payout
                    ));
                }

                // ✅ NEW: Send payout notification to babysitter
                if ($babysitter && $payout) {
                    $babysitter->notify(new \App\Notifications\PayoutCreatedNotification($payout));
                }
            } catch (\Exception $notificationError) {
                // Notifications failed silently
            }
        }

        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,
                'payout_created' => $payout ? true : false,
                'payout_id' => $payout ? $payout->payout_id : null,
                'payout_amount' => $payout ? $payout->amount : null,
                'notifications_sent' => true
            ]
        ]);
    } catch (\Exception $e) {
        // Mark payment as failed
        if (isset($payment)) {
            $payment->update([
                'payment_status' => 'failed',
                'gateway_response' => $e->getMessage(),
                'updated_at' => now()
            ]);
        }

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