<?php

namespace App\Http\Controllers;

use App\Repositories\Member\WishlistRepository;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Auth;

class WishController extends Controller
{
    protected $wishlistRepository;

    public function __construct(WishlistRepository $wishlistRepository)
    {
        $this->wishlistRepository = $wishlistRepository;
    }

    /**
     * Display the wishlist page
     */
    public function index(Request $request)
    {
        try {
            $wishlists = $this->wishlistRepository->getList($request);
            
            return view('account.wishlist', [
                'wishlists' => $wishlists,
                'user' => Auth::user()
            ]);
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to load wishlist: ' . $e->getMessage());
        }
    }

    /**
     * Add item to wishlist
     */
    public function store(Request $request): JsonResponse
    {
        $request->validate([
            'item_id' => 'required|exists:items,id'
        ]);

        try {
            $wishlist = $this->wishlistRepository->create([
                'item_id' => $request->item_id
            ]);

            return response()->json([
                'success' => true,
                'message' => 'Item added to wishlist successfully',
                'wishlist' => $wishlist
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to add item to wishlist: ' . $e->getMessage()
            ], 500);
        }
    }

    /**
     * Remove item from wishlist
     */
    public function destroy(Request $request, $id): JsonResponse
    {
        try {
            

            $this->wishlistRepository->delete($id);

            return response()->json([
                'success' => true,
                'message' => 'Item removed from wishlist successfully'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => 'Failed to remove item from wishlist: ' . $e->getMessage()
            ], 500);
        }
    }
}
