<?php
/**
 * @author 1902 Software
 * @copyright Copyright © 2023 1902 Software (https://1902software.com/magento/)
 * @package WriteTextAI_WriteTextAI
 */

namespace WriteTextAI\WriteTextAI\Block\Adminhtml\System\Config\Field;

use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Backend\Block\Template\Context;
use Magento\Framework\View\Helper\SecureHtmlRenderer;
use WriteTextAI\WriteTextAI\Helper\CronStatus;
use WriteTextAI\WriteTextAI\Helper\Data as HelperData;

class AutoTransfer extends Field
{
    /**
     * @var CronStatus
     */
    protected $cronStatus;

    /**
     * @var HelperData
     */
    protected $helperData;

    /**
     * @param Context $context
     * @param CronStatus $cronStatus
     * @param HelperData $helperData
     * @param array $data
     * @param SecureHtmlRenderer|null $secureRenderer
     */
    public function __construct(
        Context $context,
        CronStatus $cronStatus,
        HelperData $helperData,
        array $data = [],
        ?SecureHtmlRenderer $secureRenderer = null
    ) {
        $this->cronStatus = $cronStatus;
        $this->helperData = $helperData;
        parent::__construct(
            $context,
            $data,
            $secureRenderer
        );
    }

    /**
     * @inheritdoc
     */
    protected function _getElementHtml(AbstractElement $element)
    {
        if (!$this->cronStatus->isCronRunning(CronStatus::DEFAULT_CRON_MINUTES_CHECK)) {
            $element->setDisabled(true);
            $element->setData('comment', $this->getCronJobDisabledAutoTransferMessage());
            $html = parent::_getElementHtml($element);
            return $html;
        }
        $element->setData(
            'comment',
            $this->helperData->getConfigTimezone() . ' (' . $this->helperData->getFormattedTimezone() . ')'
        );
        return parent::_getElementHtml($element);
    }

    /**
     * Get cron job disabled message
     *
     * @return string
     */
    public function getCronJobDisabledAutoTransferMessage()
    {
        $html = '';
        $html .= '<span style="color: #C35F5F;">'
            . __('Website cron jobs have been disabled.'
                . ' This setting requires a cron job to function properly.'
                . ' Please enable it to ensure proper operation.'
                . ' You may need to contact your hosting provider or developer regarding this.')
            . '</span>';
        return $html;
    }
}
