<?php

namespace common\logic\Subscription\Subscription\Service;

use common\logic\AbstractService;
use common\logic\SolverInterface;
use common\logic\Subscription\Subscription\Model\Subscription;
use common\logic\User\User\Service\UserSolver;

class SubscriptionSolver extends AbstractService implements SolverInterface
{
    protected UserSolver $userSolver;

    public function loadDependencies(): void
    {
        $this->userSolver = $this->loadService(UserSolver::class);
    }

    /**
     * Informe s'il existe une commande correspond à l'abonnement courant.
     */
    public function hasOrderAlreadyExist(Subscription $subscription, array $orderArray): bool
    {
        if (is_array($orderArray) && count($orderArray) > 0) {
            foreach ($orderArray as $order) {
                if ((($order->id_user > 0 && $order->id_user == $subscription->id_user) ||
                        (!$order->id_user && $order->username == $subscription->username)) &&
                    $order->id_point_sale == $subscription->id_point_sale) {
                    return true;
                }
            }
        }

        return false;
    }

    public function getUsername(Subscription $subscription): string
    {
        if ($subscription->user) {
            return $this->userSolver->getUsername($subscription->user);
        }

        return $subscription->username;
    }

    /**
     * Valide le fait qu'un abonnement est bien compatible avec une date donnée.
     */
    public function isSubscriptionMatchWith(Subscription $subscription, string $date): bool
    {
        $arrayDays = [
            1 => 'monday',
            2 => 'tuesday',
            3 => 'wednesday',
            4 => 'thursday',
            5 => 'friday',
            6 => 'saturday',
            7 => 'sunday'
        ];

        $nbDays = (strtotime($date) - strtotime($subscription->date_begin)) / (24 * 60 * 60);
        if (round($nbDays) % ($subscription->week_frequency * 7) < 7) {
            $numDay = date('N', strtotime($date));
            $day = $arrayDays[$numDay];
            if ($subscription->$day) {
                return true;
            }
        }

        return false;
    }
}