<?php


namespace App\Listeners;

use App\Events\UserLoggedIn;
use Illuminate\Auth\Events\Login;
use App\Services\Models\CartService;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Events\Authenticated;

class MergeGuestCart
{
    public function handle(Registered|UserLoggedIn $event): void
    {
        $service = app(CartService::class);
        $guestCart = $service->getCart();    // this is the old guest cart
        // delete any old active user cart so we can keep only one
        $userCart  = \App\Models\Cart::where('user_id', $event->user->id)
            ->where('status', 'active')
            ->first();
        if ($userCart && $userCart->id !== $guestCart->id) {
            // move items over
            foreach ($guestCart->items as $item) {
                $service->add(productId: $item->product_id, quantity: $item->quantity);
            }
            // clear guest cart
            $guestCart->items()->delete();
        }
    }
}
