<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Services\BookingService;
use App\Traits\DeleteModelTrait;
use App\Traits\FlashMessageTrait;
use App\Models\Booking;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AdminBookingController extends Controller
{
    use DeleteModelTrait, FlashMessageTrait;
    
    protected $bookingService;

    public function __construct(BookingService $bookingService)
    {
        $this->bookingService = $bookingService;
    }

    /**
     * Display a listing of bookings
     */
    public function index(Request $request)
    {
        try {
            $perPage = 5;
            $filters = $request->only(['status', 'property_id', 'tenant_id', 'landlord_id']);
            $bookings = $this->bookingService->getAllBookings($filters + ['per_page' => $perPage]);
            
            // Calculate serial numbers and format data
            $bookings->getCollection()->transform(function ($booking, $index) use ($bookings) {
                $booking->sn = ($bookings->currentPage() - 1) * $bookings->perPage() + $index + 1;
                $booking->property_title = $booking->property->title ?? 'N/A';
                $booking->tenant_name = $booking->tenant->name ?? 'N/A';
                $booking->landlord_name = $booking->landlord->name ?? 'N/A';
                $booking->status_text = $booking->status_text;
                return $booking;
            });

            return Inertia::render('Admin/Bookings/Booking', [
                'bookings' => $bookings->items(),
                'pagination' => [
                    'current_page' => $bookings->currentPage(),
                    'last_page' => $bookings->lastPage(),
                    'per_page' => $bookings->perPage(),
                    'total' => $bookings->total(),
                    'from' => $bookings->firstItem(),
                    'to' => $bookings->lastItem(),
                    'links' => $bookings->linkCollection()->toArray(),
                ],
                'filters' => $filters
            ]);
        } catch (\Exception $e) {
            return $this->error('Failed to load bookings: ' . $e->getMessage());
        }
    }

    /**
     * Show the form for viewing booking details
     */
    public function show($id)
    {
        try {
            $booking = $this->bookingService->getBookingById($id);
            
            if (!$booking) {
                return response()->json(['error' => 'Booking not found'], 404);
            }

            return response()->json($booking);
        } catch (\Exception $e) {
            return response()->json(['error' => $e->getMessage()], 500);
        }
    }

    /**
     * Update booking status
     */
    public function updateStatus(Request $request, $id)
    {
        try {
            $request->validate([
                'status' => 'required|in:1,2,3,4,5'
            ]);

            $booking = Booking::findOrFail($id);
            $booking->update(['status' => $request->status]);
            
            return $this->success('Booking status updated successfully');
        } catch (\Exception $e) {
            return $this->error('Failed to update booking status: ' . $e->getMessage());
        }
    }

    /**
     * Remove the specified booking
     */
    public function destroy($id)
    {
        try {
            $booking = $this->bookingService->getBookingById($id);

            if (!$booking) {
                return $this->error('Booking not found');
            }

            // Use the trait for consistent deletion handling
            return $this->deleteModel($id, new Booking());
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }
}
