<?php

/**
 * Settings page class
 *
 * @package ReplicateWP_Virtual_TryOn
 */

// Exit if accessed directly
if (! defined('ABSPATH')) {
    exit;
}

/**
 * Settings page class
 */
class RWPVTO_Settings
{

    /**
     * Single instance
     *
     * @var RWPVTO_Settings
     */
    private static $instance = null;

    /**
     * Get instance
     *
     * @return RWPVTO_Settings
     */
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor
     */
    private function __construct()
    {
        add_action('admin_menu', array($this, 'add_menu_page'), 60);
        add_action('admin_init', array($this, 'register_settings'));
    }

    /**
     * Add menu page
     */
    public function add_menu_page()
    {
        add_submenu_page(
            'rwpvto-dashboard',
            __('Settings', 'ai-virtual-try-on-for-woocommerce'),
            __('Settings', 'ai-virtual-try-on-for-woocommerce'),
            'manage_options',
            'rwpvto-settings',
            array($this, 'render_page')
        );
    }

    /**
     * Register settings
     */
    public function register_settings()
    {
        register_setting(
            'rwpvto_settings_group',
            'rwpvto_settings',
            array($this, 'sanitize_settings')
        );

        // API Settings Section
        add_settings_section(
            'rwpvto_api_section',
            __('API Configuration', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_api_section'),
            'rwpvto-settings'
        );

        add_settings_field(
            'api_key',
            __('Replicate API Key', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_api_key_field'),
            'rwpvto-settings',
            'rwpvto_api_section'
        );

        add_settings_field(
            'model_version',
            __('Model Version', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_model_version_field'),
            'rwpvto-settings',
            'rwpvto_api_section'
        );

        // Generation Settings Section
        add_settings_section(
            'rwpvto_generation_section',
            __('Generation Settings', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_generation_section'),
            'rwpvto-settings'
        );

        add_settings_field(
            'default_steps',
            __('Default Steps', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_steps_field'),
            'rwpvto-settings',
            'rwpvto_generation_section'
        );

        add_settings_field(
            'default_seed',
            __('Default Seed', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_seed_field'),
            'rwpvto-settings',
            'rwpvto_generation_section'
        );

        add_settings_field(
            'default_category',
            __('Default Category', 'ai-virtual-try-on-for-woocommerce'),
            array($this, 'render_category_field'),
            'rwpvto-settings',
            'rwpvto_generation_section'
        );
    }

    /**
     * Sanitize settings
     *
     * @param array $input Input data
     * @return array
     */
    public function sanitize_settings($input)
    {
        $sanitized = array();

        // Sanitize API key - trim whitespace only to preserve special characters in tokens
        if (isset($input['api_key'])) {
            $sanitized['api_key'] = trim($input['api_key']);
        }

        // Sanitize model version
        if (isset($input['model_version'])) {
            $sanitized['model_version'] = sanitize_text_field($input['model_version']);
        }

        // Sanitize default steps - ensure it's a positive integer within valid range
        if (isset($input['default_steps'])) {
            $steps = absint($input['default_steps']);
            $sanitized['default_steps'] = max(10, min(100, $steps)); // Clamp between 10-100
        }

        // Sanitize default seed - ensure it's a non-negative integer
        if (isset($input['default_seed'])) {
            $sanitized['default_seed'] = absint($input['default_seed']);
        }

        // Validate default category against whitelist
        if (isset($input['default_category'])) {
            $allowed_categories = array('upper_body', 'lower_body', 'dresses');
            $category = sanitize_text_field($input['default_category']);
            
            if (in_array($category, $allowed_categories, true)) {
                $sanitized['default_category'] = $category;
            } else {
                // If invalid, use default value
                $sanitized['default_category'] = 'upper_body';
            }
        }

        // Add success message
        add_settings_error(
            'rwpvto_settings',
            'rwpvto_settings_updated',
            __('Settings saved successfully!', 'ai-virtual-try-on-for-woocommerce'),
            'success'
        );

        return $sanitized;
    }

    /**
     * Render settings page
     */
    public function render_page()
    {
        if (! current_user_can('manage_options')) {
            return;
        }

        $settings = get_option('rwpvto_settings', array());
        $api_key_set = ! empty($settings['api_key']);

?>
        <div class="wrap rwpvto-settings-wrap">
            <h1 class="wp-heading-inline">
                <span class="dashicons dashicons-admin-settings" style="font-size: 28px; margin-right: 8px;"></span>
                <?php echo esc_html(get_admin_page_title()); ?>
            </h1>

            <hr class="wp-header-end">

            <?php settings_errors('rwpvto_settings'); ?>

            <!-- Settings Grid Layout -->
            <div class="rwpvto-settings-grid">

                <!-- Main Settings Form -->
                <div class="rwpvto-settings-main">
                    <form method="post" action="options.php" id="rwpvto-settings-form">
                        <?php settings_fields('rwpvto_settings_group'); ?>

                        <!-- API Configuration Card -->
                        <div class="rwpvto-settings-card">
                            <div class="rwpvto-settings-card-header">
                                <h2>
                                    <span class="dashicons dashicons-admin-network"></span>
                                    <?php esc_html_e('API Configuration', 'ai-virtual-try-on-for-woocommerce'); ?>
                                </h2>
                                <p class="description">
                                    <?php
                                    echo wp_kses_post(
                                        sprintf(
                                            /* translators: %s: Replicate.com link */
                                            __('Connect to Replicate.com to enable AI-powered virtual try-on. Get your API key from %s.', 'ai-virtual-try-on-for-woocommerce'),
                                            '<a href="https://replicate.com/account/api-tokens" target="_blank">Replicate.com <span class="dashicons dashicons-external" style="font-size: 14px;"></span></a>'
                                        )
                                    );
                                    ?>
                                </p>
                            </div>
                            <div class="rwpvto-settings-card-body">
                                <?php do_settings_fields('rwpvto-settings', 'rwpvto_api_section'); ?>
                            </div>
                        </div>

                        <!-- Generation Settings Card -->
                        <div class="rwpvto-settings-card">
                            <div class="rwpvto-settings-card-header">
                                <h2>
                                    <span class="dashicons dashicons-admin-generic"></span>
                                    <?php esc_html_e('Generation Settings', 'ai-virtual-try-on-for-woocommerce'); ?>
                                </h2>
                                <p class="description">
                                    <?php esc_html_e('Configure default parameters for AI image generation. These can be adjusted per-product.', 'ai-virtual-try-on-for-woocommerce'); ?>
                                </p>
                            </div>
                            <div class="rwpvto-settings-card-body">
                                <?php do_settings_fields('rwpvto-settings', 'rwpvto_generation_section'); ?>
                            </div>
                        </div>

                        <?php submit_button(__('Save Settings', 'ai-virtual-try-on-for-woocommerce'), 'primary large', 'submit', true); ?>
                    </form>
                </div>

                <!-- Sidebar -->
                <div class="rwpvto-settings-sidebar">

                    <!-- API Status Card -->
                    <div class="rwpvto-settings-card rwpvto-status-card">
                        <div class="rwpvto-settings-card-header">
                            <h3>
                                <span class="dashicons dashicons-info"></span>
                                <?php esc_html_e('API Status', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </h3>
                        </div>
                        <div class="rwpvto-settings-card-body">
                            <div class="rwpvto-status-indicator <?php echo $api_key_set ? 'connected' : 'disconnected'; ?>">
                                <span class="rwpvto-status-dot"></span>
                                <span class="rwpvto-status-text">
                                    <?php echo $api_key_set ? esc_html__('API Key Configured', 'ai-virtual-try-on-for-woocommerce') : esc_html__('No API Key Set', 'ai-virtual-try-on-for-woocommerce'); ?>
                                </span>
                            </div>

                            <button type="button" class="button button-secondary rwpvto-test-api-btn" style="width: 100%; margin-top: 15px;" <?php echo !$api_key_set ? 'disabled' : ''; ?>>
                                <span class="dashicons dashicons-update"></span>
                                <?php esc_html_e('Test Connection', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </button>
                            <div class="rwpvto-test-result"></div>
                        </div>
                    </div>

                    <!-- Quick Links Card -->
                    <div class="rwpvto-settings-card">
                        <div class="rwpvto-settings-card-header">
                            <h3>
                                <span class="dashicons dashicons-external"></span>
                                <?php esc_html_e('Quick Links', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </h3>
                        </div>
                        <div class="rwpvto-settings-card-body">
                            <ul class="rwpvto-quick-links">
                                <li>
                                    <a href="https://replicate.com/account/api-tokens" target="_blank">
                                        <span class="dashicons dashicons-admin-network"></span>
                                        <?php esc_html_e('Get API Key', 'ai-virtual-try-on-for-woocommerce'); ?>
                                    </a>
                                </li>
                                <li>
                                    <a href="https://replicate.com/account/billing" target="_blank">
                                        <span class="dashicons dashicons-chart-line"></span>
                                        <?php esc_html_e('View Usage & Billing', 'ai-virtual-try-on-for-woocommerce'); ?>
                                    </a>
                                </li>
                                <li>
                                    <a href="https://replicate.com/cuuupid/idm-vton" target="_blank">
                                        <span class="dashicons dashicons-info"></span>
                                        <?php esc_html_e('IDM-VTON Model Info', 'ai-virtual-try-on-for-woocommerce'); ?>
                                    </a>
                                </li>
                                <li>
                                    <a href="<?php echo esc_url(admin_url('admin.php?page=rwpvto-dashboard')); ?>">
                                        <span class="dashicons dashicons-images-alt2"></span>
                                        <?php esc_html_e('View Dashboard', 'ai-virtual-try-on-for-woocommerce'); ?>
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>

                    <!-- Cost Info Card -->
                    <div class="rwpvto-settings-card rwpvto-info-card">
                        <div class="rwpvto-settings-card-header">
                            <h3>
                                <span class="dashicons dashicons-money-alt"></span>
                                <?php esc_html_e('Pricing Info', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </h3>
                        </div>
                        <div class="rwpvto-settings-card-body">
                            <p style="margin: 0 0 10px 0; font-size: 13px; line-height: 1.6;">
                                <?php esc_html_e('Replicate.com charges approximately:', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </p>
                            <div class="rwpvto-price-display">
                                <strong>$0.01-0.03</strong> <?php esc_html_e('per image', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </div>
                            <p style="margin: 10px 0 0 0; font-size: 12px; color: #666;">
                                <?php esc_html_e('Actual pricing may vary. Check Replicate.com for current rates.', 'ai-virtual-try-on-for-woocommerce'); ?>
                            </p>
                        </div>
                    </div>

                </div>

            </div>
        </div>
    <?php
    }

    /**
     * Render API section description
     */
    public function render_api_section()
    {
    ?>
        <p>
            <?php
            echo wp_kses_post(
                sprintf(
                    /* translators: %s: Replicate.com link */
                    __('Enter your Replicate.com API credentials. Get your API key from %s.', 'ai-virtual-try-on-for-woocommerce'),
                    '<a href="https://replicate.com/account/api-tokens" target="_blank">Replicate.com</a>'
                )
            );
            ?>
        </p>
    <?php
    }

    /**
     * Render API key field
     */
    public function render_api_key_field()
    {
        $settings = get_option('rwpvto_settings', array());
        $api_key = isset($settings['api_key']) ? $settings['api_key'] : '';
    ?>
        <div class="rwpvto-field-group">
            <label for="rwpvto_api_key">
                <strong><?php esc_html_e('Replicate API Key', 'ai-virtual-try-on-for-woocommerce'); ?></strong>
            </label>
            <div class="rwpvto-input-group">
                <input
                    type="password"
                    name="rwpvto_settings[api_key]"
                    id="rwpvto_api_key"
                    value="<?php echo esc_attr($api_key); ?>"
                    class="large-text rwpvto-api-key-input"
                    placeholder="r8_..." />
                <button type="button" class="button rwpvto-toggle-api-key" title="<?php esc_attr_e('Show/Hide API Key', 'ai-virtual-try-on-for-woocommerce'); ?>">
                    <span class="dashicons dashicons-visibility"></span>
                </button>
            </div>
            <p class="description">
                <?php esc_html_e('Your Replicate API token (starts with "r8_"). Keep this secure!', 'ai-virtual-try-on-for-woocommerce'); ?>
            </p>
        </div>
    <?php
    }

    /**
     * Render model version field
     */
    public function render_model_version_field()
    {
        $settings = get_option('rwpvto_settings', array());
        $model_version = isset($settings['model_version']) ? $settings['model_version'] : 'cuuupid/idm-vton:0513734a452173b8173e907e3a59d19a36266e55b48528559432bd21c7d7e985';
    ?>
        <div class="rwpvto-field-group">
            <label for="rwpvto_model_version">
                <strong><?php esc_html_e('Model Version', 'ai-virtual-try-on-for-woocommerce'); ?></strong>
                <span class="rwpvto-badge rwpvto-badge-advanced"><?php esc_html_e('Advanced', 'ai-virtual-try-on-for-woocommerce'); ?></span>
            </label>
            <input
                type="text"
                name="rwpvto_settings[model_version]"
                id="rwpvto_model_version"
                value="<?php echo esc_attr($model_version); ?>"
                class="large-text code"
                readonly />
            <p class="description">
                <?php esc_html_e('The Replicate AI model version. Leave as default unless you know what you\'re doing.', 'ai-virtual-try-on-for-woocommerce'); ?>
            </p>
        </div>
    <?php
    }

    /**
     * Render generation section description
     */
    public function render_generation_section()
    {
    ?>
        <p><?php esc_html_e('Configure default parameters for image generation.', 'ai-virtual-try-on-for-woocommerce'); ?></p>
    <?php
    }

    /**
     * Render steps field
     */
    public function render_steps_field()
    {
        $settings = get_option('rwpvto_settings', array());
        $steps = isset($settings['default_steps']) ? $settings['default_steps'] : 30;
    ?>
        <div class="rwpvto-field-group">
            <label for="rwpvto_default_steps">
                <strong><?php esc_html_e('Default Steps', 'ai-virtual-try-on-for-woocommerce'); ?></strong>
                <span class="rwpvto-badge rwpvto-badge-recommended"><?php esc_html_e('Recommended: 30', 'ai-virtual-try-on-for-woocommerce'); ?></span>
            </label>
            <div style="display: flex; align-items: center; gap: 15px;">
                <input
                    type="range"
                    id="rwpvto_steps_range"
                    value="<?php echo esc_attr($steps); ?>"
                    min="10"
                    max="100"
                    step="1"
                    style="flex: 1;" />
                <input
                    type="number"
                    name="rwpvto_settings[default_steps]"
                    id="rwpvto_default_steps"
                    value="<?php echo esc_attr($steps); ?>"
                    min="10"
                    max="100"
                    step="1"
                    style="width: 80px;" />
            </div>
            <p class="description">
                <?php esc_html_e('Number of denoising steps (10-100). Higher = better quality but slower. 30 is optimal.', 'ai-virtual-try-on-for-woocommerce'); ?>
            </p>
        </div>
    <?php
    }

    /**
     * Render seed field
     */
    public function render_seed_field()
    {
        $settings = get_option('rwpvto_settings', array());
        $seed = isset($settings['default_seed']) ? $settings['default_seed'] : 42;
    ?>
        <div class="rwpvto-field-group">
            <label for="rwpvto_default_seed">
                <strong><?php esc_html_e('Default Seed', 'ai-virtual-try-on-for-woocommerce'); ?></strong>
            </label>
            <input
                type="number"
                name="rwpvto_settings[default_seed]"
                id="rwpvto_default_seed"
                value="<?php echo esc_attr($seed); ?>"
                min="0"
                max="999999"
                class="regular-text" />
            <p class="description">
                <?php esc_html_e('Random seed for reproducible results. Same seed = similar outputs. Leave at 42 for variety.', 'ai-virtual-try-on-for-woocommerce'); ?>
            </p>
        </div>
    <?php
    }

    /**
     * Render category field
     */
    public function render_category_field()
    {
        $settings = get_option('rwpvto_settings', array());
        $category = isset($settings['default_category']) ? $settings['default_category'] : 'upper_body';

        $categories = array(
            'upper_body' => __('Upper Body (Shirts, Tops, Jackets)', 'ai-virtual-try-on-for-woocommerce'),
            'lower_body' => __('Lower Body (Pants, Skirts)', 'ai-virtual-try-on-for-woocommerce'),
            'dresses' => __('Dresses', 'ai-virtual-try-on-for-woocommerce'),
        );
    ?>
        <div class="rwpvto-field-group">
            <label for="rwpvto_default_category">
                <strong><?php esc_html_e('Default Category', 'ai-virtual-try-on-for-woocommerce'); ?></strong>
            </label>
            <select name="rwpvto_settings[default_category]" id="rwpvto_default_category" class="regular-text">
                <?php foreach ($categories as $value => $label) : ?>
                    <option value="<?php echo esc_attr($value); ?>" <?php selected($category, $value); ?>>
                        <?php echo esc_html($label); ?>
                    </option>
                <?php endforeach; ?>
            </select>
            <p class="description">
                <?php esc_html_e('Default garment category for try-on generation. Can be changed per-product.', 'ai-virtual-try-on-for-woocommerce'); ?>
            </p>
        </div>
<?php
    }
}
