<?php

namespace common\logic\Producer\Producer\Service;

use common\components\PageSizer;
use common\helpers\GlobalParam;
use common\logic\AbstractService;
use common\logic\Producer\Producer\Model\Producer;
use common\logic\SolverInterface;
use common\logic\User\User\Model\User;
use yii\helpers\Html;

class ProducerSolver extends AbstractService implements SolverInterface
{
    /**
     * Retourne true si le compte est un compte de démo.
     */
    public function isDemo(Producer $producer): bool
    {
        if (strpos($producer->name, 'Démo') !== false) {
            return true;
        }

        return false;
    }

    public function getFullAddressAsHtml(Producer $producer): string
    {
        $address = '<div class="name">'.$producer->name . '</div>';

        if (strlen($producer->address)) {
            $address .= $producer->address . '<br>';
        }

        if (strlen($producer->postcode) || strlen($producer->city)) {
            $address .= $producer->postcode . ' ' . $producer->city;
        }

        return $address;
    }

    public function getHtmlLogo(Producer $producer)
    {
        $html = '';

        if (strlen($producer->logo)) {
            $html = '<img src="' . $this->getUrlLogo($producer) . '" class="producer-logo" />';
        }

        return $html;
    }

    public function getUrlLogo(Producer $producer): string
    {
        return \Yii::$app->urlManagerProducer->getHostInfo() . '/' . \Yii::$app->urlManagerProducer->baseUrl . '/uploads/' . $producer->logo;
    }

    /**
     * @deprecated Déplacé dans MailerService
     */
    public function getEmailOpendistrib(Producer $producer): string
    {
        return $producer->slug . '@opendistrib.net';
    }

    public function getMainContact(Producer $producer): ?User
    {
        if ($producer->contact) {
            foreach ($producer->contact as $contact) {
                if ($contact->is_main_contact) {
                    return $contact;
                }
            }
        }

        return null;
    }

    public function getMainContactEmail(Producer $producer): ?string
    {
        $contact = $this->getMainContact($producer);

        if ($contact) {
            return $contact->email;
        }

        return null;
    }

    public function isUpToDateWithOpendistribVersion(Producer $producer): bool
    {
        return $producer->latest_version_opendistrib == GlobalParam::getOpendistribVersion();
    }

    public function isBillingTypeClassic(Producer $producer): bool
    {
        return $producer->option_billing_type == Producer::BILLING_TYPE_CLASSIC;
    }

    public function isBillingTypeFreePrice(Producer $producer): bool
    {
        return $producer->option_billing_type == Producer::BILLING_TYPE_FREE_PRICE;
    }

    /**
     * Retourne le montant de l'abonnement à prix libre définit par
     * le producteur.
     */
    public function getFreePrice(Producer $producer, bool $format = true)
    {
        if (!is_null($producer->free_price)) {
            if ($format) {
                return number_format($producer->free_price, 2, ',', false) . ' €';
            } else {
                return $producer->free_price;
            }
        }
    }

    public function getSpecificDelays(Producer $producer): array
    {
        $array = [];
        $daysArray = [
            'monday',
            'tuesday',
            'wednesday',
            'thursday',
            'friday',
            'saturday',
            'sunday'
        ];

        foreach ($daysArray as $day) {
            $fieldDelay = 'order_delay_' . $day;
            $fieldDeadline = 'order_deadline_' . $day;

            $delay = $producer->order_delay;
            $deadline = $producer->order_deadline;
            if ($producer->$fieldDelay) {
                $delay = $producer->$fieldDelay;
            }
            if ($producer->$fieldDeadline) {
                $deadline = $producer->$fieldDeadline;
            }

            $array[$day] = [
                'order_delay' => $delay,
                'order_deadline' => $deadline,
            ];
        }

        return $array;
    }

    public function hasSpecificDelays(Producer $producer): bool
    {
        $daysArray = [
            'monday',
            'tuesday',
            'wednesday',
            'thursday',
            'friday',
            'saturday',
            'sunday'
        ];

        foreach ($daysArray as $day) {
            $fieldDelay = 'order_delay_' . $day;
            $fieldDeadline = 'order_deadline_' . $day;

            if ($producer->$fieldDelay || $producer->$fieldDeadline) {
                return true;
            }
        }

        return false;
    }

    public function getFilenamePrivateKeyApiStripe(Producer $producer): string
    {
        return '../../common/config/stripe/api-' . $producer->id . '.key';
    }

    public function getFilenamePrivateKeyEndpointStripe(Producer $producer): string
    {
        return '../../common/config/stripe/endpoint-' . $producer->id . '.key';
    }

    /**
     * Retourne la clé secrète d'API de Stripe.
     */
    public function getPrivateKeyStripe(string $filename): string
    {
        if (file_exists($filename)) {
            $handle = fopen($filename, "r");
            $filesize = filesize($filename);
            if ($handle && $filesize) {
                $secretKey = fread($handle, $filesize);
                fclose($handle);
                return $secretKey;
            }
        }

        return '';
    }

    public function getPrivateKeyApiStripe(Producer $producer): string
    {
        return $this->getPrivateKeyStripe($this->getFilenamePrivateKeyApiStripe($producer));
    }

    public function getPrivateKeyEndpointStripe(Producer $producer): string
    {
        return $this->getPrivateKeyStripe($this->getFilenamePrivateKeyEndpointStripe($producer));
    }

    public function isOnlinePaymentActive(Producer $producer): bool
    {
        return $producer->online_payment
            || ($producer->option_stripe_mode_test
                    && !\Yii::$app->user->isGuest
                    && \Yii::$app->user->identity->status > 10);
    }

    public function isOnlinePaymentActiveAndTypeOrder(Producer $producer): bool
    {
        return $this->isOnlinePaymentActive($producer)
            && $producer->option_online_payment_type == 'order';
    }

    public function isBillingFrequencyMonthly(Producer $producer): bool
    {
        return $producer->option_billing_frequency == Producer::BILLING_FREQUENCY_MONTHLY;
    }

    public function isBillingFrequencyQuarterly(Producer $producer): bool
    {
        return $producer->option_billing_frequency == Producer::BILLING_FREQUENCY_QUARTERLY;
    }

    public function isBillingFrequencyBiannual(Producer $producer): bool
    {
        return $producer->option_billing_frequency == Producer::BILLING_FREQUENCY_BIANNUAL;
    }

    public function getPointSaleWording(Producer $producer)
    {
        if($producer->option_point_sale_wording && strlen($producer->option_point_sale_wording)) {
            return Html::encode($producer->option_point_sale_wording);
        }

        return 'Points de vente';
    }

    public function getConfig(string $config, Producer $producer = null): ?string
    {
        if(!$producer) {
            $producer = $this->getProducerContext();
        }

        return $producer->$config;
    }
}