<?php

namespace console\commands;

use common\helpers\MeanPayment;
use domain\Distribution\Distribution\Distribution;
use domain\Distribution\Distribution\DistributionModule;
use domain\Distribution\Distribution\ExportManager;
use domain\Order\Order\Order;
use domain\Order\Order\OrderModule;
use domain\Payment\PaymentModule;
use domain\Producer\Producer\Producer;
use domain\Producer\Producer\ProducerModule;
use domain\User\User\User;
use domain\User\User\UserModule;
use yii\console\Controller;

class ClosingOrdersController extends Controller
{
    public $date;
    public $hour;
    public $notification;

    public function options($actionID)
    {
        return [
            'date',
            'hour',
            'notification'
        ];
    }

    public function optionAliases()
    {
        return [
            'date' => 'date',
            'hour' => 'hour',
            'notification' => 'notification'
        ];
    }

    public function actionIndex()
    {
        // exemple tâche planifiée : ./yii closing-orders -notification=1

        $producerModule = ProducerModule::getInstance();
        $distributionModule = DistributionModule::getInstance();
        $orderModule = OrderModule::getInstance();
        $userModule = UserModule::getInstance();

        [$date, $hour] = $this->getDateHour();
        $arrayProducers = $producerModule->getRepository()->findProducers();
        $userSystem = $userModule->getRepository()->findOneUserById(User::ID_USER_SYSTEM)

        foreach($arrayProducers as $producer) {
            \Yii::$app->logic->setProducerContext($producer);
            $distribution = $distributionModule->getRepository()->findOneDistribution($date, true);

            if($distribution) {
                // @TODO : gérer les horaires spécifiques
                if($hour == $producer->order_deadline || !$hour) {
                    $ordersArray = $orderModule->getRepository()->findOrdersByDistribution($distribution);

                    foreach($ordersArray as $order) {
                        $orderModule->getBuilder()->initOrder($order);

                        $this->payOrder($order, $userSystem);
                        $this->notifyProducer($distribution);
                    }
                }
            }
        }
    }

    public function notifyProducer(Distribution $distribution)
    {
        $producerModule = ProducerModule::getInstance();

        if ($this->notification
            && $producerModule->getSolver()->getConfig('option_notify_producer_order_summary')) {

            $mail = $this->buildMailNotificationProducer($distribution);
            $this->sendMailNotificationProducer($mail, $distribution->producer);
        }
    }

    public function buildMailNotificationProducer(Distribution $distribution)
    {
        $orderModule = OrderModule::getInstance();
        $distributionModule = DistributionModule::getInstance();

        $ordersArray = $orderModule->getRepository()->findOrdersByDistribution($distribution);
        $mail = \Yii::$app->mailer->compose(
            [
                'html' => '@common/mail/cronOrdersSummary-html',
                'text' => '@common/mail/cronOrdersSummary-text',
            ], [
                'date' => $distribution->date,
                'orders' => $ordersArray
            ]
        )->setFrom([\Yii::$app->parameterBag->get('adminEmail') => 'Souke']);

        if (count($ordersArray)) {
            $subject = '[Souke] Commandes du ' . date('d/m', strtotime($distribution->date));
            // @TODO : envoyer uniquement les exports qui sont activés dans les paramètres du producteur
            $distributionModule->getExportManager()->generate(ExportManager::ORDERS_PDF, $distribution, true);
            $mail->attach(\Yii::getAlias('@app/web/pdf/Commandes-' . $distribution->date . '-' . $distribution->producer->id . '.pdf'));
        } else {
            $subject = '[Souke] Aucune commande';
        }
        $mail->setSubject($subject);

        return $mail;
    }

    public function sendMailNotificationProducer($mail, Producer $producer)
    {
        $userModule = UserModule::getInstance();
        $usersArray = $userModule->getRepository()->findUsersByProducer($producer);

        foreach ($usersArray as $user) {
            if($user->email && strlen($user->email)) {
                $mail->setTo($user->email)->send();
            }
        }
    }

    public function payOrder(Order $order, User $userSystem)
    {
        $paymentModule = PaymentModule::getInstance();
        $orderModule = OrderModule::getInstance();

        if($orderModule->getRepository()->isCreditAutoPayment($order)
            && $orderModule->getSolver()->getOrderAmount($order, Order::AMOUNT_REMAINING) > 0) {

            $paymentModule->getManager()->payOrder(
                $order,
                MeanPayment::CREDIT,
                $userSystem,
                false
            );
        }
    }

    public function getDateHour(): array
    {
        $hour = $this->hour;
        $date = $this->date;

        if(!$date) {
            $hour = date('H');
            if ($hour == '00') {
                $date = date('Y-m-d');
                $hour = 24;
            } else {
                $date = date('Y-m-d', time() + 24 * 60 * 60);
            }
        }

        return [$date, $hour];
    }
}

?>