<?php

namespace App\Http\Controllers\API\Manager;

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

class AddonController extends Controller
{
    public function index(Request $request)
    {
        $addons = Addon::where('restaurant_id', $request->user()->restaurant->id)
            ->get();

        return response()->json(['success' => true, 'data' => $addons]);
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
        ]);

        $addon = Addon::create([
            'restaurant_id' => $request->user()->restaurant->id,
            'name' => $validated['name'],
            'price' => $validated['price'],
            'is_active' => true,
        ]);

        return response()->json(['success' => true, 'data' => $addon], 201);
    }

    public function update(Request $request, $id)
    {
        $addon = Addon::where('restaurant_id', $request->user()->restaurant->id)
            ->findOrFail($id);

        $validated = $request->validate([
            'name' => 'required|string|max:255',
            'price' => 'required|numeric|min:0',
        ]);

        $addon->update($validated);

        return response()->json(['success' => true, 'data' => $addon]);
    }

    public function toggle(Request $request, $id)
    {
        $addon = Addon::where('restaurant_id', $request->user()->restaurant->id)
            ->findOrFail($id);

        $addon->update(['is_active' => !$addon->is_active]);

        return response()->json(['success' => true, 'data' => $addon]);
    }

    public function destroy(Request $request, $id)
    {
        $addon = Addon::where('restaurant_id', $request->user()->restaurant->id)
            ->findOrFail($id);

        $addon->delete();

        return response()->json(['success' => true]);
    }
}
