<?php


namespace Shop\Application\Shopping\SendNotifyOrderChangeState;


use Core\Helpers\Date;
use Shop\Application\Notification\SendEmail\SendEmailCommand;

use Diamond\Application\Notification\NotificationService;
use spaceonfire\CommandBus\CommandBus;

class SendNotifyOrderChangeStateHandler
{
    /**
     * @var
     */
    protected $notificationService;

    /**
     * @var CommandBus
     */
    protected $commandBus;

    /**
     * SendNotifyOrderChangeStateHandler constructor.
     * @param NotificationService $notificationService
     * @param CommandBus $commandBus
     */
    public function __construct(NotificationService $notificationService, CommandBus $commandBus)
    {
        $this->notificationService = $notificationService;
        $this->commandBus = $commandBus;
    }

    /**
     * @param SendNotifyOrderChangeStateCommand $command
     * @throws \Propel\Runtime\Exception\PropelException
     * @throws \Repo\Concrete\Exceptions\Collection
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     */
    public function handle(SendNotifyOrderChangeStateCommand $command): void
    {
        $order = $command->getOrder();

        $customer = $order->getCustomer();

        if ($customer->getNotifyOrder() === "N") {
            return;
        }

        $data = array(
            'date' => $order->getDatetime(Date::formatDisplay()),
            'cst_name' => $customer->getName(),
            'order_code' => $order->getOrderCode(),
            'state' => $order->getState()->getTitle()
        );

        //EMAIL ------------------------------------------------------------------
        //отправляем уведомление
        if ($customer->isNotifyEmail() === true && $customer->getEmail()) {
            $this->notificationService->sendToEmailByReport('change_state_order_email',$customer->getEmail(), $data);
        }

        // SMS ------------------------------------------------------------------
        if ($customer->isNotifySms() === true && $customer->getPhone()) {
            $this->notificationService->sendToPhoneByReport('change_state_order_sms',$customer->getPhone(),$data);
        }

    }

}