<?php

namespace App\Http\Controllers;

use App\Models\Booking;
use App\Http\Requests\BookingStoreRequest;
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;
use App\Models\EventBookingDetail;
use App\Models\SchoolServiceBookingDetail;
use App\Models\ServiceBookingDetail;
use Illuminate\Http\Request;
use App\Services\PaystackService;
use App\Services\PaypalService;
use Illuminate\Support\Facades\Log;

class BookingController extends Controller
{
    public function myBookings()
    {
        $bookings = Booking::where('user_id', Auth::id())
            ->with('bookable')
            ->latest()
            ->paginate(10);

        return Inertia::render('User/MyBookings', [
            'bookings' => $bookings,
        ]);
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(BookingStoreRequest $request)
    {
        $validated = $request->validated();
        $booking = Booking::create([
            'user_id' => Auth::id(),
            'bookable_id' => $validated['bookable_id'],
            'bookable_type' => $validated['bookable_type'],
            'status' => 'pending',
            'booking_date' => $validated['booking_date'] ?? null,
            'notes' => $validated['notes'] ?? null,
            'price' => $validated['price'],
            'quantity' => $validated['quantity'],
            'reference_id' => 'PB_'.uniqid()
        ]);

        // Create associated detail record based on bookable_type
        switch ($validated['bookable_type']) {
            case 'App\\Models\\Event':
                EventBookingDetail::create([
                    'booking_id' => $booking->id,
                    'attendees' => $validated['quantity'] ?? null, // Use quantity from main booking
                    'notes' => $validated['notes'] ?? null,
                    'event_id' => $validated['bookable_id'], // Use bookable_id as event_id
                    'price' => $validated['price'],
                    'user_id' => Auth::id(),
                ]);
                break;
            case 'App\\Models\\SchoolService':
                SchoolServiceBookingDetail::create([
                    'booking_id' => $booking->id,
                    'phone_number' => $validated['phone_number'] ?? null,
                ]);
                break;
            case 'App\\Models\\Service':
                ServiceBookingDetail::create([
                    'booking_id' => $booking->id,
                    'booking_time' => $validated['booking_time'] ?? null,
                    'service_id' => $validated['bookable_id'],
                ]);
                break;
        }
        
        // Notify the user about the new booking
        $user = \App\Models\User::find(Auth::id());
        if ($user) {
            $user->notify(new \App\Notifications\NewBookingNotification($booking));
        }
        
        return response()->json([
            'message' => 'Booking created successfully.',
            'booking' => $booking->load('eventBookingDetail', 'schoolServiceBookingDetail', 'serviceBookingDetail'),
        ]);
    }

    public function updateStatus(Request $request, Booking $booking)
    {
        $request->validate([
            'status' => ['required', 'string', 'in:confirmed,cancelled,pending'],
        ]);

        $booking->update([
            'status' => $request->status,
        ]);

        return response()->json([
            'message' => 'Booking status updated successfully.',
            'booking' => $booking,
        ]);
    }

    public function initiatePayment(Request $request, Booking $booking, PaystackService $paystackService)
    {
        $request->validate([
            'payment_method' => ['required', 'string', 'in:paystack,paypal'],
        ]);

        $user = Auth::user();

        if (!$user) {
            return response()->json(['message' => 'User not authenticated.'], 401);
        }

        // Ensure the booking belongs to the authenticated user
        if ($booking->user_id !== $user->id) {
            return response()->json(['message' => 'Unauthorized to initiate payment for this booking.'], 403);
        }

        // Ensure the booking is in a pending state and has a price
        if ($booking->status !== 'pending' || $booking->price <= 0) {
            return response()->json(['message' => 'Payment cannot be initiated for this booking.'], 400);
        }

        $amount = $booking->price;
        $email = $user->email;
        $orderId = $booking->reference_id; // Unique order ID for payment gateway

        try {
            if ($request->payment_method === 'paystack') {
                $data = [
                    'amount' => $amount,
                    'email' => $email,
                    'orderID' => $orderId,
                    'callback_url' => route('paystack.callback'),
                    'reference' => $orderId,
                    'metadata' => [
                        'booking_id' => $booking->id,
                    ],
                ];
                $result = $paystackService->initializePayment($data);

                if ($result['status']) {
                    return response()->json(['authorization_url' => $result['authorization_url']]);
                }
            } elseif ($request->payment_method === 'paypal') {
                $data = [
                    'amount' => $amount,
                    'order_id' => $booking->id, // This is actually the booking ID
                    'custom_id' => $booking->id, // Pass booking_id as custom_id for PayPal metadata
                ];
                $result = $paypalService->initializePayment($data);

                if ($result['status']) {
                    return response()->json(['authorization_url' => $result['authorization_url']]);
                }
            }

            Log::error('Payment initiation failed for booking ' . $booking->id . ': ' . ($result['message'] ?? 'Unknown error'));
            return response()->json(['message' => $result['message'] ?? 'Payment initialization failed. Please try again.'], 500);
        } catch (\Exception $e) {
            Log::error('Payment initiation error for booking ' . $booking->id . ': ' . $e->getMessage());
            return response()->json(['message' => 'An error occurred during payment initiation. Please try again later.'], 500);
        }
    }
}
