<?php

namespace App\Http\Controllers\Member;

use App\Http\Controllers\Controller;
use App\Models\Favorite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class FavoriteController extends Controller
{
    public function index()
    {
        $favorites = Auth::user()->favorites()->latest()->paginate(12);
        return view('member.favorites.index', compact('favorites'));
    }

    public function store(Request $request)
    {
        $validated = $request->validate([
            'product_slug' => ['required', 'string'],
            'product_name' => ['required', 'string'],
            'product_image' => ['nullable', 'string'],
            'product_price' => ['nullable', 'numeric'],
        ]);

        $favorite = Auth::user()->favorites()->where('product_slug', $validated['product_slug'])->first();

        if ($favorite) {
            return back()->with('info', 'Bu ürün zaten favorilerinizde.');
        }

        $validated['user_id'] = Auth::id();
        Favorite::create($validated);

        return back()->with('success', 'Ürün favorilere eklendi.');
    }

    public function destroy(Favorite $favorite)
    {
        if ($favorite->user_id !== Auth::id()) {
            abort(403);
        }

        $favorite->delete();

        return back()->with('success', 'Ürün favorilerden kaldırıldı.');
    }
}
