<?php


namespace Magetop\Advancepreview\Controller\Adminhtml\Order;

use Magento\Backend\App\Action;



class UpdatePaidStatus extends Action
{
    protected $jsonFactory;
    protected $previewOrderItemsFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory
     */
    protected $resPreviewOrderItemsFactory;
    protected $colPreviewOrderItemsFactory;
    public function __construct(
        Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $jsonFactory,
        \Magetop\Advancepreview\Model\PreviewOrderItemsFactory $previewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItemsFactory $resPreviewOrderItemsFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewOrderItems\CollectionFactory $colPreviewOrderItemsFactory
    )
    {
        parent::__construct($context);
        $this->jsonFactory = $jsonFactory;
        $this->previewOrderItemsFactory = $previewOrderItemsFactory;
        $this->resPreviewOrderItemsFactory = $resPreviewOrderItemsFactory;
        $this->colPreviewOrderItemsFactory = $colPreviewOrderItemsFactory;
    }

    public function execute()
    {
        $itemId = $this->getRequest()->getParam('item_id',0);
        $paid = $this->getRequest()->getParam('pay_status','');
        $response = [
            'status'=>'error',
            'title'=>'error',
            'message'=>'can not update status',
        ];
        try {
            if($itemId > 0 && $paid != '') {
                $previewItem = $this->getPreviewItemByItemId($itemId);
                if($previewItem && $previewItem->getId()) {
                    $datSave = [
                        'custom_item_id'=>$previewItem->getId(),
                        'paid_status'=>$paid
                    ];
                    $model = $this->previewOrderItemsFactory->create();
                    $model->setData($datSave);
                    $this->resPreviewOrderItemsFactory->create()->save($model);
                    $response['status'] = 'success';
                    $response['title'] = 'Success';
                    $response['message'] = __('You have updated the status successfully');
                }
            }
        }
        catch (\Exception $exception) {
            $response['message'] = $exception->getMessage();
        }
        return $this->jsonFactory->create()->setData($response);
    }
    public function getPreviewItemByItemId($itemId = 0) {
        $collection = $this->colPreviewOrderItemsFactory->create()
            ->addFieldToSelect(array('status'))
            ->addFieldToFilter('item_id',$itemId);
        $previewItem = $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        return $previewItem;

    }

}
