<?php

/**
 * MassPost Admin Activation Interface
 *
 * Handles the WordPress admin dashboard authorization/activation page.
 *
 * @package MassPost
 * @since   1.0.0
 */

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

/**
 * Class MassPost_Admin_Activation
 *
 * Renders and manages the plugin activation screen for:
 * - License authorization with masspost.net
 * - Authorization callback handling
 * - License revocation
 *
 * @since 1.0.0
 */
class MassPost_Admin_Activation
{
    /** @var MassPost_Admin_Activation|null Singleton instance */
    private static $instance = null;

    public static function init()
    {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct()
    {
        // License AJAX handlers
        add_action('wp_ajax_masspost_start_authorization', [$this, 'ajax_start_authorization']);
        add_action('wp_ajax_masspost_check_authorization', [$this, 'ajax_check_authorization']);
        add_action('admin_post_masspost_revoke_license', [$this, 'handle_revoke_license']);

        // Handle authorization callback
        add_action('admin_init', [$this, 'maybe_handle_auth_callback']);

        // Admin notices
        add_action('admin_notices', [$this, 'maybe_notice']);
    }

    /**
     * Check if plugin is activated.
     *
     * @return bool
     */
    public function is_activated(): bool
    {
        return function_exists('masspost_is_activated') && masspost_is_activated();
    }

    /**
     * Render admin notice if transient is set.
     */
    public function maybe_notice(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }
        $notice = get_transient('masspost_admin_notice');
        if ($notice && is_array($notice)) {
            $cls = !empty($notice['success'])
                ? 'notice notice-success'
                : 'notice notice-error';
            echo '<div class="' .
                esc_attr($cls) .
                '"><p>' .
                wp_kses_post($notice['message']) .
                '</p></div>';
            delete_transient('masspost_admin_notice');
        }
    }

    /**
     * Render the license activation screen.
     */
    public function render_activation_screen(): void
    {
        $license = function_exists('masspost_get_license_data') ? masspost_get_license_data() : [];
        $has_pending = isset($license['status']) && 'pending' === $license['status'];
        $last_error = $license['last_error'] ?? null;
        $session = $license['session'] ?? [];

        echo '<div class="wrap masspost-wrap" style="font-family: \'Montserrat\', -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, sans-serif;">';
        echo '<div class="masspost-header" style="display:flex;align-items:center;justify-content: center;gap:12px;">';
        echo '<h1><img src="' . esc_url(plugin_dir_url(dirname(__FILE__)) . 'assets/images/masspost-logo-light.svg') . '" alt="' . esc_attr__('MassPost', 'masspost') . '" style="height:50px; margin: 25px 0; vertical-align:middle;"></h1>';
        echo '</div><hr class="wp-header-end" />';

        // Show error if exists
        if ($last_error && !empty($last_error['message'])) {
            echo '<div class="notice notice-error" style="margin:20px auto;text-align:center;"><p>' . esc_html($last_error['message']) . '</p></div>';
        }

        if ($has_pending && !empty($session['authorize_url'])) {
            // Pending state - show continue authorization
            echo '<div class="notice notice-warning" style="margin:20px auto;text-align:center;"><p>' .
                esc_html__('Authorization pending. Complete the process on masspost.net to unlock the plugin.', 'masspost') .
                '</p></div>';

            echo '<form method="post" class="masspost-authorization-form" style="max-width:1200px;margin:30px auto;text-align:center;padding: 20px 20px 30px 20px; background: #fbfbfb; border-radius: 10px;">';
            wp_nonce_field('masspost_authorize_action', 'masspost_authorize_nonce');
            echo '<input type="hidden" name="masspost_action" value="cancel_pending">';
            echo '<h2 style="font-size:22px;margin-bottom:20px;">' . esc_html__('Complete Authorization', 'masspost') . '</h2>';
            echo '<p style="font-size:15px;line-height:1.6;color:#555;margin-bottom:30px;">' . esc_html__('Click below to complete the authorization on masspost.net', 'masspost') . '</p>';
            echo '<p><a href="' . esc_url($session['authorize_url']) . '" class="button button-primary" style="background:#394eff;border:none;border-radius:50px;padding:10px 30px;font-size:15px;font-weight:500;">' . esc_html__('Complete Authorization', 'masspost') . '</a></p>';
            echo '<p style="margin-top:20px;"><button type="submit" class="button button-secondary" style="background:#fff;color:#394eff;border:none;border-radius:50px;padding:8px 24px;font-weight:500;box-shadow:inset 0 0 0 1px #e8e8e8;">' . esc_html__('Start Over', 'masspost') . '</button></p>';
            echo '</form>';
        } else {
            // Show authorization notice
            echo '<div class="notice notice-warning" style="margin:20px auto;text-align:center;"><p>' .
                esc_html__('Please authorize this site with your MassPost account to unlock the plugin settings.', 'masspost') .
                '</p></div>';

            // Authorization form
            echo '<form id="masspost-activation-form" class="masspost-authorization-form" style="max-width:1200px;margin:30px auto;text-align:center;padding: 20px 20px 30px 20px; background: #fbfbfb; border-radius: 10px;">';
            echo '<h2 style="font-size:22px;margin-bottom:20px;">' . esc_html__('Connect Your Site', 'masspost') . '</h2>';
            echo '<p style="font-size:15px;line-height:1.6;color:#555;margin-bottom:30px;">' . esc_html__('Authorize this WordPress install with masspost.net to unlock multi-site publishing features.', 'masspost') . '</p>';

            // Feature list grid
            echo '<ul class="feature-list" style="max-width:600px;margin:0 auto 30px;display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px;text-align:left;">';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-share" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Publish to multiple sites at once', 'masspost') . '</span></li>';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-admin-network" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Secure REST API communication', 'masspost') . '</span></li>';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-category" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Category & tag synchronization', 'masspost') . '</span></li>';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-format-image" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Featured image transfer', 'masspost') . '</span></li>';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-clock" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Scheduled post support', 'masspost') . '</span></li>';
            echo '<li style="display:flex;gap:12px;align-items:center;"><span class="dashicons dashicons-admin-site-alt3" style="color:#394eff;font-size:20px;"></span><span>' . esc_html__('Works with any WordPress theme', 'masspost') . '</span></li>';
            echo '</ul>';

            echo '<hr style="border-top: 1px dotted #ddd;margin: 30px 0;">';

            // Email input
            echo '<p><label for="masspost-activation-email">';
            echo '<strong style="font-size: 14px;">' . esc_html__('Provide your email address', 'masspost') . '</strong><br>';
            echo '<input style="background: #dde6ffa8; border: 1px solid #b5c8ffa8; margin: 10px 0; text-align: center;" name="masspost_email" type="email" id="masspost-activation-email" class="regular-text" value="" required>';
            echo '</label></p>';

            echo '<button type="submit" id="masspost-activate-btn" class="button button-primary" style="background:#394eff;border:none;border-radius:50px;padding:8px 24px;font-size:15px;font-weight:500;">' . esc_html__('Authorize MassPost', 'masspost') . '</button>';
            echo '</form>';
        }

        echo '<p id="masspost-activation-status" style="margin-top:16px;color:#666;text-align:center;"></p>';

        // Pricing info box
        echo '<hr style="margin: 30px 0;">';
        echo '<div style="margin-top: 20px; font-size: 14px; max-width: 1200px; margin-left: auto; margin-right: auto; text-align: center; line-height: 1.5em; padding: 20px; background: #dde6ffa8; border-radius: 10px; color: #2435c7;">';
        $acct_label = '<strong>' . esc_html__('MassPost Account', 'masspost') . '</strong>';
        $site_text = '<strong>' . esc_html('https://masspost.net') . '</strong>';
        $link_style = 'color:#394eff;';

        echo wp_kses(
            sprintf(
                /* translators: 1: account URL, 2: website URL, 3: website label, 4: account label, 5: CSS style */
                __('To activate this plugin, you need an active <a href="%1$s" target="_blank" rel="noopener" style="%5$s">%4$s</a>.<br>For more info: <a href="%2$s" target="_blank" rel="noopener" style="%5$s">%3$s</a>', 'masspost'),
                esc_url('https://masspost.net/account'),
                esc_url('https://masspost.net'),
                $site_text,
                $acct_label,
                esc_attr($link_style)
            ),
            [
                'a' => ['href' => [], 'target' => [], 'rel' => [], 'style' => []],
                'strong' => [],
                'br' => [],
            ]
        );
        echo '</div>';

        echo '</div>';

        // Inline JS for activation
?>
        <script>
            jQuery(function($) {
                $('#masspost-activation-form').on('submit', function(e) {
                    e.preventDefault();
                    var email = $('#masspost-activation-email').val();
                    var btn = $('#masspost-activate-btn');
                    var status = $('#masspost-activation-status');

                    btn.prop('disabled', true).text('<?php echo esc_js(__('Connecting...', 'masspost')); ?>');
                    status.text('');

                    $.post(ajaxurl, {
                        action: 'masspost_start_authorization',
                        email: email,
                        _wpnonce: '<?php echo esc_js(wp_create_nonce('masspost_auth_nonce')); ?>'
                    }, function(response) {
                        if (response.success && response.data.authorize_url) {
                            status.text('<?php echo esc_js(__('Redirecting to masspost.net...', 'masspost')); ?>');
                            window.location.href = response.data.authorize_url;
                        } else {
                            btn.prop('disabled', false).text('<?php echo esc_js(__('Connect to masspost.net', 'masspost')); ?>');
                            status.css('color', '#d63638').text(response.data && response.data.message ? response.data.message : '<?php echo esc_js(__('An error occurred.', 'masspost')); ?>');
                        }
                    }).fail(function() {
                        btn.prop('disabled', false).text('<?php echo esc_js(__('Connect to masspost.net', 'masspost')); ?>');
                        status.css('color', '#d63638').text('<?php echo esc_js(__('Connection failed. Please try again.', 'masspost')); ?>');
                    });
                });
            });
        </script>
<?php
    }

    /**
     * AJAX: Start authorization flow.
     */
    public function ajax_start_authorization(): void
    {
        check_ajax_referer('masspost_auth_nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Access denied.', 'masspost')]);
        }

        $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';

        if (!function_exists('masspost_license')) {
            wp_send_json_error(['message' => __('License system not initialized.', 'masspost')]);
        }

        $result = masspost_license()->start_authorization($email);

        if (is_wp_error($result)) {
            wp_send_json_error(['message' => $result->get_error_message()]);
        }

        wp_send_json_success([
            'session_id' => $result['id'],
            'authorize_url' => $result['authorize_url'],
        ]);
    }

    /**
     * AJAX: Check authorization status.
     */
    public function ajax_check_authorization(): void
    {
        check_ajax_referer('masspost_auth_nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Access denied.', 'masspost')]);
        }

        if (!function_exists('masspost_is_activated')) {
            wp_send_json_error(['status' => 'error']);
        }

        if (masspost_is_activated()) {
            wp_send_json_success(['status' => 'authorized']);
        }

        $license = masspost_get_license_data();
        $status = $license['status'] ?? 'inactive';

        wp_send_json_success(['status' => $status]);
    }

    /**
     * Handle authorization callback from masspost.net.
     */
    public function maybe_handle_auth_callback(): void
    {
        // Handle POST actions (Start Over button, etc.)
        $request_method = isset($_SERVER['REQUEST_METHOD']) ? sanitize_text_field(wp_unslash($_SERVER['REQUEST_METHOD'])) : '';
        if ('POST' === strtoupper($request_method) && isset($_POST['masspost_action'])) {
            if (!current_user_can('manage_options') || !wp_verify_nonce(
                isset($_POST['masspost_authorize_nonce']) ? sanitize_text_field(wp_unslash($_POST['masspost_authorize_nonce'])) : '',
                'masspost_authorize_action'
            )) {
                return;
            }

            $action = sanitize_text_field(wp_unslash($_POST['masspost_action']));

            if ('cancel_pending' === $action && function_exists('masspost_license')) {
                masspost_license()->clear_license();
                set_transient('masspost_admin_notice', [
                    'success' => true,
                    'message' => __('Pending authorization cleared. You can start fresh.', 'masspost'),
                ], 60);
                wp_safe_redirect(admin_url('admin.php?page=masspost'));
                exit;
            }
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Callback from external server
        if (empty($_GET['masspost_auth_callback']) || empty($_GET['page']) || 'masspost' !== $_GET['page']) {
            return;
        }

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

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Callback from external server
        $session_id = isset($_GET['session_id']) ? sanitize_text_field(wp_unslash($_GET['session_id'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Callback from external server
        $auz_token = isset($_GET['auz_token']) ? sanitize_text_field(wp_unslash($_GET['auz_token'])) : '';
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Callback from external server
        $request_id = isset($_GET['request_id']) ? sanitize_text_field(wp_unslash($_GET['request_id'])) : '';

        if (!$session_id || !$auz_token) {
            set_transient('masspost_admin_notice', [
                'success' => false,
                'message' => __('Invalid authorization callback. Missing parameters.', 'masspost'),
            ], 60);
            wp_safe_redirect(admin_url('admin.php?page=masspost'));
            exit;
        }

        if (!function_exists('masspost_license')) {
            wp_safe_redirect(admin_url('admin.php?page=masspost&error=license_init'));
            exit;
        }

        $result = masspost_license()->finalize_authorization($session_id, $auz_token, $request_id);

        if (is_wp_error($result)) {
            set_transient('masspost_admin_notice', [
                'success' => false,
                'message' => $result->get_error_message(),
            ], 60);
        } else {
            set_transient('masspost_admin_notice', [
                'success' => true,
                'message' => __('MassPost activated successfully!', 'masspost'),
            ], 60);
        }

        wp_safe_redirect(admin_url('admin.php?page=masspost'));
        exit;
    }

    /**
     * Handle license revocation.
     */
    public function handle_revoke_license(): void
    {
        if (!current_user_can('manage_options') || !check_admin_referer('masspost_revoke_license', 'masspost_revoke_nonce')) {
            wp_die(esc_html__('Access denied.', 'masspost'), '', 403);
        }

        if (!function_exists('masspost_license')) {
            wp_safe_redirect(admin_url('admin.php?page=masspost'));
            exit;
        }

        $result = masspost_license()->revoke_authorization();
        $redirect = add_query_arg(
            'revoked',
            is_wp_error($result) ? 'fail' : 'success',
            admin_url('admin.php?page=masspost')
        );

        wp_safe_redirect($redirect);
        exit;
    }

    /**
     * Render revoke button HTML for use in settings page.
     *
     * @return string
     */
    public function get_revoke_button_html(): string
    {
        return '<a href="' .
            esc_url(
                wp_nonce_url(
                    admin_url('admin-post.php?action=masspost_revoke_license'),
                    'masspost_revoke_license',
                    'masspost_revoke_nonce'
                )
            ) .
            '" class="button masspost-revoke-button" onclick="return confirm(\'' .
            esc_js(__('Are you sure you want to revoke the license?', 'masspost')) .
            '\');">' .
            esc_html__('Revoke License', 'masspost') .
            '</a>';
    }
}

/**
 * Helper accessor.
 *
 * @return MassPost_Admin_Activation
 */
function masspost_admin_activation(): MassPost_Admin_Activation
{
    return MassPost_Admin_Activation::init();
}
