<?php declare(strict_types=1);

namespace Shop\Application\Shopping\SendNotifyOrderChangeState;

use Core\Helpers\Date;
use Shop\Application\Notification\SendEmail\SendEmailCommand;
use Diamond\Application\Notification\NotificationService;
use Shop\Application\Shopping\ShoppingService;
use spaceonfire\CommandBus\CommandBus;

class SendNotifyOrderChangeStateHandler
{

    /**
     * SendNotifyOrderChangeStateHandler constructor.
     * @param NotificationService $notificationService
     * @param CommandBus $commandBus
     */
    public function __construct(protected NotificationService $notificationService,
                                protected ShoppingService $shoppingService,
                                protected 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 = $this->shoppingService->prepareCustomerOrderDataForReport($order);
        
        $data = array_merge($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);
        }

    }

}