<?php

namespace CouponsPlus\App\Coupon;

use CouponsPlus\App\Offers\Abilities\Offers;
use CouponsPlus\Original\Collections\Collection;

#[\AllowDynamicProperties]
Class CouponOffersTracker
{
    protected $couponsWithAppliedOffers = [];
    protected Collection $offerIds;

    /**
     * Unfortunately a singletone again until we can refactor the code to use dependency injection properly.
     */
    public static function getInstance() : self
    {
        static $instance = null;

        if ($instance === null) {
            $instance = new self();
        }

        return $instance;
    }

    private function __construct()
    {
        $this->reset();
    }

    public function track(Coupon $coupon, Offers $offers)
    {
        $this->couponsWithAppliedOffers[] = $coupon->getClassic()->get_code($context = 'edit');
        $this->couponsWithAppliedOffers = array_unique($this->couponsWithAppliedOffers);

        $this->offerIds->concat($offers->getIds());
    }

    public function haveBeenApplied(Coupon $coupon) : bool
    {
        return in_array($coupon->getClassic()->get_code($context = 'edit'), $this->couponsWithAppliedOffers);  
    }

    public function reset()
    {
        $this->couponsWithAppliedOffers = [];
        $this->resetOfferIds();
    }

    public function resetOfferIds(): void
    {
        $this->offerIds = new Collection([]);
    }
}