<?php
/**
 * License Admin Page for BotFend Pro
 *
 * @package BotFend\Admin\Pages
 * @since 4.9.0
 */

namespace BotFend\Admin\Pages;

use BotFend\License\LicenseKey;

defined('ABSPATH') || exit;

class LicensePage {
    
    private $license;
    
    public function __construct() {
        $this->license = LicenseKey::get_instance();
        add_action('admin_init', [$this, 'process_forms']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }
    
    /**
     * Enqueue assets for license page - WordPress compliant
     */
    public function enqueue_assets(string $hook): void {
        if (strpos($hook, 'botfend-license') === false) {
            return;
        }

        wp_enqueue_style(
            'botfend-license-css',
            BOTFEND_ASSETS_URL . 'css/license.css',
            ['botfend-admin-css'],
            BOTFEND_VERSION
        );

        wp_enqueue_script(
            'botfend-license-js',
            BOTFEND_ASSETS_URL . 'js/license.js',
            ['jquery'],
            BOTFEND_VERSION,
            true
        );

        wp_localize_script('botfend-license-js', 'botfendLicense', [
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('botfend_license_nonce'),
            'i18n'    => [
                'deactivate_confirm' => esc_html__('Deactivate license on this site? You will lose access to Pro features.', 'botfend-anti-bot-firewall'),
                'activating'         => esc_html__('Activating license...', 'botfend-anti-bot-firewall'),
                'deactivating'       => esc_html__('Deactivating license...', 'botfend-anti-bot-firewall'),
                'success'            => esc_html__('Success!', 'botfend-anti-bot-firewall'),
                'error'              => esc_html__('An error occurred. Please try again.', 'botfend-anti-bot-firewall'),
            ],
        ]);
    }
    
    /**
     * Process license form submissions
     */
    public function process_forms(): void {
        if (!isset($_POST['botfend_license_nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['botfend_license_nonce'])), 'botfend_license_action')) {
            return;
        }

        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_POST['botfend_activate_license'])) {
            $this->process_activation();
        } elseif (isset($_POST['botfend_deactivate_license'])) {
            $this->process_deactivation();
        }
    }
    
    /**
     * Process license activation
     */
    private function process_activation(): void {
        if (empty($_POST['botfend_license_key'])) {
            add_settings_error(
                'botfend_license',
                'empty_key',
                esc_html__('Please enter a license key.', 'botfend-anti-bot-firewall'),
                'error'
            );
            return;
        }

        $license_key = sanitize_text_field(wp_unslash($_POST['botfend_license_key']));
        $result = $this->license->activate($license_key);

        if ($result['success']) {
            add_settings_error(
                'botfend_license',
                'license_activated',
                esc_html($result['message']),
                'success'
            );
        } else {
            add_settings_error(
                'botfend_license',
                'license_invalid',
                esc_html($result['message']),
                'error'
            );
        }
    }
    
    /**
     * Process license deactivation
     */
    private function process_deactivation(): void {
        $result = $this->license->deactivate();

        if ($result['success']) {
            add_settings_error(
                'botfend_license',
                'license_deactivated',
                esc_html($result['message']),
                'success'
            );
        } else {
            add_settings_error(
                'botfend_license',
                'deactivation_failed',
                esc_html__('Failed to deactivate license.', 'botfend-anti-bot-firewall'),
                'error'
            );
        }
    }
    
    /**
     * Render license page
     */
    public function render(): void {
        if (!current_user_can('manage_options')) {
            wp_die(esc_html__('You do not have sufficient permissions to access this page.', 'botfend-anti-bot-firewall'));
        }
        
        $license_key = get_option('botfend_license_key', '');
        $is_valid = $this->license->is_valid();
        $status_text = $this->license->get_status_text();
        $license_data = $this->license->get_license_data();
        $days_left = $this->license->days_remaining();
        ?>
        <div class="wrap">
            <h1>
                <?php echo esc_html__('BotFend Pro License', 'botfend-anti-bot-firewall'); ?>
                <?php if ($is_valid) : ?>
                    <span class="botfend-pro-badge"><?php echo esc_html__('ACTIVE', 'botfend-anti-bot-firewall'); ?></span>
                <?php endif; ?>
            </h1>
            
            <?php settings_errors('botfend_license'); ?>
            
            <div class="botfend-license-container">
                <?php if ($is_valid) : ?>
                    <!-- Active License Card -->
                    <div class="botfend-license-card active">
                        <div class="botfend-license-icon">
                            <span class="dashicons dashicons-yes-alt"></span>
                        </div>
                        <div class="botfend-license-content">
                            <h2><?php echo esc_html__('License Active', 'botfend-anti-bot-firewall'); ?></h2>
                            <p class="botfend-license-status"><?php echo esc_html($status_text); ?></p>
                            
                            <?php if ($days_left > 0 && $days_left <= 14) : ?>
                                <div class="botfend-renewal-notice">
                                    <span class="dashicons dashicons-warning"></span>
                                    <strong><?php echo esc_html__('Renewal Reminder:', 'botfend-anti-bot-firewall'); ?></strong>
                                    <?php
                                    /* translators: %d: number of days until license expires */
                                    printf(esc_html__('Your license will expire in %d days. Renew now to continue receiving updates and support.', 'botfend-anti-bot-firewall'), absint($days_left));
                                    ?>
                                </div>
                            <?php endif; ?>
                            
                            <div class="botfend-license-details">
                                <h3><?php echo esc_html__('License Details', 'botfend-anti-bot-firewall'); ?></h3>
                                <table>
                                    <tr>
                                        <th><?php echo esc_html__('License Key', 'botfend-anti-bot-firewall'); ?></th>
                                        <td><code><?php echo esc_html(substr($license_key, 0, 15) . '********'); ?></code></td>
                                    </tr>
                                    <tr>
                                        <th><?php echo esc_html__('Customer Email', 'botfend-anti-bot-firewall'); ?></th>
                                        <td><?php echo esc_html($license_data['email'] ?? esc_html__('N/A', 'botfend-anti-bot-firewall')); ?></td>
                                    </tr>
                                    <tr>
                                        <th><?php echo esc_html__('License Type', 'botfend-anti-bot-firewall'); ?></th>
                                        <td>
                                            <?php 
                                            if (isset($license_data['max_sites'])) {
                                                if ($license_data['max_sites'] >= 999) {
                                                    echo esc_html__('Unlimited Sites', 'botfend-anti-bot-firewall');
                                                } else {
                                                    /* translators: %d: number of licensed sites */
                                                    printf(esc_html__('%d Sites', 'botfend-anti-bot-firewall'), absint($license_data['max_sites']));
                                                }
                                            } else {
                                                echo esc_html__('Single Site', 'botfend-anti-bot-firewall');
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                    <tr>
                                        <th><?php echo esc_html__('Expires', 'botfend-anti-bot-firewall'); ?></th>
                                        <td>
                                            <?php 
                                            if ($license_data['expires'] === 'never') {
                                                echo '<strong style="color: #46b450;">' . esc_html__('Never', 'botfend-anti-bot-firewall') . '</strong>';
                                            } else {
                                                $expiry_class = $days_left <= 7 ? 'color: #dc3232;' : '';
                                                echo '<span style="' . esc_attr($expiry_class) . '">';
                                                echo esc_html($license_data['expires']) . ' (';
                                                /* translators: %d: number of days remaining */
                                                printf(esc_html__('%d days left', 'botfend-anti-bot-firewall'), absint($days_left));
                                                echo ')';
                                                echo '</span>';
                                            }
                                            ?>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                            
                            <div class="botfend-license-details">
                                <h3>
                                    <?php echo esc_html__('Pro Features Included', 'botfend-anti-bot-firewall'); ?>
                                    <span class="botfend-feature-subtitle">(<?php echo esc_html__('Active', 'botfend-anti-bot-firewall'); ?>)</span>
                                </h3>
                                <div class="botfend-feature-grid">
                                    <?php 
                                    $all_features = [
                                        'cloudflare'       => esc_html__('Cloudflare Integration', 'botfend-anti-bot-firewall'),
                                        'geolocation'      => esc_html__('IP Geolocation API', 'botfend-anti-bot-firewall'),
                                        'threat_intel'     => esc_html__('Advanced Threat Intelligence', 'botfend-anti-bot-firewall'),
                                        'firewall'         => esc_html__('Full Firewall Protection', 'botfend-anti-bot-firewall'),
                                        'waf'              => esc_html__('Advanced WAF Rules', 'botfend-anti-bot-firewall'),
                                        'priority_support' => esc_html__('Priority Support', 'botfend-anti-bot-firewall'),
                                    ];
                                    
                                    $active_features = $license_data['features'] ?? ['cloudflare', 'geolocation', 'threat_intel'];
                                    
                                    foreach ($all_features as $key => $label):
                                        $is_active = in_array($key, $active_features, true);
                                    ?>
                                        <div class="botfend-feature-item <?php echo $is_active ? 'active' : 'inactive'; ?>">
                                            <?php if ($is_active): ?>
                                                <span class="dashicons dashicons-yes-alt"></span>
                                                <strong><?php echo esc_html($label); ?></strong>
                                            <?php else: ?>
                                                <span class="dashicons dashicons-lock"></span>
                                                <span><?php echo esc_html($label); ?></span>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                            
                            <form method="post" action="">
                                <?php wp_nonce_field('botfend_license_action', 'botfend_license_nonce'); ?>
                                <button type="submit" name="botfend_deactivate_license" class="button button-secondary button-large" onclick="return confirm(botfendLicense.i18n.deactivate_confirm);">
                                    <span class="dashicons dashicons-no-alt"></span>
                                    <?php echo esc_html__('Deactivate License', 'botfend-anti-bot-firewall'); ?>
                                </button>
                            </form>
                        </div>
                    </div>
                    
                <?php else : ?>
                    <!-- Inactive License Card -->
                    <div class="botfend-license-card inactive">
                        <div class="botfend-license-icon">
                            <span class="dashicons dashicons-lock"></span>
                        </div>
                        <div class="botfend-license-content">
                            <h2><?php echo esc_html__('Activate BotFend Pro', 'botfend-anti-bot-firewall'); ?></h2>
                            <p><?php echo esc_html__('Enter your license key to unlock Pro features:', 'botfend-anti-bot-firewall'); ?></p>
                            
                            <div class="botfend-feature-grid">
                                <?php
                                $pro_features = [
                                    'cloudflare'   => ['icon' => 'cloud', 'label' => esc_html__('Cloudflare Integration', 'botfend-anti-bot-firewall')],
                                    'geolocation'  => ['icon' => 'location-alt', 'label' => esc_html__('IP Geolocation API', 'botfend-anti-bot-firewall')],
                                    'threat_intel' => ['icon' => 'shield-alt', 'label' => esc_html__('Advanced Threat Intelligence', 'botfend-anti-bot-firewall')],
                                    'firewall'     => ['icon' => 'shield', 'label' => esc_html__('Full Firewall Protection', 'botfend-anti-bot-firewall')],
                                    'waf'          => ['icon' => 'chart-line', 'label' => esc_html__('Advanced WAF Rules', 'botfend-anti-bot-firewall')],
                                    'support'      => ['icon' => 'star-filled', 'label' => esc_html__('Priority Support', 'botfend-anti-bot-firewall')],
                                ];
                                foreach ($pro_features as $feature):
                                ?>
                                    <div class="botfend-feature-item">
                                        <span class="dashicons dashicons-<?php echo esc_attr($feature['icon']); ?>"></span>
                                        <strong><?php echo esc_html($feature['label']); ?></strong>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                            
                            <form method="post" action="" class="botfend-license-form">
                                <?php wp_nonce_field('botfend_license_action', 'botfend_license_nonce'); ?>
                                <div class="botfend-license-input-group">
                                    <input type="text" 
                                           name="botfend_license_key" 
                                           class="botfend-license-input" 
                                           placeholder="BOTFEND-XXXXX-XXXXX-XXXXX-XXXXX" 
                                           value="<?php echo esc_attr($license_key); ?>"
                                           autocomplete="off">
                                    <button type="submit" name="botfend_activate_license" class="button button-primary button-large">
                                        <span class="dashicons dashicons-yes"></span>
                                        <?php echo esc_html__('Activate License', 'botfend-anti-bot-firewall'); ?>
                                    </button>
                                </div>
                                <p class="description">
                                    <?php echo esc_html__('Your license key was sent to you via email after purchase.', 'botfend-anti-bot-firewall'); ?>
                                </p>
                            </form>
                            
                            <div class="botfend-license-footer">
                                <a href="https://ejesgist.com/developer/" target="_blank" rel="noopener noreferrer" class="button button-secondary">
                                    <span class="dashicons dashicons-cart"></span>
                                    <?php echo esc_html__('Purchase a License', 'botfend-anti-bot-firewall'); ?>
                                </a>
                                <a href="https://ejesgist.com/developer/" target="_blank" rel="noopener noreferrer" class="botfend-lost-license-link">
                                    <?php echo esc_html__('Lost your license key?', 'botfend-anti-bot-firewall'); ?>
                                </a>
                            </div>
                        </div>
                    </div>
                <?php endif; ?>
                
                <!-- License Information Card (always visible) -->
                <div class="botfend-license-card botfend-license-info">
                    <div class="botfend-license-content">
                        <h3>
                            <span class="dashicons dashicons-info"></span>
                            <?php echo esc_html__('License Information', 'botfend-anti-bot-firewall'); ?>
                        </h3>
                        <ul>
                            <li><strong><?php echo esc_html__('One license per site', 'botfend-anti-bot-firewall'); ?></strong> &ndash; <?php echo esc_html__('Each license key activates one WordPress installation.', 'botfend-anti-bot-firewall'); ?></li>
                            <li><strong><?php echo esc_html__('Terms', 'botfend-anti-bot-firewall'); ?></strong> &ndash; <?php echo esc_html__('Check your purchase email for license terms, expiration, and renewal details.', 'botfend-anti-bot-firewall'); ?></li>
                            <li><strong><?php echo esc_html__('Offline validation', 'botfend-anti-bot-firewall'); ?></strong> &ndash; <?php echo esc_html__('No internet connection required after activation.', 'botfend-anti-bot-firewall'); ?></li>
                            <li><strong><?php echo esc_html__('Need help?', 'botfend-anti-bot-firewall'); ?></strong> &ndash; 
                                <a href="https://ejesgist.com/developer/" target="_blank" rel="noopener noreferrer"><?php echo esc_html__('Contact Support', 'botfend-anti-bot-firewall'); ?></a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}