<?php

/*
|--------------------------------------------------------------------------
| OwnStore - Build your own online store
| Author: TakfeDev (MKJUEL)
| All Rights Reserved
|--------------------------------------------------------------------------
*/

namespace App\Http\Controllers\Buyer;

use App\Http\Controllers\Controller;
use App\Models\Product;
use Illuminate\Http\Request;
use Inertia\Inertia;

class FavoriteController extends Controller
{
    public function index()
    {
        // Fetch user's favorite products
        $favorites = auth()->user()->favorites()
            ->with(['images', 'category', 'seller'])
            ->withAvg('reviews', 'rating')
            ->latest('favorites.created_at')
            ->paginate(12);

        return Inertia::render('Dashboard/Buyer/Favorites', [
            'favorites' => $favorites
        ]);
    }

    public function toggle(Product $product)
    {
        // ---  Cast to integer to prevent strict type mismatch ---
        if ((int) auth()->id() === (int) $product->seller_id) {
            return back()->withErrors(['error' => 'You cannot favorite your own product.']);
        }

        // Attach or detach the product ID to the user's favorites
        auth()->user()->favorites()->toggle($product->id);

        return back();
    }
}