<?php
/**
 * @author Amasty Team
 * @copyright Copyright (c) 2021 Amasty (https://www.amasty.com)
 * @package Amasty_ReviewersDiscounts
 */


declare(strict_types=1);

namespace Amasty\ReviewersDiscounts\Model\Condition;

use Amasty\ReviewersDiscounts\Model\ResourceModel\Review as ReviewResource;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Model\AbstractModel;
use Magento\Rule\Model\Condition\AbstractCondition;
use Magento\Rule\Model\Condition\Context;

class ApprovedReviewsQty extends AbstractCondition
{
    /**
     * @var ReviewResource
     */
    private $reviewResource;

    /**
     * @var AbstractElement
     */
    private $valueElement;

    public function __construct(
        ReviewResource $reviewResource,
        Context $context,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->reviewResource = $reviewResource;
    }

    /**
     * @param AbstractModel $model
     * @return bool
     */
    public function validate(AbstractModel $model)
    {
        $result = false;
        $customerId = $model->getQuote() ? $model->getQuote()->getCustomerId() : $model->getCustomerId();
        if ($customerId) {
            $result = $this->validateAttribute($this->reviewResource->getTotalReviews($customerId));
        }

        return $result;
    }

    /**
     * Render element HTML
     *
     * @return string
     */
    public function asHtml()
    {
        $this->valueElement = $this->getValueElement();
        return $this->getTypeElementHtml()
            . __(
                'Quantity of approved reviews by Registered Customer %1 %2',
                $this->getOperatorElementHtml(),
                $this->valueElement->getHtml()
            )
            . $this->getRemoveLinkHtml();
    }

    /**
     * Value element type getter
     *
     * @return string
     */
    public function getValueElementType()
    {
        return 'text';
    }

    /**
     * Specify allowed comparison operators
     *
     * @return $this
     */
    public function loadOperatorOptions()
    {
        parent::loadOperatorOptions();
        $this->setOperatorOption(
            [
                '==' => __('is'),
                '>=' => __('equals or greater than'),
                '<=' => __('equals or less than'),
                '>' => __('greater than'),
                '<' => __('less than')
            ]
        );

        return $this;
    }
}
