<?php

namespace App\Http\Controllers\Customer;

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

class WatchlistController extends Controller
{
    public function index()
    {
        $watchlists = Watchlist::with('vehicle', 'auctionVehicle.auctionHouse')
            ->where('user_id', Auth::id())
            ->orderBy('created_at', 'desc')
            ->paginate(12);

        return view('customer.watchlist', compact('watchlists'));
    }

    public function toggle(Request $request)
    {
        $userId = Auth::id();
        $vehicleId = $request->input('vehicle_id');
        $auctionVehicleId = $request->input('auction_vehicle_id');

        $query = Watchlist::where('user_id', $userId);
        if ($vehicleId) {
            $query->where('vehicle_id', $vehicleId);
        }
        if ($auctionVehicleId) {
            $query->where('auction_vehicle_id', $auctionVehicleId);
        }

        $existing = $query->first();

        if ($existing) {
            $existing->delete();
            $added = false;
            $message = 'Vehicle removed from watchlist.';
        } else {
            Watchlist::create([
                'user_id' => $userId,
                'vehicle_id' => $vehicleId,
                'auction_vehicle_id' => $auctionVehicleId,
                'notify_on_status_change' => true,
            ]);
            $added = true;
            $message = 'Vehicle added to your watchlist.';
        }

        if ($request->wantsJson()) {
            return response()->json(['success' => true, 'added' => $added, 'message' => $message]);
        }

        return back()->with('success', $message);
    }
}
