<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Ride;
use App\Http\Requests\RideRequest;
use App\Http\Resources\RideResource;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class RideController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request): JsonResponse
    {
        $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);

        return response()->json([
            'data' => RideResource::collection($rides),
            'meta' => [
                'current_page' => $rides->currentPage(),
                'last_page' => $rides->lastPage(),
                'per_page' => $rides->perPage(),
                'total' => $rides->total(),
            ]
        ]);
    }

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

        return response()->json([
            'message' => 'Ride created successfully',
            'data' => new RideResource($ride)
        ], 201);
    }

    /**
     * Display the specified resource.
     */
    public function show(Ride $ride): JsonResponse
    {
        return response()->json([
            'data' => new RideResource($ride)
        ]);
    }

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

        return response()->json([
            'message' => 'Ride updated successfully',
            'data' => new RideResource($ride)
        ]);
    }

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

        return response()->json([
            'message' => 'Ride deleted successfully'
        ]);
    }
}