<?php

namespace App\Http\Controllers;

use App\Models\Ride;
use App\Http\Requests\RideRequest;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;

class RideController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): View
    {
        $query = Ride::query();

        // Search functionality
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function ($q) use ($search) {
                $q->where('name', 'ILIKE', "%{$search}%")
                  ->orWhere('description', 'ILIKE', "%{$search}%");
            });
        }

        // Filter by status
        if ($request->filled('status')) {
            $query->where('is_active', $request->get('status') === 'active');
        }

        $rides = $query->latest()->paginate(15)->withQueryString();

        return view('rides.index', compact('rides'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create(): View
    {
        return view('rides.create');
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(RideRequest $request): RedirectResponse
    {
        $ride = Ride::create($request->validated());

        return redirect()
            ->route('rides.show', $ride)
            ->with('success', 'Ride created successfully!');
    }

    /**
     * Display the specified resource.
     */
    public function show(Ride $ride): View
    {
        return view('rides.show', compact('ride'));
    }

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(Ride $ride): View
    {
        return view('rides.edit', compact('ride'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(RideRequest $request, Ride $ride): RedirectResponse
    {
        $ride->update($request->validated());

        return redirect()
            ->route('rides.show', $ride)
            ->with('success', 'Ride updated successfully!');
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Ride $ride): RedirectResponse
    {
        $ride->delete();

        return redirect()
            ->route('rides.index')
            ->with('success', 'Ride deleted successfully!');
    }
}