<?php

namespace TbiBank\FusionPay\Plugin;

use Magento\Setup\Console\Command\ModuleDisableCommand;
use Magento\Framework\Module\Manager as ModuleManager;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\HTTP\Client\Curl;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use TbiBank\FusionPay\Helper\Data as FusionPayHelper;
use TbiBank\FusionPay\Logger\FusionPayLogger;

class ModuleDisablePlugin
{
    protected $moduleManager;
    protected $scopeConfig;
    protected $curl;
    protected $fusionPayHelper;
    protected $logger;

    public function __construct(
        ModuleManager $moduleManager,
        ScopeConfigInterface $scopeConfig,
        Curl $curl,
        FusionPayHelper $fusionPayHelper,
        FusionPayLogger $logger
    ) {
        $this->moduleManager = $moduleManager;
        $this->scopeConfig = $scopeConfig;
        $this->curl = $curl;
        $this->fusionPayHelper = $fusionPayHelper;
        $this->logger = $logger;
    }

    /**
     * Run this function BEFORE the module disable command is executed
     */
    public function beforeExecute(ModuleDisableCommand $subject, InputInterface $input, OutputInterface $output)
    {
        $this->logger->info('TbiBank_FusionPay module disable command detected BEFORE execution.');
        $this->sendNotification();
        return [$input, $output]; // Return unchanged parameters to allow execution to continue
    }

    /**
     * Send a notification to an external API before module is disabled
     */
    protected function sendNotification()
    {
        $this->logger->info('Sending pre-disable notification for TbiBank_FusionPay module...');

        $tbiEndpointStatus = $this->fusionPayHelper->getConstValue('TBI_PLATFORM_URL') . '/api/PluginsSettings/status';

        $apiData = [
            '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'        => 'disabling', // Indicating that disabling is about to happen
            'date'          => date('Y-m-d H:i:s')
        ];

        // Convert data to JSON
        $jsonData = json_encode($apiData);

        try {
            $this->curl->post($tbiEndpointStatus, $jsonData);
            $response = $this->curl->getBody();
            $this->logger->info('Pre-disable notification sent successfully: ' . $response);
        } catch (\Exception $e) {
            $this->logger->error('Failed to send pre-disable notification: ' . $e->getMessage());
        }
    }
}
