<?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_ProductAttachments
 * @copyright   Copyright (c) Mageplaza (https://www.mageplaza.com/)
 * @license     https://www.mageplaza.com/LICENSE.txt
 */

declare(strict_types=1);

namespace Mageplaza\ProductAttachments\Model\Resolver;

use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Mageplaza\ProductAttachments\Model\Api\ProductAttachmentsRepository;
use Mageplaza\ProductAttachments\Helper\Data;
use Magento\Framework\UrlInterface;
use Magento\Customer\Model\Customer;

/**
 * Class LabelRules
 * @package Mageplaza\ProductLabelsGraphQl\Model\Resolver
 */
class AttachmentsDataProvider implements ResolverInterface
{
    /**
     * @var Data
     */
    protected $helperData;

    /**
     * @var ProductAttachmentsRepository
     */
    protected $productAttachment;

    /**
     * @var UrlInterface
     */
    protected $_urlInterface;

    /**
     * @var Customer
     */
    protected $customer;

    /**
     * AttachmentsDataProvider constructor.
     *
     * @param Data $helperData
     * @param ProductAttachmentsRepository $productAttachment
     * @param UrlInterface $urlInterface
     * @param Customer $customer
     */
    public function __construct(
        Data $helperData,
        ProductAttachmentsRepository $productAttachment,
        UrlInterface $urlInterface,
        Customer $customer
    ) {
        $this->helperData        = $helperData;
        $this->productAttachment = $productAttachment;
        $this->_urlInterface     = $urlInterface;
        $this->customer          = $customer;
    }

    /**
     * @inheritdoc
     */
    public function resolve(Field $field, $context, ResolveInfo $info, ?array $value = null, ?array $args = null)
    {
        $storeId = $context->getExtensionAttributes()->getStore()->getId();
        if (!$this->helperData->isEnabled($storeId)) {
            return [];
        }
        if (!array_key_exists('model', $value) || !$value['model'] instanceof ProductInterface) {
            throw new LocalizedException(__('"model" value should be specified'));
        }
        $product         = $value['model'];
        $productId       = $product->getId();
        $attachmentsData = [];
        $customerId      = $context->getUserId();
        $customerGroupId = $customerId ? $this->customer->load($customerId)->getGroupId() : '0';

        $filesList = $this->getMpFileList($product);
        if (count($filesList)) {
            foreach ($filesList as $file) {
                $customerGroups = explode(',', $file->getCustomerGroup() ?: '');
                if (in_array($customerGroupId, $customerGroups)) {
                    $urlFile = '';
                    $note    = 'Login required';
                    if (!$file->getCustomerLogin() || $customerId) {
                        if ($this->isPurchased(
                            $file->getIsBuyer(),
                            $file->getOrderStatuses(),
                            $productId,
                            $customerId
                        )) {

                            if ($file->getType() == '0') {
                                $filePatch = $this->helperData->getFileUrl($file->getFilePath());
                                $urlFile   = $file->getFilePath() ? $this->_urlInterface->getUrl($filePatch) : '';
                            } else {
                                $urlFile = $file->getFilePath() ?: '';
                            }

                            $note = '';
                        } else {
                            $note = 'Purchase required';
                        }
                    }

                    $attachmentsData[] = [
                        'file_label' => $file->getLabel(),
                        'file_name'  => $file->getName(),
                        'file_icon'  => $file->getFileIconPath()
                            ? $this->helperData->getImageUrl($file->getFileIconPath()) : $this->helperData->getDefaultIconUrl(),
                        'url_file'   => $urlFile,
                        'note'       => $note,
                        'group'      => $this->getGroupAttachment($file, $storeId),
                        'file_size'  => $file->getType() == '0' ? $this->helperData->fileSizeFormat($file->getSize()) : ''
                    ];
                }
            }
        }

        return $attachmentsData;
    }

    /**
     * @param $product
     *
     * @return array
     */
    public function getMpFileList($product)
    {
        $files = [];

        $fileCollection = $this->helperData->getFileByProduct($product->getId());
        $fileRules = $this->getFileRuleList($product);
        foreach ($fileCollection->getItems() as $file) {
            $files[]    = $file;
        }
        foreach ($fileRules as $file) {
            $files[]    = $file;
        }

        return $files;
    }

    /**
     * @param $product
     *
     * @return array
     */
    public function getFileRuleList($product)
    {
        /** if the product use the current rules */
        $fileInRule = [];

        if ($product !== null) {
            $fileCollection = $this->helperData->getFileByRule();
            foreach ($fileCollection as $file) {
                if ($file->getConditions()->validate($product)) {
                    $fileInRule[] = $file;
                }
            }
        }

        return $fileInRule;
    }

    /**
     * @param $fileIsBuyer
     * @param $orderStatuses
     * @param $productId
     * @param $customerId
     *
     * @return bool
     */
    public function isPurchased($fileIsBuyer, $orderStatuses, $productId, $customerId)
    {
        if (!$fileIsBuyer || !$customerId) {
            return true;
        }
        if ($fileIsBuyer && empty($orderStatuses)) {
            return false;
        }

        $collection = $this->helperData->getPurchasedOrderWithProduct(
            $customerId,
            $productId,
            $orderStatuses,
            $this->helperData->getStoreId()
        );

        if ($collection->getSize()) {
            return true;
        }

        return false;
    }

    /**
     * @param $file
     * @param $storeId
     *
     * @return array
     */
    public function getGroupAttachment($file, $storeId)
    {
        $groupsData = [];
        $groups     = $this->helperData->jsonDecode($this->helperData->getConfigGeneral('groups', $storeId));
        if (count($groups)) {
            foreach ($groups['option']['value'] as $value => $group) {
                if ($file->getGroup() == $group['value']) {
                    $groupsData = [
                        'value'    => $group['value'],
                        'name'     => $group['name'],
                        'position' => $group['position']
                    ];
                }
            }
        }

        return $groupsData;
    }
}
