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

namespace WriteTextAI\WriteTextAI\Helper;

use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Framework\DB\Adapter\AdapterInterface;
use Magento\Framework\App\ResourceConnection;

class CronStatus extends AbstractHelper
{
    /** in minutes */
    public const DEFAULT_CRON_MINUTES_CHECK = 1440;

    /**
     * @var AdapterInterface
     */
    protected $connection;

    /**
     * @param Context $context
     * @param ResourceConnection $resourceConnection
     */
    public function __construct(
        Context $context,
        ResourceConnection $resourceConnection
    ) {
        parent::__construct($context);
        $this->connection = $resourceConnection->getConnection();
    }

    /**
     * Returns true if recent cron jobs have run successfully in the last N minutes.
     *
     * @param int $minutes
     * @return bool
     */
    public function isCronRunning($minutes = self::DEFAULT_CRON_MINUTES_CHECK)
    {
        $table = $this->connection->getTableName('cron_schedule');
        $timeLimit = (new \DateTime())->modify("-{$minutes} minutes")->format('Y-m-d H:i:s');

        $select = $this->connection->select()
            ->from($table, ['job_code', 'status', 'executed_at'])
            ->where('executed_at >= ?', $timeLimit)
            ->where('status IN (?)', ['success', 'running'])
            ->order('executed_at DESC')
            ->limit(1);

        $result = $this->connection->fetchRow($select);
        return !empty($result);
    }
}
