<?php
/**
 * Admin Settings class.
 *
 * Handles the plugin admin settings page for license activation with AJAX.
 *
 * @package Hugeicons
 */

namespace Hugeicons;

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Admin class for managing plugin settings.
 */
class Admin {

    /**
     * License instance.
     *
     * @var License
     */
    private $license;

    /**
     * Constructor.
     */
    public function __construct() {
        $this->license = new License();
    }

    /**
     * Initialize admin hooks.
     *
     * @return void
     */
    public function init() {
        add_action( 'admin_menu', array( $this, 'add_settings_page' ) );
        add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_assets' ) );
    }

    /**
     * Add the settings page to WordPress admin menu.
     *
     * @return void
     */
    public function add_settings_page() {
        add_options_page(
            __( 'Hugeicons Settings', 'hugeicons' ),
            __( 'Hugeicons', 'hugeicons' ),
            'manage_options',
            'hugeicons-settings',
            array( $this, 'render_settings_page' )
        );
    }

    /**
     * Enqueue admin assets.
     *
     * @param string $hook The current admin page hook.
     * @return void
     */
    public function enqueue_admin_assets( $hook ) {
        if ( 'settings_page_hugeicons-settings' !== $hook ) {
            return;
        }

        wp_add_inline_style( 'wp-admin', $this->get_admin_styles() );
        wp_add_inline_script( 'jquery', $this->get_admin_script(), 'after' );
    }

    /**
     * Get inline admin styles.
     *
     * @return string CSS styles.
     */
    private function get_admin_styles() {
        return '
            .hugeicons-settings-wrap {
                max-width: 600px;
                margin-top: 20px;
            }
            .hugeicons-settings-wrap .card {
                padding: 20px;
                margin-bottom: 20px;
            }
            .hugeicons-license-status {
                display: flex;
                align-items: center;
                gap: 10px;
                margin-bottom: 15px;
            }
            .hugeicons-license-status .status-badge {
                display: inline-block;
                padding: 4px 12px;
                border-radius: 4px;
                font-size: 12px;
                font-weight: 600;
                text-transform: uppercase;
            }
            .hugeicons-license-status .status-badge.active {
                background-color: #d1fae5;
                color: #065f46;
            }
            .hugeicons-license-status .status-badge.inactive {
                background-color: #fee2e2;
                color: #b91c1c;
            }
            .hugeicons-license-form {
                display: flex;
                gap: 10px;
                align-items: flex-start;
            }
            .hugeicons-license-form input[type="text"] {
                flex: 1;
                max-width: 350px;
            }
            .hugeicons-license-key-display {
                font-family: monospace;
                background: #f3f4f6;
                padding: 8px 12px;
                border-radius: 4px;
                margin-bottom: 15px;
            }
            .hugeicons-pro-features {
                background: #f0f9ff;
                border: 1px solid #bae6fd;
                border-radius: 8px;
                padding: 15px;
                margin-top: 20px;
            }
            .hugeicons-pro-features h4 {
                margin-top: 0;
                color: #0369a1;
            }
            .hugeicons-pro-features ul {
                margin-bottom: 0;
            }
            .hugeicons-license-message {
                margin-top: 15px;
                padding: 10px 15px;
                border-radius: 4px;
                display: none;
            }
            .hugeicons-license-message.success {
                background-color: #d1fae5;
                color: #065f46;
                border: 1px solid #10b981;
            }
            .hugeicons-license-message.error {
                background-color: #fee2e2;
                color: #b91c1c;
                border: 1px solid #ef4444;
            }
            .hugeicons-btn-loading {
                position: relative;
                pointer-events: none;
                opacity: 0.8;
            }
            .hugeicons-btn-loading::after {
                content: "";
                position: absolute;
                width: 14px;
                height: 14px;
                top: 50%;
                left: 50%;
                margin-left: -7px;
                margin-top: -7px;
                border: 2px solid #ffffff;
                border-radius: 50%;
                border-top-color: transparent;
                animation: hugeicons-spin 0.8s linear infinite;
            }
            .hugeicons-btn-loading span {
                visibility: hidden;
            }
            @keyframes hugeicons-spin {
                to { transform: rotate(360deg); }
            }
        ';
    }

    /**
     * Get inline admin JavaScript.
     *
     * @return string JavaScript code.
     */
    private function get_admin_script() {
        return "
            jQuery(document).ready(function($) {
                var restUrl = '" . esc_url( rest_url( 'hugeicons/v1/license/' ) ) . "';
                var nonce = '" . wp_create_nonce( 'wp_rest' ) . "';

                // Activate license
                $('#hugeicons-activate-btn').on('click', function(e) {
                    e.preventDefault();
                    var \$btn = $(this);
                    var \$input = $('#hugeicons-license-key');
                    var token = \$input.val().trim();

                    if (!token) {
                        showMessage('error', '" . esc_js( __( 'Please enter a license key.', 'hugeicons' ) ) . "');
                        return;
                    }

                    \$btn.addClass('hugeicons-btn-loading');
                    hideMessage();

                    $.ajax({
                        url: restUrl + 'activate',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': nonce },
                        contentType: 'application/json',
                        data: JSON.stringify({ token: token }),
                        success: function(response) {
                            \$btn.removeClass('hugeicons-btn-loading');
                            if (response.success) {
                                showMessage('success', response.message);
                                setTimeout(function() {
                                    location.reload();
                                }, 1500);
                            } else {
                                showMessage('error', response.message);
                            }
                        },
                        error: function(xhr) {
                            \$btn.removeClass('hugeicons-btn-loading');
                            var msg = xhr.responseJSON?.message || '" . esc_js( __( 'An error occurred. Please try again.', 'hugeicons' ) ) . "';
                            showMessage('error', msg);
                        }
                    });
                });

                // Deactivate license
                $('#hugeicons-deactivate-btn').on('click', function(e) {
                    e.preventDefault();
                    var \$btn = $(this);

                    if (!confirm('" . esc_js( __( 'Are you sure you want to deactivate your license?', 'hugeicons' ) ) . "')) {
                        return;
                    }

                    \$btn.addClass('hugeicons-btn-loading');
                    hideMessage();

                    $.ajax({
                        url: restUrl + 'deactivate',
                        method: 'POST',
                        headers: { 'X-WP-Nonce': nonce },
                        success: function(response) {
                            \$btn.removeClass('hugeicons-btn-loading');
                            showMessage('success', response.message);
                            setTimeout(function() {
                                location.reload();
                            }, 1500);
                        },
                        error: function(xhr) {
                            \$btn.removeClass('hugeicons-btn-loading');
                            var msg = xhr.responseJSON?.message || '" . esc_js( __( 'An error occurred. Please try again.', 'hugeicons' ) ) . "';
                            showMessage('error', msg);
                        }
                    });
                });

                function showMessage(type, text) {
                    var \$msg = $('#hugeicons-license-message');
                    \$msg.removeClass('success error').addClass(type).text(text).show();
                }

                function hideMessage() {
                    $('#hugeicons-license-message').hide();
                }
            });
        ";
    }

    /**
     * Render the settings page.
     *
     * @return void
     */
    public function render_settings_page() {
        $license_status = $this->license->get_license_status();
        $is_active      = $license_status['is_active'];
        ?>
        <div class="wrap hugeicons-settings-wrap">
            <h1><?php esc_html_e( 'Hugeicons Settings', 'hugeicons' ); ?></h1>

            <div class="card">
                <h2><?php esc_html_e( 'License Activation', 'hugeicons' ); ?></h2>

                <div class="hugeicons-license-status">
                    <span><?php esc_html_e( 'Status:', 'hugeicons' ); ?></span>
                    <?php if ( $is_active ) : ?>
                        <span class="status-badge active"><?php esc_html_e( 'Pro Active', 'hugeicons' ); ?></span>
                    <?php else : ?>
                        <span class="status-badge inactive"><?php esc_html_e( 'Free', 'hugeicons' ); ?></span>
                    <?php endif; ?>
                </div>

                <?php if ( $is_active && ! empty( $license_status['license_key'] ) ) : ?>
                    <div class="hugeicons-license-key-display">
                        <?php echo esc_html( $license_status['license_key'] ); ?>
                    </div>
                <?php endif; ?>

                <?php if ( $is_active ) : ?>
                    <p><?php esc_html_e( 'Your Pro license is active. You have access to all icon styles.', 'hugeicons' ); ?></p>
                    <button type="button" id="hugeicons-deactivate-btn" class="button">
                        <span><?php esc_html_e( 'Deactivate License', 'hugeicons' ); ?></span>
                    </button>
                <?php else : ?>
                    <div class="hugeicons-license-form">
                        <input
                            type="text"
                            id="hugeicons-license-key"
                            placeholder="<?php esc_attr_e( 'Enter your license key...', 'hugeicons' ); ?>"
                            class="regular-text"
                        />
                        <button type="button" id="hugeicons-activate-btn" class="button button-primary">
                            <span><?php esc_html_e( 'Activate License', 'hugeicons' ); ?></span>
                        </button>
                    </div>
                    <p class="description" style="margin-top: 10px;">
                        <?php
                        printf(
                            /* translators: %s: link to Hugeicons website */
                            esc_html__( 'Don\'t have a license? %s', 'hugeicons' ),
                            '<a href="https://hugeicons.com/pricing" target="_blank">' . esc_html__( 'Get Hugeicons Pro', 'hugeicons' ) . '</a>'
                        );
                        ?>
                    </p>
                <?php endif; ?>

                <div id="hugeicons-license-message" class="hugeicons-license-message"></div>

                <?php if ( ! $is_active ) : ?>
                    <div class="hugeicons-pro-features">
                        <h4><?php esc_html_e( 'Pro Features', 'hugeicons' ); ?></h4>
                        <ul>
                            <li><?php esc_html_e( '✓ Access to all 10 icon styles', 'hugeicons' ); ?></li>
                            <li><?php esc_html_e( '✓ 46,000+ premium icons', 'hugeicons' ); ?></li>
                            <li><?php esc_html_e( '✓ Stroke, Solid, Duotone, Twotone, and Bulk variants', 'hugeicons' ); ?></li>
                            <li><?php esc_html_e( '✓ Rounded, Standard, and Sharp corners', 'hugeicons' ); ?></li>
                        </ul>
                    </div>
                <?php endif; ?>
            </div>
        </div>
        <?php
    }
}
