<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

class MasterPanelService
{
    protected $baseUrl;
    protected $licenseKey;
    protected $apiKey;
    protected $apiSecret;

    public function __construct()
    {
        $this->baseUrl = rtrim(config('services.master_panel.url', env('MASTER_PANEL_URL')), '/');
        $this->licenseKey = config('services.master_panel.license_key', env('MASTER_PANEL_LICENSE_KEY'));
        $this->apiKey = config('services.master_panel.api_key', env('MASTER_PANEL_API_KEY'));
        $this->apiSecret = config('services.master_panel.api_secret', env('MASTER_PANEL_API_SECRET'));
    }

    /**
     * Validar licença com o Master Panel
     *
     * @param string|null $licenseKey
     * @return array
     */
    public function validateLicense($licenseKey = null)
    {
        $licenseKey = $licenseKey ?? $this->licenseKey;

        if (!$licenseKey) {
            return [
                'valid' => false,
                'message' => 'License key não configurada'
            ];
        }

        // Cache por 5 minutos
        $cacheKey = "master_license_{$licenseKey}";
        
        return Cache::remember($cacheKey, 300, function () use ($licenseKey) {
            try {
                $url = $this->baseUrl . '/api/v1/validate-license.php';
                
                $response = Http::timeout(10)
                    ->get($url, [
                        'license_key' => $licenseKey,
                        'domain' => request()->getHost(),
                        'ip' => request()->ip()
                    ]);

                if ($response->successful()) {
                    $data = $response->json();
                    
                    if (isset($data['success']) && $data['success']) {
                        return [
                            'valid' => true,
                            'license' => $data['license'] ?? [],
                            'client' => $data['license']['client'] ?? [],
                            'plugins' => $data['license']['client']['plan']['premium_plugins'] ?? []
                        ];
                    } else {
                        return [
                            'valid' => false,
                            'message' => $data['message'] ?? 'Licença inválida'
                        ];
                    }
                } else {
                    return [
                        'valid' => false,
                        'message' => 'Erro ao comunicar com Master Panel: HTTP ' . $response->status()
                    ];
                }
            } catch (\Exception $e) {
                Log::error('Master Panel validation error', [
                    'error' => $e->getMessage()
                ]);

                return [
                    'valid' => false,
                    'message' => 'Erro ao validar licença: ' . $e->getMessage()
                ];
            }
        });
    }

    /**
     * Buscar plugins habilitados para esta licença
     *
     * @return array
     */
    public function getEnabledPlugins()
    {
        $validation = $this->validateLicense();
        
        if (!$validation['valid']) {
            return [];
        }

        return $validation['plugins'] ?? [];
    }

    /**
     * Verificar se plugin está habilitado
     *
     * @param string $pluginKey
     * @return bool
     */
    public function isPluginEnabled($pluginKey)
    {
        $plugins = $this->getEnabledPlugins();
        
        if (empty($plugins)) {
            return false;
        }

        // Plugins podem vir como array de strings ou array de objetos
        if (is_array($plugins)) {
            foreach ($plugins as $plugin) {
                if (is_string($plugin) && $plugin === $pluginKey) {
                    return true;
                }
                if (is_array($plugin) && ($plugin['key'] ?? $plugin['slug'] ?? null) === $pluginKey) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Verificar status da licença (ativa/expirada/suspensa)
     *
     * @return array
     */
    public function getLicenseStatus()
    {
        $validation = $this->validateLicense();
        
        if (!$validation['valid']) {
            return [
                'status' => 'invalid',
                'message' => $validation['message'] ?? 'Licença inválida'
            ];
        }

        $license = $validation['license'] ?? [];
        $expiresAt = $license['expires_at'] ?? null;

        if ($expiresAt) {
            $expires = \Carbon\Carbon::parse($expiresAt);
            if ($expires->isPast()) {
                return [
                    'status' => 'expired',
                    'expires_at' => $expiresAt,
                    'message' => 'Licença expirada em ' . $expires->format('d/m/Y H:i')
                ];
            }
        }

        return [
            'status' => 'active',
            'expires_at' => $expiresAt,
            'client' => $validation['client'] ?? []
        ];
    }

    /**
     * Limpar cache de validação
     *
     * @param string|null $licenseKey
     * @return void
     */
    public function clearCache($licenseKey = null)
    {
        $licenseKey = $licenseKey ?? $this->licenseKey;
        $cacheKey = "master_license_{$licenseKey}";
        Cache::forget($cacheKey);
    }
}
