<?

namespace Shop\Services;

use Diamond\Services\Report,
    Propel\Runtime\Map\TableMap;
use Shop\{
    Config\Main, DTO\CustomerRequest, DTO\OrderRequest, Models\Customer\Customer, Models\OrderItem\OrderItem
};
use Twig\Environment;

/**
 * Сервис заказа
 *
 * @author Admin
 */
class Order
{

    protected $orderRepo;
    protected $confMain;
    protected $reportService;
    protected $twig;
    protected $notifyService;

    function __construct(\Shop\Repositories\Order $orderRepo, Main $confMain, Report $reportService,
                         Environment $twig, Notify $notifyService)
    {
        $this->orderRepo = $orderRepo;
        $this->confMain = $confMain;
        $this->reportService = $reportService;
        $this->twig = $twig;
        $this->notifyService = $notifyService;
    }

    /**
     * Уведомление о смене статуса заказа и почтового кода
     * 
     * @param \Shop\Models\Order\Order $order
     */
    public function notifyAboutStateAndPostCode(\Shop\Models\Order\Order $order)
    {
        $code = trim($order->getPostCode());
        $customer = $order->getCustomer();

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

        $data = [
            "order_code"   => $order->getOrderCode(),
            "date"         => $order->getDatetime(\Diamond\Helpers\Date::formatDisplay()),
            "state"        => $order->getState()->getTitle(),
            "post_code"    => $code,
            "ruspost_link" => anchor($this->confMain->getRussianPostUrl() . '#' . $code, $code,
                                     [
                "title"  => "перейти на сайт почты",
                "target" => "_blank"
                    ]
            )
        ];

        //на email
        $message = $this->reportService->buildMessageFromContent("change_post_code_and_state_email", $data);

        //отправляем уведомление
        if ($message && $customer->isNotifyEmail() === true) {
            $this->notifyService->sendToEmail($customer->getEmail(), $message);
        }

        //на cmc
        $messageSms = $this->reportService->buildMessageFromContent("change_post_code_and_state_sms", $data);

        if ($messageSms && $customer->isNotifySms() === true) {

            $this->notifyService->sendToSms($customer->getPhone(), $messageSms);
        }
    }

    /**
     * 
     * @param \Shop\Models\Order\Order $order
     * @return type
     */
    public function notifyAboutState(\Shop\Models\Order\Order $order)
    {
        $customer = $order->getCustomer();

        if ($customer->getNotifyOrder() == "N") {
            return;
        }
        
        $data = array(
                    'date'      =>  $order->getDatetime(\Diamond\Helpers\Date::formatDisplay()),
                    'cst_name'  =>  $customer->getName(),
                    'order_code'=>  $order->getOrderCode(),
                    'state'     =>  $order->getState()->getTitle()
                );
        
        //на email
        $message = $this->reportService->buildMessageFromContent("change_state_order_email", $data);

        //отправляем уведомление
        if ($message && $customer->isNotifyEmail() === true) {
            $this->notifyService->sendToEmail($customer->getEmail(), $message);
        }

        //на cmc
        $messageSms = $this->reportService->buildMessageFromContent("change_state_order_sms", $data);

        if ($messageSms && $customer->isNotifySms() === true) {

            $this->notifyService->sendToSms($customer->getPhone(), $messageSms);
        }        
    }

    /**
     * 
     * @param \Shop\Models\Order\Order $order
     */
    public function notifyAboutPostCode(\Shop\Models\Order\Order $order)
    {
        $code = trim($order->getPostCode());
        $customer = $order->getCustomer();

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

        $data = [
            "order_code"   => $order->getOrderCode(),
            "date"         => $order->getDatetime(\Diamond\Helpers\Date::formatDisplay()),
            "state"        => $order->getState()->getTitle(),
            "post_code"    => $code,
            "ruspost_link" => anchor($this->confMain->getRussianPostUrl() . '#' . $code, $code,
                                     [
                "title"  => "перейти на сайт почты",
                "target" => "_blank"
                    ]
            )
        ];
        
        //на email
        $message = $this->reportService->buildMessageFromContent("change_post_code_order_email", $data);

        //отправляем уведомление
        if ($message && $customer->isNotifyEmail() === true) {
            $this->notifyService->sendToEmail($customer->getEmail(), $message);
        }

        //на cmc
        $messageSms = $this->reportService->buildMessageFromContent("change_post_code_order_sms", $data);

        if ($messageSms && $customer->isNotifySms() === true) {

            $this->notifyService->sendToSms($customer->getPhone(), $messageSms);
        }         
    }

    /**
     * Создание заказа
     * 
     * @param OrderRequest $order
     * @return int
     */
    public function createWithNotify(OrderRequest $_order): \Shop\Models\Order\Order
    {

        $order = $this->create($_order);

        $customer = $order->getCustomer();

        /**
         * @todo Исправить отправку
         * Возможно ту нужно чтобы уведомления уходили менеджеру магазина или на почту самого магазина
         */
        $manager = $customer->getManager();
        
        //формируем сообщение
        $imgPath = $this->confMain->getStockImagePath() . $order->getShop()->getLogo();
        
        $data = [
            "order"      => $order->toArray(TableMap::TYPE_CAMELNAME, true, [], true),
            "customer"   => $customer->toArray(TableMap::TYPE_CAMELNAME),
            "manager"    => $customer->getManager()->toArray(TableMap::TYPE_CAMELNAME),
            "payment"    => $order->getPayment()->toArray(TableMap::TYPE_CAMELNAME),
            "shop_image" => file_exists($_SERVER["DOCUMENT_ROOT"] . $imgPath) ? $imgPath : "/assets/images/no-photo.jpg",
            "shop_name"  => $order->getShop()->getTitle(),
            "summ"       => $order->getSumm(),
            "order_final_summ"=>$order->getOrderFinalSumm(),
            "discount_summ"=>$order->getDiscountSumm(),
            "discount_percent"=>$order->getDiscountPercent(),
            "currency"   => $this->confMain->getCurencyDisplay(),
            "group" =>  $customer->getCustomerGroup()
        ];

        $message = $this->reportService->buildMessageFromContent("order_notify", $data);

        //отправляем уведомление
        if ($message) {
            $this->notifyService->sendToEmail($customer->getEmail(), $message);
        }
        
        $messageManager = $this->reportService->buildMessageFromContent("order_notify_manager", $data);

        if($message && $manager){
            $this->notifyService->sendToEmail($manager->getEmail(), $messageManager);
        }
        
        return $order;
    }

    /**
     * Создание заказа
     * @param CustomerRequest $newCustomer
     * @return Customer
     * @throws \Core\Exceptions\LogicException
     */
    public function create(OrderRequest $orderRequest): \Shop\Models\Order\Order
    {

        $order = $this->orderRepo
                ->buildEntity()
                ->setCustomerId($orderRequest->getClient())
                ->setPaymentId($orderRequest->getPayment())
                ->setComment($orderRequest->getComment())
                ->setDeliveryAddress($orderRequest->getAddress())
                ->setShopId($orderRequest->getShop())
                ->setStateId($this->confMain->getStateDefault())
                ->setDiscountSumm($orderRequest->getDiscount())
        ;

        foreach ($orderRequest->getItems() as $item) {

            /**
             * @var $item \Shop\DTO\OrderItemRequest
             */
            $orderItem = (new OrderItem)
                    ->setAmount($item->getAmount())
                    ->setBrand($item->getBrand())
                    ->setDesc($item->getDesc())
                    ->setMenagerComment($item->getManagerComment())
                    ->setName($item->getName())
                    ->setArticle($item->getArticle())
                    ->setPrice($item->getPrice())
                    ->setMenagerComment($item->getMenagerComment())
                    ->setRefId($item->getRefId())
                    ->setCurrencyId(!$item->getCurrencyId()?1:$item->getCurrencyId())
            ;

            $order->addOrderItem($orderItem);
        }

        if ( ! $order->save()) {
            throw new \Core\Exceptions\LogicException("order not save");
        }

        return $order;
    }

}