<?php

namespace domain\Subscription\Subscription;

use domain\_\AbstractManager;
use domain\Product\Product\Product;
use domain\Subscription\ProductSubscription\ProductSubscription;

class SubscriptionManager extends AbstractManager
{
    protected SubscriptionRepository $subscriptionRepository;
    protected SubscriptionSolver $subscriptionSolver;

    public function loadDependencies(): void
    {
        $this->subscriptionRepository = $this->loadService(SubscriptionRepository::class);
        $this->subscriptionSolver = $this->loadService(SubscriptionSolver::class);
    }

    public function deleteProductInSubscriptionsIfUnavailableForSubscriptions(Product $product): void
    {
        $subscriptionsWithProductDeletedArray = [];
        if(!$product->is_available_for_subscriptions) {
            $subscriptionsArray = $this->subscriptionRepository->findSubscriptions();

            foreach($subscriptionsArray as $subscription) {
                if($this->deleteProductUnavailableInSubscriptions($subscription, $product)) {
                    $subscriptionsWithProductDeletedArray[] = $subscription;
                }
            }
        }

        if(count($subscriptionsWithProductDeletedArray)) {
            \Yii::$app->session->addFlash('warning', 'Le produit a été supprimé des abonnements suivants : '.$this->subscriptionSolver->getSubscriptionsListAsHtml($subscriptionsWithProductDeletedArray));
        }
    }

    public function deleteProductUnavailableInSubscriptions(Subscription $subscription, Product $product): bool
    {
        if(!$product->is_available_for_subscriptions
            && $this->subscriptionSolver->containProduct($subscription, $product)) {

            foreach($subscription->productSubscription as $productSubscription) {
                if($productSubscription->id_product == $product->id) {

                    // Si le produit n'est pas le seul dans l'abonnement
                    if(count($subscription->productSubscription) > 1) {
                        $productSubscription->delete();
                    }
                }
            }

            return true;
        }

        return false;
    }
}