<?php

namespace TbiBank\FusionPay\Cron;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\Module\ModuleListInterface;
use Magento\Framework\HTTP\Client\Curl;
use Psr\Log\LoggerInterface;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;
use TbiBank\FusionPay\Logger\FusionPayLogger;



class CheckModuleStatus
{
    protected $moduleList;
    protected $scopeConfig;
    protected $curl;
    protected $logger;
    protected $lastKnownStatus;
 /**
     * @var FusionPayHelper
    */
    protected $fusionPayHelper;

    /**
     * @var FusionPayLogger
    */
    protected $fusionPayLogger; // Custom Logger
    public function __construct(
        ModuleListInterface $moduleList,
        ScopeConfigInterface $scopeConfig,
        Curl $curl,
        LoggerInterface $logger,
        FusionPayHelper $fusionPayHelper,
        FusionPayLogger $fusionPayLogger

    ) {
        $this->moduleList = $moduleList;
        $this->scopeConfig = $scopeConfig;
        $this->curl = $curl;
        $this->logger = $logger;
        $this->lastKnownStatus = BP . '/var/fusionpay_status.txt'; // Store the last known status`
        $this->fusionPayHelper = $fusionPayHelper;
        $this->fusionPayLogger = $fusionPayLogger;
    }

    public function execute()
    {
        $isModuleEnabled = $this->moduleList->has('TbiBank_FusionPay'); // Check if module exists in module list
        $isPaymentEnabled = $this->scopeConfig->isSetFlag(
            'payment/fusionpay/active',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );

        $currentStatus = $isModuleEnabled && $isPaymentEnabled ? 'enabled' : 'disabled';

        // Check the last known status from the stored file
        $lastStatus = $this->getLastKnownStatus();

        // If the status changed to "disabled", send notification
        if ($lastStatus !== $currentStatus) {
            $this->setLastKnownStatus($currentStatus);
            $this->notifyEndpoint($currentStatus);
        }
    }

    private function getLastKnownStatus()
    {
        if (file_exists($this->lastKnownStatus)) {
            return trim(file_get_contents($this->lastKnownStatus));
        }
        return 'enabled'; // Assume enabled by default
    }

    private function setLastKnownStatus($status)
    {
        file_put_contents($this->lastKnownStatus, $status);
    }

    private function notifyEndpoint($currentStatus)
    {
        try {
            $endpointUrl = $this->fusionPayHelper->getConstValue('TBI_PLATFORM_URL') . '/api/PluginsSettings/status';

            $payload = json_encode([
                'reseller_code' => $this->fusionPayHelper->getConfigValue('tbi_settings/general_settings/reseller_code'),
                'reseller_key'  => $this->fusionPayHelper->getConfigValue('tbi_settings/general_settings/reseller_key'),
                'plugin'        => 'Magento2',
                'version'       => '1.5',
                'status'        => $currentStatus,
                'date'          => date('Y-m-d H:i:s')
            ]);

            $this->curl->setHeaders([
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ]);
            $this->curl->post($endpointUrl, $payload);
            $response = $this->curl->getBody();

            $this->fusionPayLogger->info('FusionPay notification sent: ' . $response);
        } catch (\Exception $e) {
            $this->fusionPayLogger->error('FusionPay notification failed: ' . $e->getMessage());
        }
    }
}
