<?php

namespace common\logic\Subscription\Subscription\Repository;

use common\logic\AbstractRepository;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\Subscription\Subscription\Model\Subscription;
use common\logic\Subscription\Subscription\Service\SubscriptionSolver;
use common\logic\User\User\Model\User;

class SubscriptionRepository extends AbstractRepository
{
    protected SubscriptionRepositoryQuery $query;
    protected SubscriptionSolver $subscriptionSolver;

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

    public function getDefaultOptionsSearch(): array
    {
        return [
            'with' => ['producer'],
            'join_with' => ['user', 'productSubscription', 'productSubscription.product', 'pointSale'],
            'orderby' => 'user.name ASC',
            'attribute_id_producer' => 'subscription.id_producer'
        ];
    }

    public function findOneSubscriptionById(int $id): ?Subscription
    {
        return Subscription::searchOne(['id' => $id]);
    }

    public function findSubscriptions()
    {
        return Subscription::searchAll();
    }

    /**
     * Retourne les abonnements pour une date donnée.
     */
    // searchByDate, getByDate
    public function findSubscriptionsByDate(string $date)
    {
        $date = date('Y-m-d', strtotime($date));
        $subscriptionArray = $this->findSubscriptions();
        $subscriptionReturnArray = [];

        foreach ($subscriptionArray as $subscription) {
            if ($date >= $subscription->date_begin &&
                (!$subscription->date_end || $date <= $subscription->date_end)
                && $this->subscriptionSolver->isSubscriptionMatchWith($subscription, $date)) {
                $subscriptionReturnArray[] = $subscription;
            }
        }

        return $subscriptionReturnArray;
    }

    public function countSubscriptionsByUser(User $user, Producer $producer)
    {
        return Subscription::find()
            ->where([
                'subscription.id_user' => $user->id,
                'subscription.id_producer' => $producer->id,
            ])->count();
    }
}