<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

use App\Models\Event; // Import Event model
use App\Models\Booking; // Import Booking model
use Illuminate\Support\Facades\Auth;
use Inertia\Inertia;

class UserTicketController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $user = Auth::user();

        $eventBookings = Booking::where('user_id', $user->id)
            ->where('bookable_type', Event::class)
            ->with('bookable') // Eager load the polymorphic relationship (Event model)
            ->latest()
            ->paginate(10);

        $eventBookings->getCollection()->transform(function ($booking) {
            return [
                'id' => $booking->id,
                'event_name' => $booking->bookable->title, // Access title from the eager-loaded Event model
                'booking_date' => $booking->booking_date,
                'quantity' => $booking->quantity,
                'total_price' => $booking->price,
                'status' => $booking->status,
            ];
        });

        return Inertia::render('User/Tickets/Index', [
            'eventBookings' => $eventBookings,
        ]);
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     */
    public function show(Booking $booking)
    {
        $this->authorize('view', $booking);

        // Ensure the booking is for an Event
        if ($booking->bookable_type !== Event::class) {
            abort(404, 'Booking not found or is not an event booking.');
        }

        $booking->load('bookable'); // Eager load the polymorphic relationship (Event model)

        return response()->json([
            'booking' => [
                'id' => $booking->id,
                'event_name' => $booking->bookable->title,
                'booking_date' => $booking->booking_date,
                'booking_time' => $booking->booking_time,
                'status' => $booking->status,
                'notes' => $booking->notes,
                'event' => $booking->bookable,
            ]
        ]);
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(string $id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(string $id)
    {
        //
    }
}
