<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ExtraService;

class ExtraServiceController extends Controller
{
    /**
     * Display a listing of all extra services
     */
    public function index()
    {
        $extras = ExtraService::with('travelAgent')->get();
        return response()->json($extras);
    }

    /**
     * Store a newly created extra service
     */
    public function store(Request $request)
    {
        $request->validate([
            'travel_agent_id' => 'required|exists:travel_agents,id',
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0'
        ]);

        $extra = ExtraService::create([
            'travel_agent_id' => $request->travel_agent_id,
            'name' => $request->name,
            'price' => $request->price
        ]);

        return response()->json($extra, 201);
    }

    /**
     * Display the specified extra service
     */
    public function show(string $id)
    {
        $extra = ExtraService::with('travelAgent')->findOrFail($id);
        return response()->json($extra);
    }

    /**
     * Update the specified extra service
     */
    public function update(Request $request, string $id)
    {
        $extra = ExtraService::findOrFail($id);

        $request->validate([
            'travel_agent_id' => 'sometimes|exists:travel_agents,id',
            'name' => 'sometimes|string|max:255',
            'price' => 'sometimes|numeric|min:0'
        ]);

        $extra->update($request->only('travel_agent_id', 'name', 'price'));

        return response()->json($extra);
    }

    /**
     * Remove the specified extra service
     */
    public function destroy(string $id)
    {
        $extra = ExtraService::findOrFail($id);
        $extra->delete();

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

    /**
     * POS Search API for extra services
     */
    public function search(Request $request)
    {
        $request->validate([
            'query' => 'required|string'
        ]);

        $extras = ExtraService::where('name', 'like', '%' . $request->query . '%')->get();

        return response()->json($extras);
    }
}
