<?php

namespace App\Http\Controllers\Admin\Affiliates;

use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\AddAffiliateRequest;
use App\Models\Product;
use App\Services\Admin\Affiliates\AffiliatesService;
use Illuminate\Http\Request;
use Inertia\Inertia;

class AffiliatesController extends Controller
{
    /**
     * delete product from affiliate list
     */
    public function products(Request $request, AffiliatesService $affiliatesService)
    {
        return Inertia::render('Admin/Affiliates/Products', [
            'products' => $affiliatesService->getProducts($request),
        ]);
    }

    /**
     * add product to affiliate list
     */
    public function add(AddAffiliateRequest $request, Product $product)
    {
        $product->affiliate()->updateOrCreate(['product_id' => $product->id], [
            'bronze_commission' => $request->bronze_commission,
            'silver_commission' => $request->silver_commission,
            'gold_commission' => $request->gold_commission,
        ]);

        /** Report Action */
        $this->report(__("messages.report_product_added_to_affiliate"), 'product', $product);

        return redirect()->back()->with('message', [$request->edit ? __('messages.product_affiliate_edited') : __('messages.product_added_to_affiliate')]);
    }

    /**
     * delete product from affiliate list
     */
    public function delete(Product $product)
    {
        $affiliates = $product->affiliate()->where('product_id', $product->id)->get();
        foreach ($affiliates as $affiliate) {
            $affiliate->delete();
        }

        /** Report Action */
        $this->report(__("messages.report_product_deleted_from_affiliate"), 'product', $product);

        return redirect()->back()->with('message', [__('messages.product_deleted_from_affiliate')]);
    }
}
