<?php
/**
 * CalcsLive Settings Page
 *
 * Handles the plugin settings in WordPress admin.
 */

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

class CalcsLive_Settings {

    /**
     * Add admin menu item
     */
    public static function add_admin_menu() {
        add_options_page(
            __('CalcsLive Settings', 'calcslive-article-embed'),
            __('CalcsLive', 'calcslive-article-embed'),
            'manage_options',
            'calcslive-settings',
            array(__CLASS__, 'render_settings_page')
        );
    }

    /**
     * Register settings
     */
    public static function register_settings() {
        // Register settings
        register_setting('calcslive_settings', 'calcslive_api_key', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));

        register_setting('calcslive_settings', 'calcslive_default_width', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '100%',
        ));

        register_setting('calcslive_settings', 'calcslive_default_height', array(
            'type' => 'string',
            'sanitize_callback' => 'absint',
            'default' => '600',
        ));

        register_setting('calcslive_settings', 'calcslive_domain', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));

        // Add settings section
        add_settings_section(
            'calcslive_main_section',
            __('API Configuration', 'calcslive-article-embed'),
            array(__CLASS__, 'render_section_description'),
            'calcslive-settings'
        );

        // Add settings fields
        add_settings_field(
            'calcslive_api_key',
            __('Embed Token', 'calcslive-article-embed'),
            array(__CLASS__, 'render_api_key_field'),
            'calcslive-settings',
            'calcslive_main_section'
        );

        add_settings_field(
            'calcslive_domain',
            __('Domain', 'calcslive-article-embed'),
            array(__CLASS__, 'render_domain_field'),
            'calcslive-settings',
            'calcslive_main_section'
        );

        add_settings_field(
            'calcslive_default_width',
            __('Default Width', 'calcslive-article-embed'),
            array(__CLASS__, 'render_width_field'),
            'calcslive-settings',
            'calcslive_main_section'
        );

        add_settings_field(
            'calcslive_default_height',
            __('Default Height', 'calcslive-article-embed'),
            array(__CLASS__, 'render_height_field'),
            'calcslive-settings',
            'calcslive_main_section'
        );
    }

    /**
     * Render section description
     */
    public static function render_section_description() {
        echo '<p>' . esc_html__('Configure your CalcsLive embed settings. You need an Embed Token from your CalcsLive account.', 'calcslive-article-embed') . '</p>';
        echo '<p><a href="https://www.calcslive.com/account/api-keys" target="_blank" rel="noopener">' . esc_html__('Get your Embed Token from CalcsLive → Account → API Keys', 'calcslive-article-embed') . ' &rarr;</a></p>';
    }

    /**
     * Render Embed Token field
     */
    public static function render_api_key_field() {
        $value = get_option('calcslive_api_key', '');
        ?>
        <input type="text"
               id="calcslive_api_key"
               name="calcslive_api_key"
               value="<?php echo esc_attr($value); ?>"
               class="regular-text"
               placeholder="cle_xxxxxxxxxxxxxxxxxxxx">
        <button type="button" id="calcslive-test-token" class="button button-secondary" style="margin-left: 8px;">
            <?php esc_html_e('Test Connection', 'calcslive-article-embed'); ?>
        </button>
        <span id="calcslive-test-spinner" class="spinner" style="float: none; margin: 0 4px; vertical-align: middle; visibility: hidden;"></span>
        <div id="calcslive-test-result" style="margin-top: 8px; display: none;"></div>
        <p class="description">
            <?php esc_html_e('Your CalcsLive Embed Token (starts with cle_). Find it in your CalcsLive account under Account → API Keys → Embed Token.', 'calcslive-article-embed'); ?>
        </p>
        <?php
    }

    /**
     * Render domain field
     */
    public static function render_domain_field() {
        $value = get_option('calcslive_domain', '');
        ?>
        <input type="text"
               name="calcslive_domain"
               value="<?php echo esc_attr($value); ?>"
               class="regular-text"
               placeholder="<?php echo esc_attr(wp_parse_url(get_site_url(), PHP_URL_HOST)); ?>">
        <p class="description">
            <?php esc_html_e('Your website domain. This should match a domain configured in your CalcsLive account.', 'calcslive-article-embed'); ?>
        </p>
        <?php
    }

    /**
     * Render width field
     */
    public static function render_width_field() {
        $value = get_option('calcslive_default_width', '100%');
        ?>
        <input type="text"
               name="calcslive_default_width"
               value="<?php echo esc_attr($value); ?>"
               class="small-text"
               placeholder="100%">
        <p class="description">
            <?php esc_html_e('Default width for embedded articles. Use percentage (e.g., 100%) or pixels (e.g., 800).', 'calcslive-article-embed'); ?>
        </p>
        <?php
    }

    /**
     * Render height field
     */
    public static function render_height_field() {
        $value = get_option('calcslive_default_height', '600');
        ?>
        <input type="number"
               name="calcslive_default_height"
               value="<?php echo esc_attr($value); ?>"
               class="small-text"
               min="200"
               max="2000"
               placeholder="600">
        <span>px</span>
        <p class="description">
            <?php esc_html_e('Default height for embedded articles in pixels.', 'calcslive-article-embed'); ?>
        </p>
        <?php
    }

    /**
     * AJAX handler: test embed token by calling the CalcsLive token-check endpoint
     */
    public static function ajax_test_token() {
        check_ajax_referer('calcslive_test_token_nonce', 'nonce');

        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => 'Unauthorized'), 403);
        }

        $token = isset($_POST['token']) ? sanitize_text_field(wp_unslash($_POST['token'])) : '';

        if (empty($token)) {
            wp_send_json_error(array('message' => 'Please enter an Embed Token before testing.'));
        }

        $url = 'https://www.calcslive.com/api/embed-ecommerce/v1/token-check?token=' . rawurlencode($token);

        $response = wp_remote_get($url, array(
            'timeout' => 10,
            'headers' => array('Accept' => 'application/json'),
        ));

        if (is_wp_error($response)) {
            wp_send_json_error(array('message' => 'Could not reach CalcsLive. Check your internet connection.'));
        }

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

        if (!is_array($body)) {
            wp_send_json_error(array('message' => 'Unexpected response from CalcsLive (HTTP ' . $status_code . ').'));
        }

        if (!empty($body['valid'])) {
            wp_send_json_success($body);
        } else {
            wp_send_json_error(array('message' => isset($body['error']) ? $body['error'] : 'Token validation failed.'));
        }
    }

    /**
     * Enqueue admin JS + pass nonce for the Test Connection button
     */
    public static function enqueue_admin_scripts($hook) {
        if ('settings_page_calcslive-settings' !== $hook) {
            return;
        }

        // Inline script — small enough not to warrant a separate file
        $nonce  = wp_create_nonce('calcslive_test_token_nonce');
        $script = "
(function() {
    var btn     = document.getElementById('calcslive-test-token');
    var spinner = document.getElementById('calcslive-test-spinner');
    var result  = document.getElementById('calcslive-test-result');
    var input   = document.getElementById('calcslive_api_key');

    if (!btn) return;

    btn.addEventListener('click', function() {
        var token = input ? input.value.trim() : '';
        if (!token) {
            result.style.display = 'block';
            result.innerHTML = '<span style=\"color:#cc1818;\">Please enter an Embed Token first.</span>';
            return;
        }

        btn.disabled       = true;
        spinner.style.visibility = 'visible';
        result.style.display     = 'none';

        var body = new URLSearchParams({
            action : 'calcslive_test_token',
            nonce  : '" . esc_js($nonce) . "',
            token  : token
        });

        fetch(ajaxurl, { method: 'POST', body: body })
            .then(function(r) { return r.json(); })
            .then(function(data) {
                spinner.style.visibility = 'hidden';
                btn.disabled = false;
                result.style.display = 'block';

                if (data.success) {
                    var d = data.data;
                    var domains = d.allowedDomains && d.allowedDomains.length
                        ? d.allowedDomains.join(', ')
                        : '<em>none configured</em>';
                    result.innerHTML =
                        '<span style=\"color:#00823a;font-weight:600;\">&#10003; Token valid</span>' +
                        ' &mdash; Plan: <strong>' + escHtml(d.tier) + '</strong>' +
                        ' &mdash; Allowed domains: ' + domains;
                } else {
                    result.innerHTML =
                        '<span style=\"color:#cc1818;font-weight:600;\">&#10007; ' +
                        escHtml(data.data && data.data.message ? data.data.message : 'Connection failed') +
                        '</span>';
                }
            })
            .catch(function() {
                spinner.style.visibility = 'hidden';
                btn.disabled = false;
                result.style.display = 'block';
                result.innerHTML = '<span style=\"color:#cc1818;\">Request failed — check your internet connection.</span>';
            });
    });

    function escHtml(str) {
        var d = document.createElement('div');
        d.appendChild(document.createTextNode(str));
        return d.innerHTML;
    }
}());
";
        wp_register_script('calcslive-admin', '', array(), CALCSLIVE_VERSION, true);
        wp_enqueue_script('calcslive-admin');
        wp_add_inline_script('calcslive-admin', $script);
    }

    /**
     * Render settings page
     */
    public static function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        ?>
        <div class="wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>

            <form action="options.php" method="post">
                <?php
                settings_fields('calcslive_settings');
                do_settings_sections('calcslive-settings');
                submit_button(__('Save Settings', 'calcslive-article-embed'));
                ?>
            </form>

            <hr>

            <h2><?php esc_html_e('Usage', 'calcslive-article-embed'); ?></h2>

            <h3><?php esc_html_e('Shortcode', 'calcslive-article-embed'); ?></h3>
            <p><?php esc_html_e('Use the shortcode to embed a CalcsLive article:', 'calcslive-article-embed'); ?></p>
            <pre><code>[calcslive id="YOUR_ARTICLE_ID"]</code></pre>

            <p><?php esc_html_e('With custom dimensions:', 'calcslive-article-embed'); ?></p>
            <pre><code>[calcslive id="YOUR_ARTICLE_ID" width="100%" height="800"]</code></pre>

            <h3><?php esc_html_e('Gutenberg Block', 'calcslive-article-embed'); ?></h3>
            <p><?php esc_html_e('Search for "CalcsLive" in the block editor to add the CalcsLive Article block.', 'calcslive-article-embed'); ?></p>

            <h3><?php esc_html_e('Physical Quantity Shortcodes', 'calcslive-article-embed'); ?></h3>
            <p><?php esc_html_e('Display interactive unit-aware values (no Embed Token needed):', 'calcslive-article-embed'); ?></p>
            <pre><code>[calcslive_qty value="25.4" unit="mm"]</code></pre>
            <pre><code>[calcslive_qty_pair values="10,20" unit="cm"]</code></pre>
            <pre><code>[calcslive_qty_triplet values="1,2,3" unit="m" dp="1"]</code></pre>
            <p class="description"><?php esc_html_e('Visitors can click the unit to convert between compatible units.', 'calcslive-article-embed'); ?></p>

            <h3><?php esc_html_e('Finding Your Article ID', 'calcslive-article-embed'); ?></h3>
            <p><?php esc_html_e('The article ID is the short code at the end of your CalcsLive article URL:', 'calcslive-article-embed'); ?></p>
            <pre><code>https://www.calcslive.com/view/<strong>3M7EJLZQ2-4N5</strong></code></pre>

            <hr>

            <h2><?php esc_html_e('Need Help?', 'calcslive-article-embed'); ?></h2>
            <ul>
                <li><a href="https://www.calcslive.com/help/wordpress-integration" target="_blank" rel="noopener"><?php esc_html_e('WordPress Integration Guide', 'calcslive-article-embed'); ?></a></li>
                <li><a href="https://www.calcslive.com/help/website-embedding" target="_blank" rel="noopener"><?php esc_html_e('Website Embedding Documentation', 'calcslive-article-embed'); ?></a></li>
                <li><a href="https://www.calcslive.com/services/embed" target="_blank" rel="noopener"><?php esc_html_e('CalcsLive Embedding Service', 'calcslive-article-embed'); ?></a></li>
            </ul>
        </div>
        <?php
    }
}
