<?php

namespace App\Http\Controllers\Panel;

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

class WishController extends Controller
{
    public function index()
    {
        $wishes = UserWish::with('product')
            ->where('user_id', Auth::id())
            ->latest()
            ->paginate(12);

        return view('panel.wishes.index', compact('wishes'));
    }

    public function toggle(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);

        $existing = UserWish::where('user_id', Auth::id())
            ->where('product_id', $request->product_id)
            ->first();

        if ($existing) {
            $existing->delete();
            $status = 'removed';
        } else {
            UserWish::create([
                'user_id'    => Auth::id(),
                'product_id' => $request->product_id,
            ]);
            $status = 'added';
        }

        $count = UserWish::where('user_id', Auth::id())->count();

        return response()->json([
            'success' => true,
            'status'  => $status,
            'count'   => $count,
        ]);
    }

    public function destroy(Product $product)
    {
        UserWish::where('user_id', Auth::id())
            ->where('product_id', $product->id)
            ->delete();

        return back()->with('success', 'محصول از علاقه‌مندی‌ها حذف شد.');
    }
}
