<?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\Block\Adminhtml\Order\Edit\Items;

use Magento\Backend\Block\Template\Context;
use Magento\Backend\Model\Session\Quote;
use Magento\Catalog\Helper\Data as CatalogHelper;
use Magento\CatalogInventory\Api\StockRegistryInterface;
use Magento\CatalogInventory\Api\StockStateInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Pricing\PriceCurrencyInterface;
use Magento\GiftMessage\Helper\Message;
use Magento\GiftMessage\Model\Save;
use Magento\Quote\Model\Quote\Item;
use Magento\Sales\Block\Adminhtml\Order\Create\Items\Grid as GridItems;
use Magento\Sales\Model\AdminOrder\Create;
use Magento\Tax\Helper\Data;
use Magento\Tax\Model\Config;
use Magento\Wishlist\Model\WishlistFactory;
use Mageplaza\EditOrder\Helper\Data as EditOrderHelper;

class Grid extends GridItems
{
    /**
     * @var EditOrderHelper
     */
    protected $editOrderHelper;

    /**
     * @param Context $context
     * @param Quote $sessionQuote
     * @param Create $orderCreate
     * @param PriceCurrencyInterface $priceCurrency
     * @param WishlistFactory $wishlistFactory
     * @param Save $giftMessageSave
     * @param Config $taxConfig
     * @param Data $taxData
     * @param Message $messageHelper
     * @param StockRegistryInterface $stockRegistry
     * @param StockStateInterface $stockState
     * @param EditOrderHelper $editOrderHelper
     * @param array $data
     * @param CatalogHelper|null $catalogHelper
     */
    public function __construct(
        Context $context,
        Quote $sessionQuote,
        Create $orderCreate,
        PriceCurrencyInterface $priceCurrency,
        WishlistFactory $wishlistFactory,
        Save $giftMessageSave,
        Config $taxConfig,
        Data $taxData,
        Message $messageHelper,
        StockRegistryInterface $stockRegistry,
        StockStateInterface $stockState,
        EditOrderHelper $editOrderHelper,
        array $data = [],
        ?CatalogHelper $catalogHelper = null
    ) {
        parent::__construct($context, $sessionQuote, $orderCreate, $priceCurrency, $wishlistFactory, $giftMessageSave,
            $taxConfig, $taxData, $messageHelper, $stockRegistry, $stockState, $data, $catalogHelper);

        $this->editOrderHelper = $editOrderHelper;
    }

    /**
     * Check to update form data
     *
     * @return bool
     */
    public function isUpdate()
    {
        $request = $this->getRequest()->getParams();

        if (isset($request['order_id']) && $request['order_id']) { // if click edit item button
            return true;
        }

        if (isset($request['block'])) { // if click add product button
            $params = explode(',', $request['block']);

            return in_array('search', $params, true);
        }

        return false;
    }

    /**
     * Get Total tax quote items
     *
     * @return float
     */
    public function getTotalTaxItems($items)
    {
        $tax = 0;
        /** @var Item $item */
        foreach ($items as $item) {
            $tax += $item->getTaxAmount() + EditOrderHelper::getWeeTaxsItemAmountApplied($item->getWeeeTaxApplied());
        }

        return $tax;
    }

    /**
     * Check is custom discount
     *
     * @param Item $item
     *
     * @return bool
     */
    public function isCustomDiscount($item)
    {
        if ($item->getMpCustomDiscountValue() === '') {
            return false;
        }

        return $item->getMpCustomDiscountValue();
    }

    /**
     * @return array
     */
    public function getDiscountOptions()
    {
        return [
            'default' => __('Value Default'),
            'percent' => __('Percent'),
            'fixed'   => __('Fixed Amount')
        ];
    }

    /**
     * @return mixed
     *
     */
    public function getCatalogHelper()
    {
        return $this->_data['catalogHelper'];
    }

    /**
     * @return string
     *
     */
    public function formatPriceItems($value)
    {
        return $this->priceCurrency->convertAndRound($value);
    }

    /**
     * @param $items
     *
     * @return float
     */
    public function getTotalDiscount($items)
    {
        $total = 0;
        foreach ($items as $item) {
            $total += $item->getTotalDiscountAmount();
        }

        return $total;
    }

    /**
     * @param $items
     *
     * @return float
     */
    public function getFinalSubtotal($items): float
    {
        return $this->getSubtotalIncludingTax() - $this->getTotalDiscount($items);
    }

    /**
     * @return float
     */
    public function getSubtotalIncludingTax()
    {
        $subtotalInclTax = 0;
        foreach ($this->getQuote()->getAllVisibleItems() as $visibleItem) {
            $subtotalInclTax += $visibleItem->getRowTotal() + $visibleItem->getTaxAmount();
        }

        return $subtotalInclTax;
    }

    /**
     * Return html for row total with discount
     *
     * @param Item $item
     *
     * @return string
     * @throws LocalizedException
     */
    public function getItemRowTotalWithDiscountHtml(Item $item)
    {
        $block = $this->getLayout()->getBlock('item_row_total_with_discount');
        $block->setItem($item);

        return $block->toHtml();
    }

    /**
     * GetTaxPercent in view Quote Admin
     *
     * @param Item $_item
     *
     * @return float
     */
    public function getTaxPercent($_item)
    {
        if ($_item->getMpCustomTaxPercent()) {
            return $_item->getMpCustomTaxPercent();
        } else {
//            if ($_item->getProductType() === "bundle") {
//                return round(($_item->getTaxAmount() / $_item->getBasePrice()) * 100/$_item->getQty(), 10);
//            } else {
                return $_item->getTaxPercent();
//            }
        }
    }

    /**
     * Check is custom tax Item
     *
     * @param Item $_item
     *
     * @return bool
     */
    public function isCustomTax($_item)
    {
        if ($_item->getMpCustomTaxPercent() !== null) {
            return true;
        }

        return false;
    }
}
