<?php

declare(strict_types=1);

namespace SmsNotifier\Facade;

use SmsNotifier\Data\NotificationData;
use SmsNotifier\Data\PluginData;
use SmsNotifier\Factory\MessageTextFactory;
use SmsNotifier\Service\Logger;
use SmsNotifier\Service\OptionsManager;
use SmsNotifier\Service\SmsNumberProvider;
use Twilio\Rest\Client;
use Ubnt\UcrmPluginSdk\Service\UcrmApi;
use GuzzleHttp\Client as GuzzleClient;
use GuzzleHttp\Exception\GuzzleException;


use Ubnt\UcrmPluginSdk\Service\PluginConfigManager;

class PluginNotifierFacade extends AbstractStripeOperationsFacade
{
    /**
     * @var Client
     */
    private $twilioClient;

    /**
     * @var PluginData
     */
    private $pluginData;

    public function __construct(
        Logger $logger,
        MessageTextFactory $messageTextFactory,
        SmsNumberProvider $smsNumberProvider,
        OptionsManager $optionsManager
    ) {
        parent::__construct($logger, $messageTextFactory, $smsNumberProvider);
        // load config data
        $this->pluginData = $optionsManager->load();
    }

    public function updatePasswordAntenaIfNeeded(int $clientId, array $jsonData): void
    {
        $this->logger->info("Iniciando verificación/sincronización de contraseña para el cliente ID: $clientId");
        // El método base getVaultCredentialsByClientId ya incluye la lógica para:
        // 1. Obtener la contraseña desde el Vault de UISP (iterando sobre dispositivos).
        // 2. Compararla con el atributo 'passwordAntenaCliente' del CRM.
        // 3. Actualizar el CRM si está vacío o si es diferente.
        $this->getVaultCredentialsByClientId($clientId);
    }

    /**
     * Procesar la lógica de corrección de contraseña cuando se detecta la etiqueta "OBTENER PASSWORD ANTENA".
     * Reutiliza la lógica del script audit_client_passwords.php.
     */
    public function processClientPasswordAntenna(int $clientId, array $clientEntity): void
    {
        $this->logger->info("Procesando etiqueta OBTENER PASSWORD ANTENA para cliente $clientId");

        // 1. Define constant to prevent script execution when including
        if (!defined('INCLUDED_AS_LIBRARY')) {
            define('INCLUDED_AS_LIBRARY', true);
        }

        // 2. Include the script functions
        $scriptPath = __DIR__ . '/../../scripts-uisp/audit_client_passwords.php';
        if (file_exists($scriptPath)) {
            require_once $scriptPath;
        } else {
            $this->logger->error("No se encontró el script de auditoría en: $scriptPath");
            return;
        }

        // 3. Initialize Config & UNMS Client
        // Note: $this->ucrmApi is already available from parent class.
        $ucrmConfig = PluginConfigManager::create()->loadConfig();
        $ipServer = $ucrmConfig['ipserver'] ?? 'localhost';

        $unmsToken = $ucrmConfig['unmsApiToken'] ?? $this->pluginData->unmsAppToken ?? '';

        if (empty($unmsToken)) {
            $this->logger->error("UNMS API Token is missing. Cannot proceed with password fix.");
            return;
        }

        $unmsClientInstance = new GuzzleClient([
            'base_uri' => "https://{$ipServer}/nms/api/v2.1/",
            'verify' => false,
            'headers' => [
                'X-Auth-Token' => $unmsToken
            ]
        ]);

        // 4. Resolve Attributes
        // Use global function from script
        $attributeIds = \resolveAttributeIds($this->ucrmApi, 'passwordAntenaCliente', 'site', 'antenaSectorial');
        if (!$attributeIds) {
            $this->logger->error("Could not resolve attributes for password fix.");
            return;
        }

        // 5. Get current password
        $currentPassword = null;
        foreach ($clientEntity['attributes'] ?? [] as $attr) {
            if ($attr['key'] === 'passwordAntenaCliente') {
                $currentPassword = $attr['value'];
                break;
            }
        }

        // 6. Fix Data
        try {
            $fixResult = \fixClientData($clientId, $this->ucrmApi, $unmsClientInstance, $attributeIds, $ucrmConfig, $currentPassword, $this->logger);
            $this->logger->info("Password fix result for client $clientId: " . json_encode($fixResult));
            
            $passwordVal = $fixResult['password'] ?? '';
            if (stripos($passwordVal, 'Error') !== false || stripos($passwordVal, '⚠️') !== false) {
                $this->logger->error("Fallo detectado al obtener la contraseña de la antena del cliente $clientId: $passwordVal");
            }
        } catch (\Exception $e) {
            $this->logger->error("Error executing fixClientData: " . $e->getMessage());
        }

        // 7. Remove Tag
        // Reuse parent method
        $this->removeTagFromClient($clientId, 'OBTENER PASSWORD ANTENA');
    }


    /*
     * Implementation of abstract method from AbstractStripeOperationsFacade
     */

    /*
     * Implementation of abstract method from AbstractStripeOperationsFacade
     */
    protected function sendWhatsApp(NotificationData $notificationData, string $clientPhoneNumber): void
    {
        $this->logger->info("PluginNotifierFacade: Enviando WhatsApp (Mock): " . $clientPhoneNumber);
    }

    /*
     * Phone number of sender - required by Twilio. In this plugin, we only load it from config.
     */
    private function getSenderNumber(): string
    {
        return $this->pluginData->twilioSmsNumber ?? '';
    }
}
