<?php
/**
 * Mageplaza
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Mageplaza.com license that is
 * available through the world-wide-web at this URL:
 * https://www.mageplaza.com/LICENSE.txt
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade this extension to newer
 * version in the future.
 *
 * @category    Mageplaza
 * @package     Mageplaza_EditOrder
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

namespace Mageplaza\EditOrder\Model;

use Magento\Framework\DataObject;
use Magento\Framework\Model\AbstractModel;
use Mageplaza\EditOrder\Model\ResourceModel\PreviousCart as ResourceModel;

/**
 * Class PreviousCart
 * @package Mageplaza\EditOrder\Model
 */
class PreviousCart extends AbstractModel
{
    const CACHE_TAG = 'mageplaza_edit_order';

    /**
     * @var string
     */
    protected $_eventPrefix = 'mageplaza_edit_order';


    /**
     * Initialize resource model
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init(ResourceModel::class);
    }

    /**
     * @inheritdoc
     * @throws LocalizedException
     * @throws Exception
     */
    public function afterSave()
    {
        parent::afterSave();

        $orderId = $this->getOrderId();
        $quoteId = $this->getQuoteId();

        if ($this->isDuplicate($orderId, $quoteId)) {
            $this->_dataSaveAllowed = false;
            return $this;
        }

        return $this;
    }

    /**
     * Check if order_id and quote_id already exist
     *
     * @param int $orderId
     * @param int $quoteId
     * @return bool
     */
    public function isDuplicate($orderId, $quoteId)
    {
        $collection = $this->getCollection()
            ->addFieldToFilter('order_id', $orderId)
            ->addFieldToFilter('quote_id', $quoteId);

        return $collection->getSize() > 0;
    }

    /**
     * Save or update PreviousCart based on order_id
     *
     * @param int $orderId
     * @param int $quoteId
     * @param array $currentItems
     * @param array $itemIdInOrder
     * @return $this
     * @throws LocalizedException
     */
    public function saveOrUpdate($orderId, $quoteId, $currentItems, $itemIdInOrder)
    {
        // Load PreviousCart by order_id
        $previousCart = $this->getPreviousCartByOrderId($orderId);

        if ($previousCart) {
            // Update existing record
            $previousCart->setQuoteId($quoteId);
            $previousCart->setQuoteItems(json_encode($currentItems));
            $previousCart->setItemIdOrder(json_encode($itemIdInOrder));
            $previousCart->save();
        } else {
            // Create new record
            $this->setData([
                'quote_id'      => $quoteId,
                'order_id'      => $orderId,
                'quote_items'   => json_encode($currentItems),
                'item_id_order' => json_encode($itemIdInOrder)
            ]);
            $this->save();
        }

        return $this;
    }

    /**
     * Get PreviousCart object by order_id
     *
     * @param int $orderId
     * @return PreviousCart|null
     * @throws LocalizedException
     */
    protected function getPreviousCartByOrderId($orderId)
    {
        $collection = $this->getCollectionLoadByOrder($orderId);

        return $collection->getId() ? $collection : null;
    }

    /**
     * Get quote items by order id
     *
     * @param int $orderId
     * @return array|null
     */
    public function getQuoteItemsByOrderId($orderId)
    {
        $collection = $this->getCollectionLoadByOrder($orderId);

        return $collection->getId() ? json_decode($collection->getQuoteItems(), true) : null;
    }

    /**
     * Get item_id_order by order_id
     *
     * @param int $orderId
     * @return array|null
     */
    public function getItemIdOrderByOrderId($orderId)
    {
        $collection = $this->getCollectionLoadByOrder($orderId);

        if ($collection->getId()) {
            return json_decode($collection->getItemIdOrder(), true);
        }

        return null;
    }

    /**
     * @param $orderId
     *
     * @return DataObject
     */
    public function getCollectionLoadByOrder($orderId)
    {
        return $this->getCollection()
            ->addFieldToFilter('order_id', $orderId)
            ->getFirstItem();
    }

}
