<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\Booking;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Inertia\Inertia;

class BookingsController extends Controller
{
    public function index(Request $request)
    {
        $user   = $request->user();
        $filter = $request->get('filter', 'all');

        $query = Booking::where('user_id', $user->id)->orderByDesc('created_at');

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

        $instapayLink = DB::table('settings')->where('key', 'instapay_link')->value('value') ?? '';

        $bookings = $query->get()->map(fn($b) => [
            'id'             => $b->id,
            'reference'      => $b->reference,
            'facility_name'  => $b->facility_name,
            'facility_type'  => $b->facility_type,
            'name'           => $b->name,
            'date_start'     => $b->date_start?->format('Y-m-d'),
            'date_end'       => $b->date_end?->format('Y-m-d'),
            'time_start'     => $b->time_start,
            'time_end'       => $b->time_end,
            'persons_count'  => $b->persons_count,
            'status'         => $b->status,
            'payment_status' => $b->payment_status,
            'payment_method' => $b->payment_method,
            'total_amount'   => $b->total_amount,
            'rejection_note' => $b->rejection_note,
            'notes'          => $b->notes,
            'created_at'     => $b->created_at->format('Y-m-d'),
        ]);

        $clubLogoUrl = asset('images/logo.png');

        return Inertia::render('Portal/Bookings', [
            'bookings'     => $bookings,
            'filter'       => $filter,
            'instapayLink' => $instapayLink,
            'clubLogoUrl'  => $clubLogoUrl,
        ]);
    }
}
