<?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\Block;

use Magento\Framework\View\Element\Template;
use Psr\Log\LoggerInterface;

class PreviewMinicart extends  \Magetop\Advancepreview\Block\AdvancePreviewAbstract
{
    /**
     * @var \Magento\Customer\Model\Session
     */
    protected $customerSession;
    /**
     * @var \Magento\Customer\Model\CustomerFactory
     */
    protected $customerFactory;
    /**
     * @var \Magento\Checkout\Model\Cart
     */
    protected $cart;
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $productFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\ProductFactory
     */
    protected $resProductFactory;
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $colProductFactory;
    /**
     * @var \Magento\Framework\App\Http\Context
     */
    protected $httpContext;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory
     */
    protected $colPreviewDiscountFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory
     */
    protected $colPreviewAdditionalFactory;
    /**
     * @var \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory
     */
    protected $colPreviewThreeFactory;
    protected $addressFactory;
    protected $currency;
    protected $dailyShippingFactory;
    protected $logger;

    public function __construct(
        Template\Context $context,
        \Magento\Framework\Pricing\Helper\Data $priceHelper,
        \Magetop\Advancepreview\Helper\Data $advancePreviewHelper,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Checkout\Model\Cart $cart,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Catalog\Model\ResourceModel\ProductFactory $resProductFactory,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $colProductFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\CollectionFactory $colPreviewDiscountFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\CollectionFactory $colPreviewAdditionalFactory,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\CollectionFactory $colPreviewThreeFactory,
        \Magento\Customer\Model\AddressFactory $addressFactory,
        \Magento\Directory\Model\Currency $currency,
        \Magetop\Advancepreview\Model\ResourceModel\PreviewDailyShipping\CollectionFactory $dailyShippingFactory,
        LoggerInterface $logger,
        array $data = []
    )
    {
        parent::__construct($context, $priceHelper, $advancePreviewHelper, $data);
        $this->cart = $cart;
        $this->customerSession = $customerSession;
        $this->customerFactory = $customerFactory;

        $this->productFactory = $productFactory;
        $this->resProductFactory = $resProductFactory;
        $this->colProductFactory = $colProductFactory;
        $this->httpContext = $httpContext;
        $this->colPreviewDiscountFactory = $colPreviewDiscountFactory;
        $this->colPreviewAdditionalFactory = $colPreviewAdditionalFactory;
        $this->colPreviewThreeFactory = $colPreviewThreeFactory;
        $this->addressFactory = $addressFactory;
        $this->currency = $currency;
        $this->dailyShippingFactory = $dailyShippingFactory;
        $this->logger = $logger;
    }
    public function getTotalPriceInMiniCart() {
        $items = $this->getAllItemInCart();
        $grandTotal = 0;
        $grandTotalTax = 0;
        $response = array(
            'is_custom'=>'no',
            'total_price'=>0,
        );

        if($items) {
            $tax = 19;
            foreach ($items as $item) {
                $productId = $item->getProduct()->getId();
                $_product = $this->getProductById($productId);
                if(!$_product) {
                    continue;
                }
                $requestOption = $this->getItemInforestion($item);
                $tierPrice = $this->getTierPriceByProductId($_product);
                $tierQtyPrice = $this->getTierPriceItemByQty($tierPrice, $item->getQty());
                $ourPrice = $this->getCustomTierOurPrice($_product,$tierQtyPrice);
                $ourPriceRow = $ourPrice * $item->getQty();
                $customDiscounts = $this->getPreviewDiscounts($productId);
                $total = $ourPriceRow;
                $designType = isset($requestOption['txt_custom_preview_design_type']) ? $requestOption['txt_custom_preview_design_type'] : 0;
                $modelPreview = isset($requestOption['txt_preview_selected']) ? $requestOption['txt_preview_selected'] : 0;
                $gernerateProjoectId = isset($requestOption['text_project_generate']) ? $requestOption['text_project_generate'] : 0;
                // custom shipping
                $dailyId = isset($requestOption['txt_daily_shipping']) ? (int)$requestOption['txt_daily_shipping'] : 0;
                $dailyShippigAmount = 0;
                if($dailyId > 0) {
                    $dailyShippig = $this->getDailyShippingById($dailyId);
                    $dailyShippigAmount = $dailyShippig != null && $dailyShippig->getData('amount') > 0 ? $dailyShippig->getData('amount') : 0;
                }
                $i = 0;
                foreach ($customDiscounts as $customDiscount) {
                    if($i == 0) {
                        $i++;
                        continue;
                    }
                    $priceDiscountItem = ($customDiscount->getData('discount_title')=="Processing & Finishing" && $item->getQty() <4) ? 0:$customDiscount->getData('discount_price');
                    $this->logger->info("priceDiscountItem" .$priceDiscountItem);
                    if($designType == 1 && $i == 1) {
                        $paramAdditionalOptions = isset($requestOption['preview_additional_options']) ? $requestOption['preview_additional_options'] : [];
                        $this->logger->info("paramAdditionalOptions" .json_encode($paramAdditionalOptions));

                        $defaultValue = $tierQtyPrice * $item->getQty();
                        $this->logger->info("defaultValue" .$defaultValue);
                        $this->logger->info("ourPriceRow" .$ourPriceRow);


                        $priceDiscountItem =($this->getAdditionalOptionPrice($paramAdditionalOptions, $productId, $defaultValue)+$priceDiscountItem);
                        $this->logger->info("priceDiscountItem" .$priceDiscountItem);

                        $priceDiscount = $priceDiscountItem;
                        $this->logger->info("priceDiscount" .$priceDiscount);
                        $this->logger->info("priceDiscountItem" .$priceDiscountItem);
                        $priceAfterDiscont = $this->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);
                    }
                    else if($dailyShippigAmount > 0 && $i == $customDiscounts->getSize() - 1) {
                        // if shipping
                        $shippingCharge = (($tierQtyPrice * $dailyShippigAmount * $item->getQty()) / 100);
                        $this->logger->info("shippingCharge" .$shippingCharge);

                        $priceDiscountItem += $shippingCharge;
                        $this->logger->info("priceDiscountItem" .$priceDiscountItem);
                        $this->logger->info("shippingCharge" .$shippingCharge);
                        $priceAfterDiscont = $priceDiscountItem;
                    }
                    else{
                        $priceAfterDiscont = $this->getAddDiscountAdditionAllPrice($priceDiscountItem, $_product);
                    }

                    $this->logger->info("priceAfterDiscont" .$priceAfterDiscont);

                    $total += $priceAfterDiscont;
                    $this->logger->info("total" .$total);
                    $this->logger->info("priceAfterDiscont" .$priceAfterDiscont);


                    $i++;
                }

                if($total < 50)
                {
                    $total += 4;
                    $this->logger->info("shippingCharge" .($shippingCharge+4));
                }
                $grandTotal += $total;
                $this->logger->info("grandTotal" .$grandTotal);

            }
            if($grandTotal > 0) {
                $response['is_custom'] = 'yes';
                $grandTotalTax = $grandTotal + ($grandTotal * $tax) / 100;
                $this->logger->info("grandTotalTax" .$grandTotalTax);

                $response['total_price'] = $this->convertNumberToPrice($grandTotalTax) ;
                $this->logger->info("total_price" .$response['total_price']);

            }

        }

        return $response;

    }
    protected function getAllItemInCart() {
        $items = null;
        if($this->cart->getItems()) {
            $items = $this->cart->getItems();
        }
        return $items;
    }
    /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewThree\Collection
     */
    public function getPreviewByProductId($productId = 0) {
        $collection = $this->colPreviewThreeFactory->create()
            ->addFieldToSelect('*')
            ->addFieldToFilter('product_id',$productId)
            ->setOrder('position','ASC');
//        echo (string)$collection->getSelect();
        return $collection;
    }


    /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewDiscount\Collection
     */
    public function getPreviewDiscounts($productId = 0) {
        $collection = $this->colPreviewDiscountFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
        return $collection;
    }

    /**
     * @param \Magento\Quote\Model\Quote\Item $item
     * @return array
     */
    public function getItemInforestion($item) {
        $customOptionsRequest = [];
        if($item) {
            $customOptions = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct());
            if(isset($customOptions['info_buyRequest'])) {
                $customOptionsRequest = $customOptions['info_buyRequest'];
            }
        }

        return $customOptionsRequest;
    }


    public function getCustomTierOurPrice($product, $price = 0) {

        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
//            $product = $this->getProductById($productId);
            if($product) {
                $discount = $product->getData('pcto_discount');
                if($discount > 0) {
                    $price -= ($price * $discount) / 100;
                }
            }
        }
        return $price;

    }

    public function getAddDiscountAdditionAllPrice($price, $product) {
//        $product = $this->getProductById($productId);
        $priceDiscount = $price;
        $customerGroup = $this->getCustomerGroup();
        if($customerGroup > 1) {
            if($product) {
                $discount = $product->getData('pcto_discount');
                if($discount > 0) {
                    $priceDiscount -= ($price * $discount) / 100;
                }
            }
        }

        return $priceDiscount;
    }

    /**
     * @param array $parmaOptions
     * @param int $productId
     * @return int
     */
    public function getAdditionalOptionPrice($parmaOptions = [], $productId = 0,$ourprice=0) {
        $collection = $this->getPreviewAdditionalOptions($productId);
        $price = 0;
        if($collection && $collection->getSize() > 0) {
            foreach ($collection as $item) {
                if(in_array($item->getId(), $parmaOptions)) {
                    $dbprice = $item->getData('price');
                    $title = strtolower($item->getData('title'));
                    if(str_contains($title,'5c transparent')){
                        $price+=$ourprice*$dbprice;
                    }
                    else{
                        $price +=$dbprice;
                    }
                }
            }
        }

        return  $price;
    }


    public function checkProductEnable3D($product) {
//        $_product = $this->getProductById($productId);
        $isEnable = false;
        if($product && $product->getData('pcto_is_3d')) {
            $isEnable = true;
        }
        return $isEnable;
    }

    /**
     * @param int $productId
     * @return \Magento\Catalog\Model\Product
     */
    public function getProductById($productId = 0) {
        $product = $this->productFactory->create();
        $this->resProductFactory->create()->load($product, $productId);
        return $product;
    }

    /**
     * @param int $productId
     * @return \Magetop\Advancepreview\Model\ResourceModel\PreviewAdditional\Collection
     */
    public function getPreviewAdditionalOptions($productId = 0) {
        return $this->colPreviewAdditionalFactory->create()
            ->addFieldToSelect(array('*'))
            ->addFieldToFilter('product_id',$productId);
    }

    /**
     * @return int
     */
    public function getCustomerGroup() {
        $group = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();
            $customer = $this->customerFactory->create()->load($customerId);
            $group = $customer->getGroupId();

        }
        return $group;
    }

    /**
     * @param array $tierPriecs
     * @param int $qty
     * @return int|mixed
     */
    public function getTierPriceItemByQty($tierPriecs = [], $qty = 0) {
        $price = 0;
        $lastIndex = count($tierPriecs) ? count($tierPriecs) - 1 : 0;
        $lastItem = isset($tierPriecs[$lastIndex]) ? $tierPriecs[$lastIndex] : [];
        if($lastIndex > 0 && isset($lastItem['price_qty']) && $qty >= $lastItem['price_qty']) {
            $price = $lastItem['price'];
        }
        else {
            for($i = 0; $i < count($tierPriecs); $i++) {
                if($i == 0 && $qty < $tierPriecs[0]['price_qty']) {
                    $price = $tierPriecs[0]['price'];
                    break;
                }
                if($i + 1 < count($tierPriecs)) {
                    $currentTeir = $tierPriecs[$i];
                    $nextTier = $tierPriecs[$i + 1];
                    if($qty >= $currentTeir['price_qty'] && $qty < $nextTier['price_qty']) {
                        $price = $currentTeir['price'];
                        break;
                    }
                }
            }
        }

        return $price;
    }
    public function getTierPriceByProductId($product) {
        $tierPrices = [];
//        $_product = $this->getProductById($productId);
        if($product != null) {
            $tierPrices = $product->getTierPrice();
        }
        return $tierPrices;
    }


    /**
     * @return bool
     */
    protected function checkIsLogin() {
        $isLogin = false;
        if($this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH)) {
            $isLogin = true;
        }
        return $isLogin;
    }

    /**
     * @return array
     */
    public function getCartAjaxUrls() {
        $customPlaceUrl = $this->getUrl('advance_preview/checkout/buyWithout');
        return [
            'place_url'=>$customPlaceUrl,
        ];
    }
    public function getCustomerDefaultAddress() {
        $customerId = $this->getCustomerId();
        $address = [];
        if($customerId > 0) {
            $customer = $this->customerFactory->create()->load($customerId);
            $billingAddressId = $customer->getDefaultBilling();
            $billingAddress = $this->addressFactory->create()->load($billingAddressId);
            $shippingAddressId = $customer->getDefaultShipping();
            $shippingAddress = $this->addressFactory->create()->load($shippingAddressId);
            if($billingAddress != null) {
                $address['billing'] = $billingAddress;
            }
            if($shippingAddress != null) {
                $address['shipping'] = $shippingAddress;
            }
        }
        return $address;


    }
    public function getDailyShippingById($dailyId = 0) {
        if($dailyId > 0) {
            $collection = $this->dailyShippingFactory->create()
                ->addFieldToSelect(array('amount'))
                ->addFieldToFilter('daily_shipping_id',$dailyId);
            return $collection && $collection->getSize() > 0 ? $collection->getFirstItem() : null;
        }
        return  null;
    }
    protected function getCustomerId() {
        $customerId = 0;
        if($this->checkIsLogin()) {
            $customerId =  $this->customerSession->getCustomerId();


        }
        return $customerId;
    }
    public function getCurrentCurrencySymbol()
    {
        $currencyCode = $this->_storeManager->getStore()->getCurrentCurrencyCode();
        $symbols = [
            'USD'=>'$',
            'EUR'=>'€',
        ];
        return isset($symbols[$currencyCode]) ? $symbols[$currencyCode] : '$';
    }


}
