<?php

namespace App\Http\Controllers\Customer;

use App\Http\Controllers\Controller;
use App\Models\CustomerFavorite;
use App\Models\Product;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class FavoriteController extends Controller
{
    public function index(Request $request): View
    {
        return view('customer.favorites.index', [
            'favorites' => $request->user('customer')
                ->favorites()
                ->with(['product.category', 'product.images'])
                ->latest()
                ->get(),
        ]);
    }

    public function toggle(Request $request, Product $product): RedirectResponse
    {
        abort_if(! $product->is_active || ! $product->category?->is_active, 404);

        $favorite = $request->user('customer')
            ->favorites()
            ->where('product_id', $product->id)
            ->first();

        if ($favorite) {
            $favorite->delete();

            return back()->with('status', 'Product removed from favorites.');
        }

        $request->user('customer')->favorites()->create(['product_id' => $product->id]);

        return back()->with('status', 'Product added to favorites.');
    }

    public function destroy(Request $request, CustomerFavorite $favorite): RedirectResponse
    {
        abort_unless($favorite->customer_id === $request->user('customer')->id, 403);

        $favorite->delete();

        return back()->with('status', 'Favorite removed.');
    }
}
