<?php
/**
 * WordChat Pro License Management Admin Interface
 *
 * Provides UI for:
 * - Entering and activating license keys
 * - Viewing license status
 * - Deactivating licenses
 * - Upgrading to Pro
 *
 * @package WordChat
 * @subpackage Pro
 * @since 0.1.27
 */

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

/**
 * Auto-activate license key when Pro status is detected
 */
function wordchat_auto_activate_license() {
    // Only run on admin pages
    if (!is_admin()) {
        return;
    }

    $is_paid = get_option('wordchat_is_paid');
    $license_key = get_option('wordchat_license_key', '');
    $license_status = get_option('wordchat_license_status', 'inactive');

    // If user is Pro, has a license key, but it's not activated
    if ($is_paid === '1' && !empty($license_key) && $license_status !== 'active') {
        // Attempt to activate the license
        $site_id = get_option('wordchat_site_id');
        $domain = get_site_url();

        if ($site_id) {
            $response = wp_remote_post(WORDCHAT_API_URL . '/license/activate', [
                'headers' => ['Content-Type' => 'application/json'],
                'body' => json_encode([
                    'license_key' => $license_key,
                    'site_id' => $site_id,
                    'domain' => $domain,
                    'plugin_version' => WORDCHAT_VERSION,
                    'wp_version' => get_bloginfo('version'),
                    'php_version' => PHP_VERSION
                ]),
                'timeout' => 15
            ]);

            if (!is_wp_error($response)) {
                $data = json_decode(wp_remote_retrieve_body($response), true);

                if (isset($data['valid']) && $data['valid'] === true) {
                    // License activated successfully
                    update_option('wordchat_license_status', 'active');
                    update_option('wordchat_license_data', $data);

                    // Log success
                    error_log('WordChat: License auto-activated successfully');
                } else {
                    // License activation failed
                    error_log('WordChat: License auto-activation failed: ' . ($data['error'] ?? 'Unknown error'));
                }
            }
        }
    }
}
add_action('admin_init', 'wordchat_auto_activate_license', 5); // Priority 5 to run early

/**
 * Add License tab to WordChat settings page
 */
function wordchat_render_license_tab() {
    $license_key = get_option('wordchat_license_key', '');
    $license_status = get_option('wordchat_license_status', 'inactive');
    $license_data = get_option('wordchat_license_data', array());
    $is_paid = get_option('wordchat_is_paid', '0');

    ?>
    <div class="wordchat-license-section">
        <h2>License Management</h2>

        <?php if ($is_paid === '1' && !$license_key): ?>
            <!-- Pro customer but no license key -->
            <div class="notice notice-info">
                <p>
                    <strong>You have an active Pro subscription!</strong>
                    Your license key should have been emailed to you.
                    Enter it below to enable automatic updates.
                </p>
            </div>
        <?php elseif ($is_paid !== '1'): ?>
            <!-- Free user - show upgrade CTA -->
            <div class="wordchat-upgrade-box" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 30px; border-radius: 8px; margin-bottom: 20px;">
                <h3 style="color: white; margin-top: 0;">Upgrade to WordChat Pro</h3>
                <p style="font-size: 16px; opacity: 0.95;">
                    Get unlimited content, unlimited messages, and automatic plugin updates.
                </p>
                <ul style="list-style: none; padding-left: 0; font-size: 15px;">
                    <li>✅ Unlimited content (vs 10 posts + 5 pages on free)</li>
                    <li>✅ Unlimited chat messages (vs 100/month on free)</li>
                    <li>✅ Remove "Powered by" branding</li>
                    <li>✅ Automatic plugin updates</li>
                    <li>✅ Priority support</li>
                </ul>
                <?php
                $license_upgrade_url = add_query_arg([
                    'utm_source' => 'plugin',
                    'utm_medium' => 'license_tab',
                    'utm_campaign' => 'upgrade',
                    'site_id' => get_option('wordchat_site_id')
                ], 'https://www.word.chat/pricing');
                ?>
                <a href="<?php echo esc_url($license_upgrade_url); ?>"
                   target="_blank"
                   class="button button-primary button-hero"
                   style="background: white; color: #667eea; border: none; margin-top: 10px; display: inline-block; text-decoration: none;">
                    Upgrade Now - $29/month →
                </a>
            </div>
        <?php endif; ?>

        <!-- License Key Input Form -->
        <form method="post" action="" class="wordchat-license-form">
            <?php wp_nonce_field('wordchat_license_action', 'wordchat_license_nonce'); ?>

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="wordchat_license_key">License Key</label>
                    </th>
                    <td>
                        <input
                            type="text"
                            id="wordchat_license_key"
                            name="wordchat_license_key"
                            value="<?php echo esc_attr($license_key); ?>"
                            class="regular-text"
                            placeholder="WC-PRO-XXXX-XXXX-XXXX-XXXX"
                            <?php echo ($license_status === 'active') ? 'readonly' : ''; ?>
                        />

                        <?php if ($license_status === 'active'): ?>
                            <span style="color: #46b450; margin-left: 10px;">
                                <span class="dashicons dashicons-yes-alt"></span>
                                Active
                            </span>
                        <?php endif; ?>

                        <p class="description">
                            Enter your license key to enable Pro features and automatic updates.
                            <?php if (!$license_key): ?>
                                <?php
                                $license_form_upgrade_url = add_query_arg([
                                    'utm_source' => 'plugin',
                                    'utm_medium' => 'license_form',
                                    'utm_campaign' => 'upgrade',
                                    'site_id' => get_option('wordchat_site_id')
                                ], 'https://www.word.chat/pricing');
                                ?>
                                <br>Don't have a license? <a href="<?php echo esc_url($license_form_upgrade_url); ?>" target="_blank">Upgrade to Pro</a>
                            <?php endif; ?>
                        </p>
                    </td>
                </tr>

                <?php if ($license_status === 'active' && !empty($license_data)): ?>
                    <!-- License Details -->
                    <tr>
                        <th scope="row">License Status</th>
                        <td>
                            <div class="wordchat-license-details" style="background: #f0f0f1; padding: 15px; border-radius: 4px;">
                                <p><strong>Plan:</strong> <?php echo esc_html(ucfirst($license_data['plan_type'] ?? 'Pro')); ?></p>
                                <p><strong>Activations:</strong>
                                    <?php echo esc_html($license_data['current_activations'] ?? 1); ?>
                                    /
                                    <?php echo esc_html($license_data['max_activations'] ?? 1); ?>
                                    sites
                                </p>
                                <?php if (!empty($license_data['expires_at'])): ?>
                                    <p><strong>Expires:</strong> <?php echo esc_html(date('F j, Y', strtotime($license_data['expires_at']))); ?></p>
                                <?php else: ?>
                                    <p><strong>Expires:</strong> Never (subscription)</p>
                                <?php endif; ?>
                                <p><strong>Domain:</strong> <?php echo esc_html(get_site_url()); ?></p>
                            </div>
                        </td>
                    </tr>
                <?php endif; ?>
            </table>

            <p class="submit">
                <?php if ($license_status === 'active'): ?>
                    <button type="submit" name="wordchat_license_action_type" value="deactivate" class="button button-secondary">
                        Deactivate License
                    </button>
                    <button type="submit" name="wordchat_license_action_type" value="refresh" class="button">
                        Refresh Status
                    </button>
                <?php else: ?>
                    <button type="submit" name="wordchat_license_action_type" value="activate" class="button button-primary">
                        Activate License
                    </button>
                <?php endif; ?>
            </p>
        </form>

        <!-- License Information Box -->
        <div class="wordchat-license-info" style="margin-top: 30px; border-left: 4px solid #2271b1; padding: 15px; background: #f0f6fc;">
            <h3 style="margin-top: 0;">About License Keys</h3>
            <ul>
                <li><strong>Where to find your license:</strong> Check your email after upgrading or visit your account dashboard.</li>
                <li><strong>Activations:</strong> Each license can be used on <?php echo esc_html($license_data['max_activations'] ?? 1); ?> site(s).</li>
                <li><strong>Deactivation:</strong> Deactivate on one site to use the license on another.</li>
                <li><strong>Updates:</strong> Automatic plugin updates require an active license.</li>
            </ul>

            <p>
                <strong>Need help?</strong>
                <a href="https://www.word.chat/support" target="_blank">Contact Support</a>
            </p>
        </div>
    </div>

    <style>
        .wordchat-license-section {
            max-width: 800px;
        }
        .wordchat-license-form input[type="text"] {
            font-family: monospace;
            font-size: 14px;
        }
        .wordchat-license-details p {
            margin: 5px 0;
        }
    </style>

    <?php
}

/**
 * Handle license activation/deactivation requests
 */
function wordchat_handle_license_action() {
    if (!isset($_POST['wordchat_license_nonce']) ||
        !wp_verify_nonce($_POST['wordchat_license_nonce'], 'wordchat_license_action')) {
        return;
    }

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

    $action = sanitize_text_field($_POST['wordchat_license_action_type'] ?? '');
    $license_key = sanitize_text_field($_POST['wordchat_license_key'] ?? '');

    if (!$action) {
        return;
    }

    $site_id = get_option('wordchat_site_id');
    $api_url = WORDCHAT_API_URL;

    if ($action === 'activate') {
        // Activate license
        if (empty($license_key)) {
            add_settings_error('wordchat_license', 'empty_license', 'Please enter a license key.', 'error');
            return;
        }

        $response = wp_remote_post($api_url . '/license/activate', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body'    => json_encode(array(
                'license_key'    => $license_key,
                'site_id'        => $site_id,
                'domain'         => get_site_url(),
                'plugin_version' => WORDCHAT_VERSION,
                'wp_version'     => get_bloginfo('version'),
                'php_version'    => PHP_VERSION
            )),
            'timeout' => 15
        ));

        if (is_wp_error($response)) {
            add_settings_error('wordchat_license', 'activation_failed',
                'License activation failed: ' . $response->get_error_message(), 'error');
            return;
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($code === 200 && isset($body['success']) && $body['success']) {
            // Activation successful
            update_option('wordchat_license_key', $license_key);
            update_option('wordchat_license_status', 'active');
            update_option('wordchat_is_paid', '1');

            // Fetch and store license details
            wordchat_fetch_license_details($license_key, $site_id);

            add_settings_error('wordchat_license', 'activation_success',
                'License activated successfully!', 'success');

            // Clear update transient to trigger fresh update check
            delete_site_transient('update_plugins');
        } else {
            $error_message = $body['error'] ?? $body['detail'] ?? 'Unknown error';
            add_settings_error('wordchat_license', 'activation_failed',
                'License activation failed: ' . $error_message, 'error');
        }

    } elseif ($action === 'deactivate') {
        // Deactivate license
        $current_license = get_option('wordchat_license_key');

        if (!$current_license) {
            return;
        }

        $response = wp_remote_post($api_url . '/license/deactivate', array(
            'headers' => array('Content-Type' => 'application/json'),
            'body'    => json_encode(array(
                'license_key' => $current_license,
                'site_id'     => $site_id,
                'reason'      => 'user_deactivated'
            )),
            'timeout' => 15
        ));

        if (!is_wp_error($response) && wp_remote_retrieve_response_code($response) === 200) {
            // Deactivation successful
            delete_option('wordchat_license_key');
            update_option('wordchat_license_status', 'inactive');
            delete_option('wordchat_license_data');

            add_settings_error('wordchat_license', 'deactivation_success',
                'License deactivated successfully.', 'success');
        } else {
            add_settings_error('wordchat_license', 'deactivation_failed',
                'License deactivation failed.', 'error');
        }

    } elseif ($action === 'refresh') {
        // Refresh license status
        $current_license = get_option('wordchat_license_key');

        if ($current_license && $site_id) {
            wordchat_fetch_license_details($current_license, $site_id);
            add_settings_error('wordchat_license', 'refresh_success',
                'License status refreshed.', 'success');
        }
    }
}
add_action('admin_init', 'wordchat_handle_license_action');

/**
 * Fetch and store license details from API
 *
 * @param string $license_key License key
 * @param string $site_id Site ID
 * @return bool Success status
 */
function wordchat_fetch_license_details($license_key, $site_id) {
    $response = wp_remote_post(WORDCHAT_API_URL . '/license/validate', array(
        'headers' => array('Content-Type' => 'application/json'),
        'body'    => json_encode(array(
            'license_key' => $license_key,
            'site_id'     => $site_id
        )),
        'timeout' => 10
    ));

    if (is_wp_error($response)) {
        return false;
    }

    $body = json_decode(wp_remote_retrieve_body($response), true);

    if (isset($body['valid']) && $body['valid']) {
        // Store license details
        update_option('wordchat_license_data', array(
            'plan_type'           => $body['plan_type'] ?? 'pro',
            'status'              => $body['status'] ?? 'active',
            'max_activations'     => $body['max_activations'] ?? 1,
            'current_activations' => $body['current_activations'] ?? 1,
            'expires_at'          => $body['expires_at'] ?? null
        ));

        update_option('wordchat_license_status', 'active');
        return true;
    } else {
        update_option('wordchat_license_status', 'invalid');
        return false;
    }
}

/**
 * Display settings errors for license actions
 */
function wordchat_display_license_notices() {
    settings_errors('wordchat_license');
}
add_action('admin_notices', 'wordchat_display_license_notices');
