<?php
/******************************************************************************
 *   ______                                                                   *
 *  /       \                                                                 *
 * /$$$$$$  | ________  __    __   ______    ______                           *
 * $$ |__$$ |/        |/  |  /  | /      \  /      \                          *
 * $$    $$ |$$$$$$$$/ $$ |  $$ |/$$$$$$  |/$$$$$$  |                         *
 * $$$$$$$$ |  /  $$/  $$ |  $$ |$$ |  $$/ $$    $$ |                         *
 * $$ |  $$ | /$$$$/__ $$ \__$$ |$$ |      $$$$$$$$/                          *
 * $$ |  $$ |/$$      |$$    $$/ $$ |      $$       |                         *
 * $$/   $$/ $$$$$$$$/  $$$$$$/  $$/        $$$$$$$/                          *
 *                                                                            *
 * @PROJECT    : 3D Preview Extension [Magetop.com]                           *
 * @AUTHOR     : Azure - Developer                                            *
 * @COPYRIGHT  : © 2019  Magetop.com                                          *
 * @LINK       : https://Magetop.com                                          *
 * @CREATED    :  10/01/2022                                                  *
 ******************************************************************************/

namespace Magetop\Advancepreview\Observer\Frontend;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;

/**
 * Class SaveOrder
 * @package Magetop\Advancepreview\Observer\Frontend
 */
class SaveOrder implements ObserverInterface
{
    /**
     * @var \Magetop\Advancepreview\Model\PreviewOrderItemsFactory
     */
    protected $previewOrderItemsFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory
     */
    protected $resPreviewOrderItemsFactory;
    protected $previewOrdersFactory;
    protected $resPreviewOrdersFactory;
    public function __construct(
        \Magetop\Advancepreview\Model\PreviewOrderItemsFactory $previewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory $resPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\PreviewOrdersFactory $previewOrdersFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrdersFactory $resPreviewOrdersFactory
    )
    {
        $this->previewOrderItemsFactory = $previewOrderItemsFactory;
        $this->resPreviewOrderItemsFactory = $resPreviewOrderItemsFactory;
        $this->previewOrdersFactory = $previewOrdersFactory;
        $this->resPreviewOrdersFactory = $resPreviewOrdersFactory;
    }

    public function execute(Observer $observer)
    {
        /** @var \Magento\Sales\Model\Order $order*/
        $order =  $observer->getData('order');
        $items = $order->getAllItems();
//        $orderId = $order->getId();
        $date = Date('Y-m-d H:i:s');
        $projectPrice = 0;

        if(count($items))
        {
            foreach ($items as $item)
            {
                $status = 'new';
                $infoRequest = $item->getProductOptionByCode('info_buyRequest');
                $designType = isset($infoRequest['txt_custom_preview_design_type']) ? $infoRequest['txt_custom_preview_design_type'] : 0;
                $customDesign = isset($infoRequest['customer_upload_design']) ? $infoRequest['customer_upload_design'] : '';
                $isAdminCreateDesign = isset($infoRequest['is_design_service']) ? $infoRequest['is_design_service'] : 0;
                $projectName = isset($infoRequest['custom_project_name']) ? $infoRequest['custom_project_name'] : '';
                $gernerateProjoectId = isset($infoRequest['text_project_generate']) ? $infoRequest['text_project_generate'] : 0;
                $namePreviewModel = isset($infoRequest['txt_preview_selected']) ? $infoRequest['txt_preview_selected'] : '';
                if($gernerateProjoectId > 0) {
                    if($gernerateProjoectId > 1000) {
//                        $gernerateProjoectId = $gernerateProjoectId;
                    }
                    else if($gernerateProjoectId > 100) {
                        $gernerateProjoectId = '0'.$gernerateProjoectId;
                    }
                    else if($gernerateProjoectId > 10) {
                        $gernerateProjoectId = '00'.$gernerateProjoectId;
                    }
                    else {
                        $gernerateProjoectId = '000'.$gernerateProjoectId;
                    }
                }
                else {
                    $gernerateProjoectId = '';
                }
                if($gernerateProjoectId != '') {
                    $projectName = $gernerateProjoectId . ' - ' .$projectName;
                }
               /* if($designType == 0) {
                    $isAdminCreateDesign = 0;
                }
                if($isAdminCreateDesign == 1) {
                    $customDesign = '';
                }
                if($designType == 1 && $customDesign == '') {
                    $isAdminCreateDesign = 1;
                }*/
                // if custom upload file, admin not create design or else

                if($designType == 0 || $customDesign != '') {
                    $isAdminCreateDesign = 0;
                }
                elseif($designType == 1 && $customDesign == '') {
                    $isAdminCreateDesign = 1;
                }
                $previewData = [
                    'order_id'=>$order->getId(),
                    'item_id'=>$item->getId(),
                    'product_id'=>$item->getProductId(),
                    'status'=>$status,
                    'custom_design'=>$customDesign,
                    'info_request'=>json_encode($infoRequest),
                    'created_at'=>$date,
                    'updated_at'=>$date,
                    'admin_upload_status'=>0,
                    'admin_upload_design'=>'',
                    'project_name'=>$projectName,
                    'is_admin_create'=>$isAdminCreateDesign,
                    'preview_model'=>$namePreviewModel,
                ];
                $projectItemPrice = isset($infoRequest['txt_project_final_price']) ? $infoRequest['txt_project_final_price'] : 0;
                $projectItemPrice = round($projectItemPrice,2);
                $projectPrice += $projectItemPrice;
                $this->savePreviewOrderItem($previewData);
            }
        }
        $this->saveCustomPreviewOrder($order->getId(), $projectPrice);
    }

    /**
     * @param array $previewData
     * @return int
     */
    protected function savePreviewOrderItem($previewData = []) {
        $model = $this->previewOrderItemsFactory->create();
        $model->setData($previewData);
        $id = 0;
        try {
            $this->resPreviewOrderItemsFactory->create()->save($model);
            $id =  $model->getId();
        }
        catch (\Exception $exception) {

        }
        return $id;

    }
    protected function saveCustomPreviewOrder($orderId, $orderTotal) {
        $dataSave = [
            'order_id'=>$orderId,
            'order_status'=>$orderId,
            'order_total'=>$orderTotal
        ];
        $model = $this->previewOrdersFactory->create();
        $model->setData($dataSave);
        try {
            $this->resPreviewOrdersFactory->create()->save($model);
        }
        catch (\Exception $exception) {

        }
    }

}
