<?php
/**
 * Launchmind Admin
 * 
 * WordPress admin interface for configuring the Launchmind Blog Connector.
 */

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

class Launchmind_Admin {
    
    /**
     * Initialize admin
     */
    public static function init() {
        add_action('admin_menu', array(__CLASS__, 'add_menu'));
        add_action('admin_init', array(__CLASS__, 'register_settings'));
        add_action('admin_enqueue_scripts', array(__CLASS__, 'enqueue_admin_assets'));
        
        // AJAX handlers
        add_action('wp_ajax_launchmind_test_connection', array(__CLASS__, 'ajax_test_connection'));
        add_action('wp_ajax_launchmind_clear_cache', array(__CLASS__, 'ajax_clear_cache'));
    }
    
    /**
     * Add admin menu
     */
    public static function add_menu() {
        add_options_page(
            __('Launchmind Blog', 'launchmind-blog'),
            __('Launchmind Blog', 'launchmind-blog'),
            'manage_options',
            'launchmind-blog',
            array(__CLASS__, 'render_settings_page')
        );
    }
    
    /**
     * Register settings
     */
    public static function register_settings() {
        // API Settings Section
        add_settings_section(
            'launchmind_api_settings',
            __('API Configuration', 'launchmind-blog'),
            array(__CLASS__, 'render_api_section'),
            'launchmind-blog'
        );
        
        // API Base URL
        register_setting('launchmind-blog', 'launchmind_blog_api_base', array(
            'type' => 'string',
            'sanitize_callback' => 'esc_url_raw',
            'default' => LAUNCHMIND_API_DEFAULT_BASE,
        ));
        
        add_settings_field(
            'launchmind_blog_api_base',
            __('API Base URL', 'launchmind-blog'),
            array(__CLASS__, 'render_api_base_field'),
            'launchmind-blog',
            'launchmind_api_settings'
        );
        
        // API Key
        register_setting('launchmind-blog', 'launchmind_blog_api_key', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));
        
        add_settings_field(
            'launchmind_blog_api_key',
            __('API Key', 'launchmind-blog'),
            array(__CLASS__, 'render_api_key_field'),
            'launchmind-blog',
            'launchmind_api_settings'
        );
        
        // Site ID
        register_setting('launchmind-blog', 'launchmind_blog_site_id', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '',
        ));
        
        add_settings_field(
            'launchmind_blog_site_id',
            __('Site ID', 'launchmind-blog'),
            array(__CLASS__, 'render_site_id_field'),
            'launchmind-blog',
            'launchmind_api_settings'
        );
        
        // Cache Settings Section
        add_settings_section(
            'launchmind_cache_settings',
            __('Cache Settings', 'launchmind-blog'),
            array(__CLASS__, 'render_cache_section'),
            'launchmind-blog'
        );
        
        // Cache TTL
        register_setting('launchmind-blog', 'launchmind_blog_cache_ttl', array(
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => LAUNCHMIND_CACHE_DEFAULT_TTL,
        ));
        
        add_settings_field(
            'launchmind_blog_cache_ttl',
            __('Cache Duration (seconds)', 'launchmind-blog'),
            array(__CLASS__, 'render_cache_ttl_field'),
            'launchmind-blog',
            'launchmind_cache_settings'
        );
        
        // Display Settings Section
        add_settings_section(
            'launchmind_display_settings',
            __('Display Settings', 'launchmind-blog'),
            array(__CLASS__, 'render_display_section'),
            'launchmind-blog'
        );
        
        // Blog Base Path
        register_setting('launchmind-blog', 'launchmind_blog_base_path', array(
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => '/blog/',
        ));
        
        add_settings_field(
            'launchmind_blog_base_path',
            __('Blog Base Path', 'launchmind-blog'),
            array(__CLASS__, 'render_base_path_field'),
            'launchmind-blog',
            'launchmind_display_settings'
        );
    }
    
    /**
     * Enqueue admin assets
     */
    public static function enqueue_admin_assets($hook) {
        if ($hook !== 'settings_page_launchmind-blog') {
            return;
        }
        
        wp_enqueue_style(
            'launchmind-admin',
            LAUNCHMIND_BLOG_PLUGIN_URL . 'admin/css/admin.css',
            array(),
            LAUNCHMIND_BLOG_VERSION
        );
        
        wp_enqueue_script(
            'launchmind-admin',
            LAUNCHMIND_BLOG_PLUGIN_URL . 'admin/js/admin.js',
            array('jquery'),
            LAUNCHMIND_BLOG_VERSION,
            true
        );
        
        wp_localize_script('launchmind-admin', 'launchmindAdmin', array(
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('launchmind_admin'),
            'strings' => array(
                'testing' => __('Testing connection...', 'launchmind-blog'),
                'success' => __('Connection successful!', 'launchmind-blog'),
                'error' => __('Connection failed:', 'launchmind-blog'),
                'clearing' => __('Clearing cache...', 'launchmind-blog'),
                'cleared' => __('Cache cleared!', 'launchmind-blog'),
            ),
        ));
    }
    
    /**
     * Render settings page
     */
    public static function render_settings_page() {
        if (!current_user_can('manage_options')) {
            return;
        }
        
        // Check for settings saved message
        if ( isset( $_GET['settings-updated'] ) && sanitize_text_field( wp_unslash( $_GET['settings-updated'] ) ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            add_settings_error('launchmind_messages', 'launchmind_message', __('Settings saved.', 'launchmind-blog'), 'updated');
        }
        
        ?>
        <div class="wrap launchmind-admin-wrap">
            <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
            
            <?php settings_errors('launchmind_messages'); ?>
            
            <div class="launchmind-admin-content">
                <div class="launchmind-admin-main">
                    <form action="options.php" method="post">
                        <?php
                        settings_fields('launchmind-blog');
                        do_settings_sections('launchmind-blog');
                        submit_button(__('Save Settings', 'launchmind-blog'));
                        ?>
                    </form>
                </div>
                
                <div class="launchmind-admin-sidebar">
                    <!-- Connection Test -->
                    <div class="launchmind-card">
                        <h3><?php esc_html_e('Test Connection', 'launchmind-blog'); ?></h3>
                        <p><?php esc_html_e('Verify your API connection is working correctly.', 'launchmind-blog'); ?></p>
                        <button type="button" id="launchmind-test-connection" class="button button-secondary">
                            <?php esc_html_e('Test Connection', 'launchmind-blog'); ?>
                        </button>
                        <div id="launchmind-test-result"></div>
                    </div>
                    
                    <!-- Cache Management -->
                    <div class="launchmind-card">
                        <h3><?php esc_html_e('Cache Management', 'launchmind-blog'); ?></h3>
                        <?php $cache_stats = Launchmind_Cache::get_stats(); ?>
                        <p>
                            <?php 
                            printf(
                                /* translators: %d: number of cached entries */
                                esc_html__('Currently cached: %d entries', 'launchmind-blog'),
                                $cache_stats['entries']
                            ); 
                            ?>
                        </p>
                        <button type="button" id="launchmind-clear-cache" class="button button-secondary">
                            <?php esc_html_e('Clear Cache', 'launchmind-blog'); ?>
                        </button>
                        <div id="launchmind-cache-result"></div>
                    </div>
                    
                    <!-- Shortcode Reference -->
                    <div class="launchmind-card">
                        <h3><?php esc_html_e('Shortcode Reference', 'launchmind-blog'); ?></h3>
                        
                        <h4><?php esc_html_e('Blog List', 'launchmind-blog'); ?></h4>
                        <code>[launchmind_blog]</code>
                        <p class="description">
                            <?php esc_html_e('Options: limit, columns, show_excerpt, show_image, show_date, show_author, show_tags', 'launchmind-blog'); ?>
                        </p>
                        
                        <h4><?php esc_html_e('Single Post', 'launchmind-blog'); ?></h4>
                        <code>[launchmind_post slug="your-post-slug"]</code>
                        <p class="description">
                            <?php esc_html_e('Options: slug (required), show_title, show_image, show_date, show_author, show_tags', 'launchmind-blog'); ?>
                        </p>
                    </div>
                    
                    <!-- Help -->
                    <div class="launchmind-card">
                        <h3><?php esc_html_e('Need Help?', 'launchmind-blog'); ?></h3>
                        <p><?php esc_html_e('Visit our documentation or contact support.', 'launchmind-blog'); ?></p>
                        <p>
                            <a href="https://launchmind.io/docs/wordpress" target="_blank" rel="noopener noreferrer" class="button button-secondary">
                                <?php esc_html_e('Documentation', 'launchmind-blog'); ?>
                            </a>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
    
    /**
     * Section renderers
     */
    public static function render_api_section() {
        echo '<p>' . esc_html__('Configure your Launchmind API connection.', 'launchmind-blog') . '</p>';
    }
    
    public static function render_cache_section() {
        echo '<p>' . esc_html__('Configure caching to improve performance.', 'launchmind-blog') . '</p>';
    }
    
    public static function render_display_section() {
        echo '<p>' . esc_html__('Configure how blog content is displayed.', 'launchmind-blog') . '</p>';
    }
    
    /**
     * Field renderers
     */
    public static function render_api_base_field() {
        $value = Launchmind_Blog_Connector::get_option('api_base', LAUNCHMIND_API_DEFAULT_BASE);
        ?>
        <input type="url" name="launchmind_blog_api_base" value="<?php echo esc_attr($value); ?>" class="regular-text">
        <p class="description"><?php esc_html_e('The Launchmind API base URL. Default: https://launchmind.io/api', 'launchmind-blog'); ?></p>
        <?php
    }
    
    public static function render_api_key_field() {
        $value = Launchmind_Blog_Connector::get_option('api_key', '');
        ?>
        <input type="password" name="launchmind_blog_api_key" value="<?php echo esc_attr($value); ?>" class="regular-text" autocomplete="off">
        <p class="description"><?php esc_html_e('Your Launchmind API key. Get this from your Launchmind dashboard.', 'launchmind-blog'); ?></p>
        <?php
    }
    
    public static function render_site_id_field() {
        $value = Launchmind_Blog_Connector::get_option('site_id', '');
        ?>
        <input type="text" name="launchmind_blog_site_id" value="<?php echo esc_attr($value); ?>" class="regular-text">
        <p class="description"><?php esc_html_e('Optional. Usually not needed - the API key is sufficient.', 'launchmind-blog'); ?></p>
        <?php
    }
    
    public static function render_cache_ttl_field() {
        $value = Launchmind_Blog_Connector::get_option('cache_ttl', LAUNCHMIND_CACHE_DEFAULT_TTL);
        ?>
        <input type="number" name="launchmind_blog_cache_ttl" value="<?php echo esc_attr($value); ?>" min="60" max="86400" class="small-text">
        <p class="description"><?php esc_html_e('How long to cache API responses (in seconds). Default: 600 (10 minutes). Minimum: 60 seconds.', 'launchmind-blog'); ?></p>
        <?php
    }
    
    public static function render_base_path_field() {
        $value = Launchmind_Blog_Connector::get_option('base_path', '/blog/');
        ?>
        <input type="text" name="launchmind_blog_base_path" value="<?php echo esc_attr($value); ?>" class="regular-text">
        <p class="description"><?php esc_html_e('The URL path for blog post links. Used in the blog list shortcode.', 'launchmind-blog'); ?></p>
        <?php
    }
    
    /**
     * AJAX: Test connection
     */
    public static function ajax_test_connection() {
        check_ajax_referer('launchmind_admin', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'launchmind-blog')));
        }
        
        $result = Launchmind_API::test_connection();
        
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
        }
        
        wp_send_json_success(array('message' => $result['message']));
    }
    
    /**
     * AJAX: Clear cache
     */
    public static function ajax_clear_cache() {
        check_ajax_referer('launchmind_admin', 'nonce');
        
        if (!current_user_can('manage_options')) {
            wp_send_json_error(array('message' => __('Permission denied', 'launchmind-blog')));
        }
        
        $count = Launchmind_Cache::clear_all();
        
        wp_send_json_success(array(
            'message' => sprintf(
                /* translators: %d: number of cleared entries */
                __('Cleared %d cache entries', 'launchmind-blog'),
                $count
            ),
        ));
    }
}

