<?php


namespace Magetop\Advancepreview\Controller\Adminhtml\OrderTracking;


use Magento\Backend\App\Action;

/**
 * Class UploadMedia
 * @package Magetop\Advancepreview\Controller\Adminhtml\ProductPreview
 */
class Save extends \Magetop\Advancepreview\Controller\Adminhtml\OrderTracking
{
    /**
     *
     */
    const CUSTOM_PREVIEWS = 'custom_previews';
    /**
     * @var \Magento\Framework\Filesystem\Driver\File
     */
    protected $file;
    /**
     * @var \Magetop\Advancepreview\Model\AdvancePreviewFileFactory
     */
    protected $advancePreviewFileFactory;
    /**
     * @var \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory
     */
    protected $advancePreviewUploadFactory;
    /**
     * @var \Magetop\Advancepreview\Model\PreviewOrderTrackingFactory
     */
    protected $previewOrderTrackingFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderTrackingFactory
     */
    protected $resPreviewOrderTrackingFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderTracking\CollectionFactory
     */
    protected $colPreviewOrderTrackingFactory;
    /**
     * @var \Magento\Sales\Model\OrderFactory
     */
    protected $orderFactory;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magetop\Advancepreview\Helper\Email
     */
    protected $emailHelper;

    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magento\Framework\Filesystem\Driver\File $file,
        \Magetop\Advancepreview\Model\AdvancePreviewFileFactory $advancePreviewFileFactory,
        \Magetop\Advancepreview\Model\AdvancePreviewUploadFactory $advancePreviewUploadFactory,
        \Magetop\Advancepreview\Model\PreviewOrderTrackingFactory $previewOrderTrackingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderTrackingFactory $resPreviewOrderTrackingFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderTracking\CollectionFactory $colPreviewOrderTrackingFactory,
        \Magento\Sales\Model\OrderFactory $orderFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magetop\Advancepreview\Helper\Email $emailHelper
    )
    {
        parent::__construct($context, $jsonFactory);
        $this->file = $file;
        $this->advancePreviewFileFactory = $advancePreviewFileFactory;
        $this->advancePreviewUploadFactory = $advancePreviewUploadFactory;
        $this->previewOrderTrackingFactory = $previewOrderTrackingFactory;
        $this->resPreviewOrderTrackingFactory = $resPreviewOrderTrackingFactory;
        $this->colPreviewOrderTrackingFactory = $colPreviewOrderTrackingFactory;
        $this->orderFactory = $orderFactory;
        $this->productFactory = $productFactory;
        $this->emailHelper = $emailHelper;

    }

    /**
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\Result\Json|\Magento\Framework\Controller\ResultInterface|void
     * @throws \Magento\Framework\Exception\FileSystemException
     */
    function execute()
    {
        $response = [
            'status'=>'error',
            'message'=>__('Something wrong when saving data'),
            'html'=>''
        ];
        $dataSave = $this->getRequest()->getParam('tracking',[]);
        $id = isset($params['preview_tracking_id']) ? (int)$params['preview_tracking_id'] : 0;
        if($id <= 0 && isset($dataSave['preview_tracking_id'])) {
            unset($dataSave['preview_tracking_id']);
        }
        $orderId = isset($dataSave['order_id']) ? $dataSave['order_id'] : 0;
        $productId = isset($dataSave['product_id']) ? $dataSave['product_id'] : 0;
        $newId = $this->saveOrderTracking($dataSave);
        if((int)$newId > 0) {
            $response['status'] = 'success';
            $response['message'] = __('you have saved tracking success');
            $response['html'] = $this->_view->getLayout()->createBlock('Magetop\Advancepreview\Block\Adminhtml\Order\PreviewOrderTracking')->setTemplate('Magetop_Advancepreview::order/tracking/tracking_items.phtml')->toHtml();
            // send email
            $emailId = 'eak_admin_update_order_item_send_tracking';
            $dataOrder = $this->getOrderIncrmentId($orderId);
            $productName = $this->getProductName($productId);
            $customerEmail = $dataOrder['email'];
            if($customerEmail != '') {
                $templatavals = [
                    'customer_name'=>$dataOrder['customer_name'],
                    'product_name'=>$productName,
                    'order_id'=>$dataOrder['increment_id'],
                    'tracking_number'=>$dataSave['tracking_number'],
                    'tracking_link'=>$dataSave['tracking_link'],
                    'courier_company'=>$dataSave['courier_company'],
                ];
                $send = $this->sendEmailToCustomer($customerEmail,$emailId,$templatavals);
//                $response['send'] = $send['message'] . $emailId;
                if($send['status'] == 'success') {
                    $response['message'] = __('you have saved and sent tracking success');
                }
            }


        }
        else {
            $response['message'] = $newId;
        }
        if($response['status'] == 'success') {
            $this->messageManager->addSuccessMessage($response['message']);
        }
        else {
            $this->messageManager->addErrorMessage($response['message']);
        }
        return $this->getAjaxResponse($response);
    }

    /**
     * @param array $dataSave
     * @return mixed|string
     */
    protected function saveOrderTracking($dataSave = []) {
        $model = $this->previewOrderTrackingFactory->create();
        $model->setData($dataSave);
        $id = 0;
        try {
            $this->resPreviewOrderTrackingFactory->create()->save($model);
            $id = $model->getId();
        }
        catch (\Exception $exception) {
            $id = $exception->getMessage();
        }
        return $id;

    }


    /**
     * @param int $orderId
     * @return string[]
     */
    protected function getOrderIncrmentId($orderId = 0) {
        $order = $this->orderFactory->create()->load($orderId);
        $data = [
            'increment_id'=>'',
            'customer_name'=>'',
            'email'=>''
        ];
        if($order) {
            $data['increment_id'] = $order->getIncrementId();
            $data['customer_name'] = $order->getCustomerName();
            $data['email'] = $order->getCustomerEmail();
        }
        return $data;
    }

    /**
     * @param int $productId
     * @return string
     */
    protected function getProductName($productId = 0) {
        $product = $this->productFactory->create()->load($productId);
        return $product ? $product->getName() : '';
    }

    /**
     * @param $toEmail
     * @param $emailId
     * @param array $templateVars
     * @return string[]
     */
    protected function sendEmailToCustomer($toEmail, $emailId, $templateVars = []) {
        $sendResponse = array(
            'status'=>'error',
            'message'=>'Can not send email'
        );
        $storeName = 'myfitmix';
        $templateVars['custom_store_name'] = $storeName;
//        $emailId = 'eak_customer_order_item_ready_sale';
        $formEmail = 'info@myfitmix.de';
        if($toEmail == '') {
            $sendResponse['message'] = 'Email not found';
        }
        else {
            $sendResponse = $this->emailHelper->sendAdvanceEmail($emailId,$templateVars,$storeName,$formEmail,$toEmail);
        }
        return $sendResponse;
    }
}
