<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreBookingRequest;
use App\Models\Account;
use App\Models\Booking;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class AccountBookingController extends Controller
{
    public function index(Account $account): Response
    {
        $bookings = Booking::query()
            ->where('account_id', $account->id)
            ->orderByDesc('booked_at')
            ->get(['id', 'payment_id', 'amount_cents', 'type', 'description', 'booked_at', 'created_at']);

        return Inertia::render('Accounts/Bookings/Index', [
            'account' => $account->only(['id', 'reference', 'description']),
            'bookings' => $bookings,
        ]);
    }

    public function store(StoreBookingRequest $request, Account $account): RedirectResponse
    {
        $validated = $request->validated();

        Booking::query()->create([
            'account_id' => $account->id,
            'payment_id' => $validated['payment_id'] ?? null,
            'amount_cents' => (int) round(((float) $validated['amount']) * 100),
            'type' => $validated['type'],
            'description' => $validated['description'] ?? null,
            'booked_at' => $validated['booked_at'] ?? now(),
        ]);

        return back()->with('success', 'Booking created.');
    }

    public function destroy(Account $account, Booking $booking): RedirectResponse
    {
        if ($booking->account_id !== $account->id) {
            abort(404);
        }

        $booking->delete();

        return back()->with('success', 'Booking deleted.');
    }
}
