<?php

namespace App\Http\Controllers\Restaurant;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\Mail;

use Yajra\DataTables\Facades\DataTables;

use App\User;
use App\Contact;
use App\Utils\Util;
use App\GuestCheckin;
use App\CustomerGroup;
use App\OnlineBooking;
use App\BusinessLocation;
use App\Utils\ContactUtil;
use App\GuestRegistration;
use App\Restaurant\Booking;
use App\Utils\RestaurantUtil;

class BookingController extends Controller
{
    protected $commonUtil;
    protected $restUtil;

    public function __construct(Util $commonUtil, RestaurantUtil $restUtil)
    {
        $this->commonUtil = $commonUtil;
        $this->restUtil = $restUtil;

        $this->middleware(function ($request, $next) {
            if (auth()->check() && !session()->has('user.business_id')) {
                session([
                    'user.business_id' => auth()->user()->business_id,
                    'user.id' => auth()->user()->id,
                ]);
            }
            return $next($request);
        });
    }

    public function index()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        $business_id = request()->session()->get('user.business_id');

        $user_id = request()->has('user_id') ? request()->user_id : null;
        if (!auth()->user()->hasPermissionTo('crud_all_bookings') && !$this->restUtil->is_admin(auth()->user(), $business_id)) {
            $user_id = request()->session()->get('user.id');
        }
        if (request()->ajax()) {
            $filters = [
                'start_date' => request()->start,
                'end_date' => request()->end,
                'user_id' => $user_id,
                'location_id' => !empty(request()->location_id) ? request()->location_id : null,
                'business_id' => $business_id
            ];

            return $this->restUtil->getBookingsForCalendar($filters);
        }

        $business_locations = BusinessLocation::forDropdown($business_id);
        $customers = Contact::customersDropdown($business_id, false);
        $correspondents = User::forDropdown($business_id, false);
        $types = Contact::getContactTypes();
        $customer_groups = CustomerGroup::forDropdown($business_id);
        $rooms = [];

        $roomDefinitions = [
            101 => ['type' => 'Double Standard', 'price' => 5000],
            102 => ['type' => 'Double Standard', 'price' => 5000],
            103 => ['type' => 'Double Standard', 'price' => 5000],
            104 => ['type' => 'Double Standard', 'price' => 5000],

            105 => ['type' => 'Single', 'price' => 4000],
            106 => ['type' => 'Single', 'price' => 4000],
            107 => ['type' => 'Single', 'price' => 4000],
            108 => ['type' => 'Single', 'price' => 4000],

            201 => ['type' => 'Double Standard', 'price' => 5000],
            202 => ['type' => 'Double Standard', 'price' => 5000],
            203 => ['type' => 'Double Standard', 'price' => 5000],
            204 => ['type' => 'Double Standard', 'price' => 5000],

            205 => ['type' => 'Single', 'price' => 4000],
            206 => ['type' => 'Single', 'price' => 4000],
            207 => ['type' => 'Single', 'price' => 4000],
            208 => ['type' => 'Single', 'price' => 4000],

            209 => ['type' => 'Deluxe', 'price' => 7000],
            210 => ['type' => 'Executive', 'price' => 12000],
            211 => ['type' => 'Executive', 'price' => 12000],
            212 => ['type' => 'Deluxe', 'price' => 7000],
        ];

        foreach ($roomDefinitions as $roomNumber => $details) {
            $label = 'Room ' . $roomNumber . ' - ' . $details['type'] . ' - KES ' . number_format($details['price']);
            $rooms[$roomNumber] = $label;
        }

        return view('restaurant.booking.index', compact('business_locations', 'customers', 'correspondents', 'types', 'customer_groups', 'rooms'));
    }

    public function store(Request $request)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            if ($request->ajax()) {
                $business_id = request()->session()->get('user.business_id');
                $user_id = request()->session()->get('user.id');

                $input = $request->input();
                $booking_start = $this->commonUtil->uf_date($input['booking_start'], true);
                $booking_end = $this->commonUtil->uf_date($input['booking_end'], true);
                $date_range = [$booking_start, $booking_end];

                $query = Booking::where('business_id', $business_id)
                    ->where('room_number', $input['room_number'])
                    ->whereDate('booking_start', '<=', \Carbon\Carbon::parse($booking_end)->toDateString())
                    ->whereDate('booking_end', '>=', \Carbon\Carbon::parse($booking_start)->toDateString());

                if (isset($input['room_number'])) {
                    $query->where('room_number', $input['room_number']);
                }

                $existing_booking = $query->first();
                if (empty($existing_booking)) {
                    $input['business_id'] = $business_id;
                    $input['created_by'] = $user_id;
                    $input['booking_start'] = $booking_start;
                    $input['booking_end'] = $booking_end;
                    $input['room_number'] = $request->input('room_number');
                    $booking = Booking::createBooking($input);

                    if ($request->input('registration_id')) {
                        $registration = GuestRegistration::find($request->input('registration_id'));
                        if ($registration) {
                            $registration->update(['booking_id' => $booking->id]);

                            // Send guest booking confirmation email
                            if ($registration->email && $request->input('send_notification')) {
                                Mail::send([], [], function ($message) use ($registration, $booking, $input) {
                                    $html = '
                                        <div style="font-family: Arial, sans-serif; color: #333; padding: 20px; background: #f7f7f7;">
                                            <div style="max-width: 600px; margin: auto; background: #fff; border-radius: 10px; padding: 20px; box-shadow: 0 0 10px rgba(0,0,0,0.05);">
                                                <h2 style="color: #0055aa;">Booking Confirmation, ' . $registration->name . '</h2>
                                                <p>Your booking has been confirmed. Here are the details:</p>
                                                <table style="width: 100%; border-collapse: collapse; margin-top: 20px;">
                                                    <tr><td><strong>Name:</strong></td><td>' . $registration->surname . ' ' . $registration->name . '</td></tr>
                                                    <tr><td><strong>Check-in:</strong></td><td>' . $input['booking_start'] . '</td></tr>
                                                    <tr><td><strong>Check-out:</strong></td><td>' . $input['booking_end'] . '</td></tr>
                                                    <tr><td><strong>Room Number:</strong></td><td>' . $input['room_number'] . '</td></tr>
                                                    <tr><td><strong>Purpose:</strong></td><td>' . $registration->stay_purpose . '</td></tr>
                                                    <tr><td><strong>Payment Method:</strong></td><td>' . $registration->payment_method . '</td></tr>
                                                </table>
                                                <p style="margin-top: 20px;">If you have any questions, contact us at <a href="mailto:info@coffeegardensuite.co.ke">info@coffeegardensuite.co.ke</a>.</p>
                                                <p style="margin-top: 30px;">Warm regards,<br/>Coffee Garden Team</p>
                                            </div>
                                        </div>';
                                    $message->to($registration->email)
                                        ->subject('Booking Confirmation')
                                        ->setBody($html, 'text/html');
                                });
                            }
                        }
                    }

                    $output = ['success' => 1, 'msg' => trans("lang_v1.added_success")];

                    if (isset($input['send_notification']) && $input['send_notification'] == 1) {
                        $output['send_notification'] = 1;
                        $output['notification_url'] = action('NotificationController@getTemplate', ["transaction_id" => $booking->id, "template_for" => "new_booking"]);
                    }
                } else {
                    $time_range = $this->commonUtil->format_date($existing_booking->booking_start, true) . ' ~ ' .
                        $this->commonUtil->format_date($existing_booking->booking_end, true);
                    $output = ['success' => 0, 'msg' => trans("restaurant.booking_not_available", [
                        'customer_name' => $existing_booking->customer->name,
                        'booking_time_range' => $time_range
                    ])];
                }
            } else {
                $output = ['success' => 0, 'msg' => __("messages.something_went_wrong")];
            }
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile() . "Line:" . $e->getLine() . "Message:" . $e->getMessage());
            $output = ['success' => 0, 'msg' => __("messages.something_went_wrong")];
        }
        return $output;
    }

    public function show($id)
    {
        if (request()->ajax()) {
            $business_id = request()->session()->get('user.business_id');
            $booking = Booking::where('business_id', $business_id)
                ->where('id', $id)
                ->with(['table', 'customer', 'correspondent', 'waiter', 'location'])
                ->first();
            if (!empty($booking)) {
                $booking_start = $this->commonUtil->format_date($booking->booking_start, true);
                $booking_end = $this->commonUtil->format_date($booking->booking_end, true);

                $booking_statuses = [
                    'waiting' => __('lang_v1.waiting'),
                    'booked' => __('restaurant.booked'),
                    'completed' => __('restaurant.completed'),
                    'cancelled' => __('restaurant.cancelled'),
                ];
                return view('restaurant.booking.show', compact('booking', 'booking_start', 'booking_end', 'booking_statuses'));
            }
        }
    }

    public function update(Request $request, $id)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            $business_id = $request->session()->get('user.business_id');
            $booking = Booking::where('business_id', $business_id)
                ->find($id);
            if (!empty($booking)) {
                $booking->booking_status = $request->booking_status;
                $booking->save();
            }

            $output = ['success' => 1, 'msg' => trans("lang_v1.updated_success")];
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile() . "Line:" . $e->getLine() . "Message:" . $e->getMessage());
            $output = ['success' => 0, 'msg' => __("messages.something_went_wrong")];
        }
        return $output;
    }

    public function destroy($id)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }
        try {
            $business_id = request()->session()->get('user.business_id');
            Booking::where('business_id', $business_id)
                ->where('id', $id)
                ->delete();
            $output = ['success' => 1, 'msg' => trans("lang_v1.deleted_success")];
        } catch (\Exception $e) {
            \Log::emergency("File:" . $e->getFile() . "Line:" . $e->getLine() . "Message:" . $e->getMessage());
            $output = ['success' => 0, 'msg' => __("messages.something_went_wrong")];
        }
        return $output;
    }

    /**
     * Get count of pending online bookings
     */
    public function getOnlineBookingsCount()
    {
        $count = OnlineBooking::whereNull('converted_booking_id')
            ->where('status', '!=', 'converted')
            ->count();

        return response()->json(['count' => $count]);
    }

    /**
     * Enhanced getTodaysBookings to include online bookings
     */
  public function getTodaysBookings(Request $request)
    {
        try {
            Log::info('Fetching today\'s bookings', ['location_id' => $request->input('location_id')]);

            $query = Booking::today()
                ->with(['customer', 'guestCheckin', 'location', 'waiter', 'table'])
                ->active();

            if ($request->has('location_id') && !empty($request->location_id)) {
                $query->where('location_id', $request->location_id);
            }

            return DataTables::of($query)
                ->addColumn('customer', fn($booking) => $booking->guest_name)
                ->addColumn('contact_info', fn($booking) => $booking->contact_info)
                ->addColumn('guest_info', fn($booking) => $booking->guestCheckin ? $booking->guestCheckin->gender . ', ' . $booking->guestCheckin->nationality : 'N/A')
                ->addColumn('room_details', fn($booking) => $booking->room_number . ' (' . $booking->room_type . ')')
                ->addColumn('table', fn($booking) => $booking->table ? $booking->table->name : 'N/A')
                ->addColumn('location', fn($booking) => $booking->location ? $booking->location->name : 'N/A')
                ->addColumn('waiter', fn($booking) => $booking->waiter ? $booking->waiter->name : 'N/A')
                ->addColumn('price', fn($booking) => 'KES ' . number_format($booking->price, 2))
                ->addColumn('status', fn($booking) => '<span class="label ' . $booking->status_badge_class . '">' . ucfirst($booking->booking_status) . '</span>')
                ->addColumn('action', fn($booking) => '<a href="/bookings/' . $booking->id . '" class="btn btn-xs btn-info">View</a>')
                ->rawColumns(['status', 'action'])
                ->make(true);
        } catch (\Exception $e) {
            Log::error('Error in getTodaysBookings: ' . $e->getMessage(), ['stack' => $e->getTraceAsString()]);
            return response()->json(['error' => 'Server error occurred. Check logs for details.'], 500);
        }
    }

    public function getCalendarBookings(Request $request)
    {
        try {
            Log::info('Fetching calendar bookings', ['location_id' => $request->input('location_id')]);

            $query = Booking::with(['customer', 'guestCheckin'])
                ->whereBetween('booking_start', [$request->start, $request->end]);

            if ($request->has('location_id') && !empty($request->location_id)) {
                $query->where('location_id', $request->location_id);
            }

            $bookings = $query->get()->map(function ($booking) {
                return [
                    'id' => $booking->id,
                    'title' => $booking->guest_name,
                    'start' => $booking->booking_start->toDateTimeString(),
                    'end' => $booking->booking_end->toDateTimeString(),
                    'customer_name' => $booking->guest_name,
                    'room_number' => $booking->room_number,
                    'price' => 'KES ' . number_format($booking->price, 2),
                    'booking_type' => $booking->guest_checkin_id ? 'online' : 'front_desk',
                    'url' => $booking->guest_checkin_id ? null : '/bookings/' . $booking->id,
                    'className' => $booking->status_badge_class
                ];
            });

            return response()->json($bookings);
        } catch (\Exception $e) {
            Log::error('Error in getCalendarBookings: ' . $e->getMessage(), ['stack' => $e->getTraceAsString()]);
            return response()->json(['error' => 'Server error occurred. Check logs for details.'], 500);
        }
    }

    /**
     * Get guest check-ins for DataTables
     */
  public function getGuestCheckins(Request $request)
    {
        try {
            Log::info('Fetching guest check-ins', ['location_id' => $request->input('location_id')]);

            $query = GuestCheckin::with(['booking'])
                ->latest();

            if ($request->has('location_id') && !empty($request->location_id)) {
                $query->whereHas('booking', fn($q) => $q->where('location_id', $request->location_id));
            }

            return DataTables::of($query)
                ->addColumn('name', fn($checkin) => $checkin->surname . ' ' . $checkin->name)
                ->addColumn('email', fn($checkin) => $checkin->email ?? 'N/A')
                ->addColumn('phone_number', fn($checkin) => $checkin->phone ?? 'N/A')
                ->addColumn('gender', fn($checkin) => $checkin->gender ?? 'N/A')
                ->addColumn('room_slug', fn($checkin) => $checkin->booking ? $checkin->booking->room_type : 'N/A')
                ->addColumn('check_in', fn($checkin) => $checkin->booking ? $checkin->booking->booking_start->format('Y-m-d H:i') : 'N/A')
                ->addColumn('check_out', fn($checkin) => $checkin->booking ? $checkin->booking->booking_end->format('Y-m-d H:i') : 'N/A')
                ->addColumn('number_of_days', fn($checkin) => $checkin->booking ? $checkin->booking->total_nights : 'N/A')
                ->addColumn('adults', fn($checkin) => $checkin->booking ? $checkin->booking->adults : 'N/A')
                ->addColumn('rooms', fn($checkin) => $checkin->booking ? $checkin->booking->rooms : 'N/A')
                ->addColumn('is_double_occupancy', fn($checkin) => $checkin->booking ? ($checkin->booking->is_double_occupancy ? 'Double' : 'Single') : 'N/A')
                ->addColumn('price_per_room', fn($checkin) => $checkin->booking ? 'KES ' . number_format($checkin->booking->price_per_room, 2) : 'N/A')
                ->addColumn('total_price', fn($checkin) => $checkin->booking ? 'KES ' . number_format($checkin->booking->price, 2) : 'N/A')
                ->addColumn('created_at', fn($checkin) => $checkin->created_at->format('Y-m-d H:i'))
                ->addColumn('action', fn($checkin) => '<a href="/bookings/guest-checkins/' . $checkin->id . '" class="btn btn-xs btn-info">View</a>')
                ->rawColumns(['action'])
                ->make(true);
        } catch (\Exception $e) {
            Log::error('Error in getGuestCheckins: ' . $e->getMessage(), ['stack' => $e->getTraceAsString()]);
            return response()->json(['error' => 'Server error occurred. Check logs for details.'], 500);
        }
    }
    /**
     * Show guest check-in details
     */
    public function showGuestCheckin($id)
    {
        if (request()->ajax()) {
            $business_id = request()->session()->get('user.business_id');

            if (!class_exists('App\GuestCheckin')) {
                return response()->json(['error' => 'GuestCheckin model not found'], 404);
            }

            $guestCheckin = GuestCheckin::where('business_id', $business_id)
                ->where('id', $id)
                ->first();

            if (!$guestCheckin) {
                return response()->json(['error' => 'Guest check-in not found'], 404);
            }

            return response()->json([
                'id' => $guestCheckin->id,
                'full_name' => ($guestCheckin->surname ?? '') . ' ' . ($guestCheckin->name ?? ''),
                'surname' => $guestCheckin->surname ?? '',
                'name' => $guestCheckin->name ?? '',
                'email' => $guestCheckin->email ?? '',
                'phone' => $guestCheckin->phone ?? '',
                'gender' => $guestCheckin->gender ?? '',
                'nationality' => $guestCheckin->nationality ?? '',
                'id_type' => $guestCheckin->id_type ?? '',
                'id_number' => $guestCheckin->id_number ?? '',
                'passport_no' => $guestCheckin->passport_no ?? '',
                'stay_purpose' => $guestCheckin->stay_purpose ?? '',
                'payment_method' => $guestCheckin->payment_method ?? '',
                'company' => $guestCheckin->company ?? '',
                'remarks' => $guestCheckin->remarks ?? '',
                'staff_acknowledged' => $guestCheckin->staff_acknowledged ?? false,
                'guest_acknowledged' => $guestCheckin->guest_acknowledged ?? false,
                'created_at' => $guestCheckin->created_at ? $guestCheckin->created_at->format('Y-m-d H:i:s') : '',
                'booking_status' => 'no_booking',
                'has_bookings' => false
            ]);
        }
    }

    /**
     * Convert OnlineBooking to regular Booking
     */
    public function convertOnlineBookingToBooking($onlineBookingId)
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            if (!class_exists('App\OnlineBooking')) {
                return response()->json([
                    'success' => false,
                    'message' => 'OnlineBooking model not found.'
                ]);
            }

            $onlineBooking = OnlineBooking::findOrFail($onlineBookingId);
            $business_id = request()->session()->get('user.business_id');
            $user_id = request()->session()->get('user.id');

            // Create or find customer contact
            $customer = $this->createCustomerFromOnlineBooking($onlineBooking, $business_id);

            // Convert room_slug to room_number
            $roomNumber = $this->extractRoomNumberFromSlug($onlineBooking->room_slug);

            // Check room availability
            $booking_start = \Carbon\Carbon::parse($onlineBooking->check_in)->startOfDay();
            $booking_end = \Carbon\Carbon::parse($onlineBooking->check_out)->endOfDay();

            $existingBooking = Booking::where('business_id', $business_id)
                ->where('room_number', $roomNumber)
                ->where(function($query) use ($booking_start, $booking_end) {
                    $query->whereBetween('booking_start', [$booking_start, $booking_end])
                        ->orWhereBetween('booking_end', [$booking_start, $booking_end])
                        ->orWhere(function($q) use ($booking_start, $booking_end) {
                            $q->where('booking_start', '<=', $booking_start)
                                ->where('booking_end', '>=', $booking_end);
                        });
                })
                ->where('booking_status', '!=', 'cancelled')
                ->first();

            if ($existingBooking) {
                return response()->json([
                    'success' => false,
                    'message' => 'Room is not available for the selected dates.'
                ]);
            }

            // Create regular booking
            $booking = Booking::create([
                'business_id' => $business_id,
                'location_id' => 1, // Default location
                'customer_id' => $customer->id,
                'booking_start' => $booking_start,
                'booking_end' => $booking_end,
                'created_by' => $user_id,
                'booking_status' => 'booked',
                'room_number' => $roomNumber,
                'price' => $onlineBooking->total_price,
                'adults' => $onlineBooking->adults,
                'rooms' => $onlineBooking->rooms,
                'is_double_occupancy' => $onlineBooking->is_double_occupancy,
                'number_of_days' => $onlineBooking->number_of_days,
                'price_per_room' => $onlineBooking->price_per_room,
                'booking_note' => 'Converted from online booking #' . $onlineBooking->id
            ]);

            // Mark online booking as converted
            $onlineBooking->update([
                'converted_booking_id' => $booking->id,
                'status' => 'converted'
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Online booking converted successfully.',
                'booking_id' => $booking->id
            ]);

        } catch (\Exception $e) {
            \Log::error("Error converting online booking: " . $e->getMessage());
            return response()->json([
                'success' => false,
                'message' => 'Error converting booking: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * Create customer contact from online booking
     */
    private function createCustomerFromOnlineBooking($onlineBooking, $business_id)
    {
        // Check if customer already exists by email or phone
        $existingCustomer = Contact::where('business_id', $business_id)
            ->where(function($query) use ($onlineBooking) {
                if ($onlineBooking->email) {
                    $query->where('email', $onlineBooking->email);
                }
                if ($onlineBooking->phone_number) {
                    $query->orWhere('mobile', $onlineBooking->phone_number);
                }
            })
            ->first();

        if ($existingCustomer) {
            return $existingCustomer;
        }

        // Create a new customer using ContactUtil
        $contactUtil = new ContactUtil();

        $contactData = [
            'business_id' => $business_id,
            'type' => 'customer',
            'name' => $onlineBooking->name,
            'email' => $onlineBooking->email,
            'mobile' => $onlineBooking->phone_number,
            'contact_status' => 'active',
            'created_by' => auth()->id() ?? 1
        ];

        $result = $contactUtil->createNewContact($contactData);

        return $result['data'];
    }

    /**
     * Extract room number from room slug
     */
    private function extractRoomNumberFromSlug($roomSlug)
    {
        // Map room slugs to room numbers based on your room definitions
        $roomMappings = [
            'executive-rooms' => 210, // Default to first executive room
            'deluxe-rooms' => 209,    // Default to first deluxe room
            'double-standard' => 101, // Default to first double standard
            'single' => 105,          // Default to first single
        ];

        // If direct mapping exists
        if (isset($roomMappings[$roomSlug])) {
            return $roomMappings[$roomSlug];
        }

        // Try to extract number from slug if it contains room number
        if (preg_match('/(\d+)/', $roomSlug, $matches)) {
            return (int)$matches[1];
        }

        // Default fallback
        return 101;
    }

    /**
     * Auto-process pending online bookings
     */
    public function processOnlineBookings()
    {
        if (!auth()->user()->can('crud_all_bookings') && !auth()->user()->can('crud_own_bookings')) {
            abort(403, 'Unauthorized action.');
        }

        try {
            if (!class_exists('App\OnlineBooking')) {
                return response()->json([
                    'success' => false,
                    'message' => 'OnlineBooking model not found.'
                ]);
            }

            // Get unprocessed online bookings
            $onlineBookings = OnlineBooking::whereNull('converted_booking_id')
                ->where('status', '!=', 'converted')
                ->get();

            $convertedCount = 0;
            $errors = [];

            foreach ($onlineBookings as $onlineBooking) {
                try {
                    $response = $this->convertOnlineBookingToBooking($onlineBooking->id);
                    $responseData = $response->getData(true);

                    if ($responseData['success']) {
                        $convertedCount++;
                    } else {
                        $errors[] = "Booking #{$onlineBooking->id}: " . $responseData['message'];
                    }

                } catch (\Exception $e) {
                    $errors[] = "Booking #{$onlineBooking->id}: " . $e->getMessage();
                    \Log::error("Failed to convert online booking {$onlineBooking->id}: " . $e->getMessage());
                    continue;
                }
            }

            $message = "Converted {$convertedCount} online bookings successfully.";
            if (!empty($errors)) {
                $message .= " Errors: " . implode(', ', array_slice($errors, 0, 3));
                if (count($errors) > 3) {
                    $message .= "... and " . (count($errors) - 3) . " more.";
                }
            }

            return response()->json([
                'success' => true,
                'message' => $message,
                'converted_count' => $convertedCount,
                'error_count' => count($errors)
            ]);

        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Error processing online bookings: ' . $e->getMessage()
            ]);
        }
    }
}