<?php

namespace App\Http\Controllers\Backend;

use App\Enums\BookingStatus;
use App\Http\Controllers\Controller;
use App\Models\Booking;
use Illuminate\Http\Request;

class BookingController extends Controller
{
    public function index(Request $request)
    {
        $perPage = $request->integer('perPage', 15);

        $status = $request->status;
        $search = $request->search;

        $bookings = Booking::with('space', 'space.location', 'user')
            ->latest()
            ->when($request->get('search'), fn($query, $value) => $query->where('booking_id', 'LIKE', '%' . $value . '%'))
            ->when($request->get('status'), fn($query, $value) => $query->where('status', $value))
            ->paginate($perPage)
            ->withQueryString();

        return view('backend.booking.index', [
            'bookings' => $bookings,
        ]);
    }

    public function show($bookingId)
    {
        // Get currency
        $currency = setting('currency_symbol');

        // Get booking details
        $booking = Booking::with('space', 'space.location', 'user')->where('booking_id', $bookingId)->firstOrFail();

        // Facilities list
        $facilities = collect($booking->facilities)->map(function ($facilityId) use ($booking, $currency) {
            $facility = $booking->space->facilities[$facilityId];

            return isset($facility) ? $facility['title'] . ' - ' . $currency . $facility['price'] : [];
        })->implode(',');

        return view('backend.booking.show', compact('booking', 'facilities'));
    }

    public function action(Request $request, $booking_id)
    {
        $request->validate([
            'status' => 'required',
            'payment_status' => 'required',
        ]);

        $booking = Booking::findOrFail($booking_id);
        $booking->status = $request->status;
        $booking->is_paid = $request->boolean('payment_status');
        $booking->save();

        if ($booking->status == BookingStatus::Cancelled) {
            $booking->space->increment('stock', $booking->stock);
        }

        notify()->success(__('Booking updated successfully!'));

        return back();
    }
}
