<?php

namespace App\Http\Controllers;

use App\Http\Requests\AddonRequest;
use App\Models\Product;
use App\Models\ProductAddon;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Cache;

class ProductAddonController extends Controller
{
    public function store(AddonRequest $request, Product $product): RedirectResponse
    {
        abort_if((int) $product->outlet_id !== (int) $request->user()->outlet_id, 403);
        $product->addons()->create($request->validated());
        Cache::forget("pos.catalog.{$request->user()->outlet_id}");

        return back()->with('success', 'Add-on ditambahkan.');
    }

    public function update(AddonRequest $request, ProductAddon $addon): RedirectResponse
    {
        abort_if((int) $addon->product->outlet_id !== (int) $request->user()->outlet_id, 403);
        $addon->update($request->validated());
        Cache::forget("pos.catalog.{$request->user()->outlet_id}");

        return back()->with('success', 'Add-on diperbarui.');
    }

    public function destroy(ProductAddon $addon): RedirectResponse
    {
        abort_if((int) $addon->product->outlet_id !== (int) auth()->user()->outlet_id, 403);
        Cache::forget("pos.catalog.".auth()->user()->outlet_id);
        $addon->delete();

        return back()->with('success', 'Add-on dihapus.');
    }
}
