<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\ServiceBooking;
use App\Models\TestDriveBooking;
use Illuminate\Http\Request;

class BookingController extends Controller
{
    public function index(Request $request)
    {
        $type = $request->get('type', 'service');

        $query = $type === 'service'
            ? ServiceBooking::with(['customer', 'vehicle', 'serviceType'])
            : TestDriveBooking::with(['customer', 'vehicle']);

        if ($request->filled('search')) {
            $search = $request->search;
            $query->whereHas('customer', function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        if ($request->filled('status') && $request->status !== 'all') {
            $query->where('status', $request->status);
        }

        $bookings = $query->latest('date')->paginate(10);
        $view = $type === 'service' ? 'admin.bookings.service_index' : 'admin.bookings.test_drive_index';

        return view($view, compact('bookings'));
    }

    public function show(Request $request, $id)
    {
        $booking = $this->resolveBooking($request, $id);
        $type = $this->resolveType($request, $booking);

        $view = $type === 'service' ? 'admin.bookings.service_show' : 'admin.bookings.test_drive_show';

        return view($view, compact('booking'));
    }

    public function update(Request $request, $id)
    {
        $booking = $this->resolveBooking($request, $id);
        $type = $this->resolveType($request, $booking);

        $validated = $request->validate([
            'status' => 'required|string|in:PENDING,CONFIRMED,COMPLETED,CANCELLED',
            'notes' => 'nullable|string|max:1000',
            'time_slot' => 'required|string|max:50',
        ]);

        $booking->update($validated);

        $label = $type === 'service' ? 'Service booking' : 'Test drive booking';

        return back()->with('success', "{$label} updated successfully.");
    }

    public function destroy(Request $request, $id)
    {
        $booking = $this->resolveBooking($request, $id);
        $type = $this->resolveType($request, $booking);

        $booking->delete();

        $label = $type === 'service' ? 'Service booking' : 'Test drive booking';

        return back()->with('success', "{$label} deleted successfully.");
    }

    /**
     * Resolve the booking model using the ?type= query parameter first,
     * falling back to searching both tables (legacy support).
     */
    private function resolveBooking(Request $request, $id)
    {
        $type = $request->query('type');

        if ($type === 'service') {
            return ServiceBooking::with(['customer', 'vehicle', 'serviceType'])->findOrFail($id);
        }

        if ($type === 'test_drive') {
            return TestDriveBooking::with(['customer', 'vehicle'])->findOrFail($id);
        }

        // Legacy fallback: try both tables (backwards compatible)
        $booking = ServiceBooking::with(['customer', 'vehicle', 'serviceType'])->find($id);
        if ($booking) {
            return $booking;
        }

        $booking = TestDriveBooking::with(['customer', 'vehicle'])->find($id);
        if ($booking) {
            return $booking;
        }

        abort(404, 'Booking not found.');
    }

    /**
     * Determine the type of the resolved booking.
     */
    private function resolveType(Request $request, $booking): string
    {
        if ($request->query('type')) {
            return $request->query('type');
        }

        return $booking instanceof ServiceBooking ? 'service' : 'test_drive';
    }
}
