<?php
/**
 * Sistema de Licencias para PulseGrid Theme
 * Validación remota contra servidor de licencias
 */

if (!defined('ABSPATH')) exit;

// Cargar configuración
require_once get_template_directory() . '/inc/license-config.php';

class PulseGrid_Theme_License {
    
    private static $instance = null;
    private $product_name = PULSEGRID_PRODUCT_NAME;
    private $license_server = PULSEGRID_LICENSE_SERVER;
    // Ofuscar nombres de opciones para evitar anulaciones triviales por búsqueda.
    private $license_option = 'pg_'.'thm'.'_lcns';
    private $license_status_option = 'pg_'.'thm'.'_lcns_stt';
    
    public static function get_instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    private function __construct() {
        add_action('admin_init', array($this, 'redirect_legacy_license_page'));
        add_action('admin_init', array($this, 'restrict_theme_settings'));
        add_action('admin_init', array($this, 'check_license_status'));
        add_action('admin_enqueue_scripts', array($this, 'enqueue_assets'));
        add_action('wp_ajax_pulsegrid_theme_activate_license', array($this, 'ajax_activate_license'));
        add_action('wp_ajax_pulsegrid_theme_deactivate_license', array($this, 'ajax_deactivate_license'));
        add_action('admin_notices', array($this, 'license_notice'));
        add_action('wp_footer', array($this, 'frontend_license_notice'));
    }

    public function redirect_legacy_license_page() {
        if (!is_admin() || !isset($_GET['page']) || $_GET['page'] !== 'pulsegrid-license') {
            return;
        }

        wp_safe_redirect(admin_url('admin.php?page=pulsegrid&tab=licencia'));
        exit;
    }

    public function restrict_theme_settings() {
        if (!is_admin() || !isset($_GET['page']) || $_GET['page'] !== 'pulsegrid') {
            return;
        }

        $active_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : 'slider';

        if ($active_tab === 'licencia') {
            return;
        }

        if (!$this->is_license_valid()) {
            wp_safe_redirect(admin_url('admin.php?page=pulsegrid&tab=licencia'));
            exit;
        }
    }

    public function get_license_data() {
        $license_key = get_option($this->license_option, '');
        if (empty($license_key)) {
            $license_key = get_option('pulsegrid_theme_license', '');
        }

        $license_status = get_option($this->license_status_option, array());
        if (empty($license_status)) {
            $license_status = get_option('pulsegrid_theme_license_status', array());
        }

        $is_active = isset($license_status['valid']) && $license_status['valid'];

        return compact('license_key', 'license_status', 'is_active');
    }

    public function render_license_panel() {
        $data = $this->get_license_data();
        $license_key = $data['license_key'];
        $license_status = is_array($data['license_status']) ? $data['license_status'] : array();
        $is_active = $data['is_active'];
        $has_key = !empty($license_key);
        $can_manage = current_user_can('manage_options');
        $product = $this->product_name;
        $site = untrailingslashit(get_site_url());

        $last_check_ts = get_transient('pulsegrid_license_last_check');
        $checked_at = $last_check_ts ? gmdate('Y-m-d H:i', $last_check_ts) . ' UTC' : '—';

        if ($is_active) {
            $badge_class = 'pg-license-badge--ok';
            $badge_text = __('Licencia activa', 'pulsegrid');
        } elseif ($has_key) {
            $badge_class = 'pg-license-badge--warn';
            $badge_text = __('Pendiente o no activada', 'pulsegrid');
        } else {
            $badge_class = 'pg-license-badge--off';
            $badge_text = __('Sin licencia', 'pulsegrid');
        }

        $license_types = array(
            'single' => __('1 Sitio', 'pulsegrid'),
            'multi_5' => __('5 Sitios', 'pulsegrid'),
            'unlimited' => __('Ilimitado', 'pulsegrid'),
        );

        $license_type_label = '—';
        if (!empty($license_status['license_type'])) {
            $license_type_label = $license_types[$license_status['license_type']] ?? $license_status['license_type'];
        }

        $activations_label = '—';
        if (isset($license_status['current_activations'], $license_status['max_activations'])) {
            $max = (int) $license_status['max_activations'];
            $activations_label = (int) $license_status['current_activations'] . ' / ' . ($max === 999999 ? '∞' : $max);
        }

        $expiry_label = !empty($license_status['expiry_date'])
            ? date_i18n(get_option('date_format'), strtotime($license_status['expiry_date']))
            : __('Sin fecha', 'pulsegrid');

        $message_label = !empty($license_status['message']) ? $license_status['message'] : '—';

        include get_template_directory() . '/admin/license-page.php';
    }

    public function enqueue_assets($hook) {
        if ($hook !== 'toplevel_page_pulsegrid') {
            return;
        }

        if (!isset($_GET['tab']) || sanitize_key($_GET['tab']) !== 'licencia') {
            return;
        }

        wp_enqueue_style('pulsegrid-theme-license', get_template_directory_uri() . '/assets/css/license.css', array('pulsegrid-admin-panel'), pulsegrid_get_theme_version());
        wp_enqueue_script('pulsegrid-theme-license', get_template_directory_uri() . '/assets/js/license.js', array('jquery'), pulsegrid_get_theme_version(), true);

        wp_localize_script('pulsegrid-theme-license', 'pulsegridThemeLicense', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('pulsegrid_theme_license_nonce'),
            'strings' => array(
                'need_key' => __('Introduce la clave de licencia.', 'pulsegrid'),
                'working' => __('Procesando…', 'pulsegrid'),
                'network' => __('Error de conexión. Inténtalo de nuevo.', 'pulsegrid'),
                'error' => __('No se pudo completar la operación.', 'pulsegrid'),
                'done' => __('Listo', 'pulsegrid'),
                'badge_active' => __('Licencia activa', 'pulsegrid'),
                'badge_pending' => __('Pendiente o no activada', 'pulsegrid'),
                'badge_none' => __('Sin licencia', 'pulsegrid'),
            ),
        ));
    }

    public function check_license_status() {
        $license_key = get_option($this->license_option, '');
        if (empty($license_key)) {
            $license_key = get_option('pulsegrid_theme_license', '');
        }
        
        if (empty($license_key)) {
            update_option($this->license_status_option, array('valid' => false));
            return;
        }
        
        // Verificar cada 12 horas
        $last_check = get_transient('pulsegrid_license_last_check');
        if ($last_check !== false) {
            return;
        }
        
        $validation = $this->validate_license($license_key);
        update_option($this->license_status_option, $validation);
        set_transient('pulsegrid_license_last_check', time(), 12 * HOUR_IN_SECONDS);
    }
    
    public function validate_license($license_key) {
        // Primero intentar validación local si el plugin está instalado
        if (class_exists('WarezDL_License_Manager')) {
            $manager = WarezDL_License_Manager::get_instance();
            return $manager->validate_license($license_key, $this->product_name, get_site_url());
        }
        
        // Si no está instalado localmente, validar contra servidor remoto
        return $this->validate_license_via_api($license_key);
    }
    
    public function validate_license_via_api($license_key) {
        // Construir URL del servidor de licencias
        $api_url = add_query_arg(array(
            'license_key' => $license_key,
            'product_name' => $this->product_name,
            'site_url' => get_site_url()
        ), $this->license_server . '/wp-json/warezdl-license/v1/validate');
        
        // Intentar con wp_remote_get primero
        $response = wp_remote_get($api_url, array(
            'timeout' => 15,
            'sslverify' => false,
            'httpversion' => '1.1',
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));
        
        // Si wp_remote_get falla, intentar con file_get_contents como fallback
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            
            // Intentar método alternativo
            if (ini_get('allow_url_fopen')) {
                $context = stream_context_create(array(
                    'http' => array(
                        'timeout' => 15,
                        'ignore_errors' => true
                    ),
                    'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false
                    )
                ));
                
                $result = @file_get_contents($api_url, false, $context);
                
                if ($result !== false) {
                    $data = json_decode($result, true);
                    if ($data) {
                        return $data;
                    }
                }
            }
            
            // Si ambos métodos fallan, retornar error
            return array(
                'valid' => false,
                'message' => sprintf(
                    __('Error de conexión: %s. Tu hosting puede estar bloqueando conexiones salientes. Contacta con tu proveedor o usa el modo de desarrollo.', 'pulsegrid'),
                    $error_message
                )
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code !== 200) {
            return array(
                'valid' => false,
                'message' => sprintf(
                    __('Error del servidor (código %d). Verifica que el plugin esté activo y la API habilitada en: %s', 'pulsegrid'),
                    $response_code,
                    $this->license_server
                )
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if (empty($data)) {
            return array(
                'valid' => false,
                'message' => __('Respuesta vacía del servidor. Verifica que el plugin esté correctamente instalado.', 'pulsegrid')
            );
        }
        
        return $data;
    }
    
    public function ajax_activate_license() {
        check_ajax_referer('pulsegrid_theme_license_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permisos insuficientes', 'pulsegrid')));
        }
        
        $license_key = sanitize_text_field($_POST['license_key']);
        
        // Validar licencia
        $validation = $this->validate_license($license_key);
        
        // Verificar que la validación no sea null
        if (!is_array($validation) || !isset($validation['valid'])) {
            wp_send_json_error(array('message' => __('Error al validar la licencia. Respuesta inválida del sistema.', 'pulsegrid')));
        }
        
        if (!$validation['valid']) {
            wp_send_json_error(array('message' => $validation['message']));
        }
        
        // Activar licencia
        $activation = $this->activate_license($license_key);
        
        // Verificar que la activación no sea null
        if (!is_array($activation) || !isset($activation['success'])) {
            wp_send_json_error(array('message' => __('Error al activar la licencia. Respuesta inválida del sistema.', 'pulsegrid')));
        }
        
        if ($activation['success']) {
            // Migrar a nuevas claves ofuscadas y limpiar las antiguas
            update_option($this->license_option, $license_key);
            update_option($this->license_status_option, $validation);
            delete_option('pulsegrid_theme_license');
            delete_option('pulsegrid_theme_license_status');
            delete_transient('pulsegrid_license_last_check');
            
            wp_send_json_success(array(
                'message' => __('Licencia activada exitosamente', 'pulsegrid'),
                'license_data' => $validation
            ));
        } else {
            wp_send_json_error(array('message' => $activation['message']));
        }
    }
    
    public function activate_license($license_key) {
        // Primero intentar activación local si el plugin está instalado
        if (class_exists('WarezDL_License_Manager')) {
            $manager = WarezDL_License_Manager::get_instance();
            return $manager->activate_license($license_key, $this->product_name, get_site_url());
        }
        
        // Si no está instalado localmente, activar contra servidor remoto
        return $this->activate_license_via_api($license_key);
    }
    
    public function activate_license_via_api($license_key) {
        // Construir URL del servidor de licencias
        $api_url = add_query_arg(array(
            'license_key' => $license_key,
            'product_name' => $this->product_name,
            'site_url' => get_site_url()
        ), $this->license_server . '/wp-json/warezdl-license/v1/activate');
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 30,
            'sslverify' => false,
            'httpversion' => '1.1',
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Error de conexión con el servidor de licencias', 'pulsegrid')
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $data;
    }
    
    public function ajax_deactivate_license() {
        check_ajax_referer('pulsegrid_theme_license_nonce', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permisos insuficientes', 'pulsegrid')));
        }
        
        $license_key = get_option($this->license_option, '');
        if (empty($license_key)) {
            $license_key = get_option('pulsegrid_theme_license', '');
        }
        
        if (empty($license_key)) {
            wp_send_json_error(array('message' => __('No hay licencia activa', 'pulsegrid')));
        }
        
        $deactivation = $this->deactivate_license($license_key);
        
        if ($deactivation['success']) {
            delete_option($this->license_option);
            delete_option($this->license_status_option);
            delete_option('pulsegrid_theme_license');
            delete_option('pulsegrid_theme_license_status');
            delete_transient('pulsegrid_license_last_check');
            
            wp_send_json_success(array('message' => __('Licencia desactivada', 'pulsegrid')));
        } else {
            wp_send_json_error(array('message' => $deactivation['message']));
        }
    }
    
    public function deactivate_license($license_key) {
        // Primero intentar desactivación local si el plugin está instalado
        if (class_exists('WarezDL_License_Manager')) {
            $manager = WarezDL_License_Manager::get_instance();
            return $manager->deactivate_license($license_key, get_site_url());
        }
        
        // Si no está instalado localmente, desactivar contra servidor remoto
        return $this->deactivate_license_via_api($license_key);
    }
    
    public function deactivate_license_via_api($license_key) {
        // Construir URL del servidor de licencias
        $api_url = add_query_arg(array(
            'license_key' => $license_key,
            'site_url' => get_site_url()
        ), $this->license_server . '/wp-json/warezdl-license/v1/deactivate');
        
        $response = wp_remote_get($api_url, array(
            'timeout' => 30,
            'sslverify' => false,
            'httpversion' => '1.1',
            'headers' => array(
                'Accept' => 'application/json'
            )
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => __('Error de conexión', 'pulsegrid')
            );
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return $data;
    }
    
    public function is_license_valid() {
        // Bypass solo cuando está habilitado explícitamente y bajo filtro (desarrollo controlado)
        $dev_bypass = defined('PULSEGRID_LICENSE_DEV_BYPASS') && PULSEGRID_LICENSE_DEV_BYPASS === true;
        if ($dev_bypass && apply_filters('pulsegrid_theme_license_valid', false)) {
            return true;
        }
        
        $license_status = get_option($this->license_status_option, array());
        return isset($license_status['valid']) && $license_status['valid'];
    }

    public function license_notice() {
        if ($this->is_license_valid()) {
            return;
        }

        $current_page = isset($_GET['page']) ? $_GET['page'] : '';
        $current_tab = isset($_GET['tab']) ? sanitize_key($_GET['tab']) : '';

        if ($current_page === 'pulsegrid' && $current_tab === 'licencia') {
            return;
        }
        
        // Solo mostrar en páginas de PulseGrid o en el dashboard principal
        $screen = get_current_screen();
        if (!$screen) {
            return;
        }
        
        // Mostrar solo en dashboard o páginas de PulseGrid
        $show_notice = false;
        if ($screen->id === 'dashboard' || strpos($screen->id, 'pulsegrid') !== false) {
            $show_notice = true;
        }
        
        if (!$show_notice) {
            return;
        }
        
        ?>
        <div class="notice notice-warning is-dismissible">
            <p>
                <strong><?php _e('PulseGrid Theme:', 'pulsegrid'); ?></strong>
                <?php _e('El tema no tiene una licencia activa. Por favor, activa tu licencia para acceder a todas las funciones del tema.', 'pulsegrid'); ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=licencia')); ?>" class="button button-primary" style="margin-left: 10px;">
                    <?php _e('Activar Licencia', 'pulsegrid'); ?>
                </a>
            </p>
        </div>
        <?php
    }
    
    public function frontend_license_notice() {
        // Solo mostrar si no hay licencia válida
        if ($this->is_license_valid()) {
            return;
        }
        
        ?>
        <div id="pulsegrid-license-notice" style="position: fixed; bottom: 0; left: 0; right: 0; background: linear-gradient(135deg, #3498db 0%, #2980b9 100%); color: #fff; padding: 15px 20px; text-align: center; z-index: 999999; box-shadow: 0 -2px 10px rgba(0,0,0,0.3); font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;">
            <div style="max-width: 1200px; margin: 0 auto; display: flex; align-items: center; justify-content: center; gap: 15px; flex-wrap: wrap;">
                <span style="font-size: 20px;">🔐</span>
                <span style="font-weight: 600; font-size: 15px;">
                    <?php _e('Licencia no activada', 'pulsegrid'); ?>
                </span>
                <span style="font-size: 14px; opacity: 0.95;">
                    <?php _e('Activa tu licencia para ocultar este mensaje y acceder a todas las funciones.', 'pulsegrid'); ?>
                </span>
                <?php if (current_user_can('manage_options')): ?>
                <a href="<?php echo esc_url(admin_url('admin.php?page=pulsegrid&tab=licencia')); ?>" style="background: rgba(255,255,255,0.25); color: #fff; padding: 8px 20px; border-radius: 5px; text-decoration: none; font-weight: 600; font-size: 14px; border: 1px solid rgba(255,255,255,0.3); transition: all 0.3s; display: inline-block;" onmouseover="this.style.background='rgba(255,255,255,0.35)'" onmouseout="this.style.background='rgba(255,255,255,0.25)'">
                    <?php _e('Activar Licencia', 'pulsegrid'); ?>
                </a>
                <?php endif; ?>
            </div>
        </div>
        <style>
            [data-theme="dark"] #pulsegrid-license-notice {
                background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
            }
            @media (max-width: 768px) {
                #pulsegrid-license-notice {
                    padding: 12px 15px;
                }
                #pulsegrid-license-notice > div {
                    font-size: 13px;
                    gap: 10px;
                }
                #pulsegrid-license-notice span {
                    font-size: 13px !important;
                }
                #pulsegrid-license-notice a {
                    font-size: 13px !important;
                    padding: 6px 15px !important;
                }
            }
        </style>
        <?php
    }
    
}

// Inicializar
function pulsegrid_theme_license() {
    return PulseGrid_Theme_License::get_instance();
}

pulsegrid_theme_license();
