<?php
if (!defined('ABSPATH')) exit;

/**
 * Pinery Flow — Admin Settings Page
 */
class Pinery_Flow_Admin {

    public static function init() {
        add_action('admin_menu', [__CLASS__, 'add_menu']);
        add_action('admin_init', [__CLASS__, 'register_settings']);
        add_action('admin_post_pinery_flow_manual_run', [__CLASS__, 'handle_manual_run']);
        add_action('admin_post_pinery_flow_clear_logs', [__CLASS__, 'handle_clear_logs']);
        add_action('admin_post_pinery_flow_pinterest_callback', [__CLASS__, 'handle_pinterest_callback']);
        add_action('admin_post_pinery_flow_pinterest_disconnect', [__CLASS__, 'handle_pinterest_disconnect']);
        add_action('admin_post_pinery_flow_save_settings', [__CLASS__, 'handle_save_settings']);
    }

    public static function add_menu() {
        add_menu_page(
            'Pinery Flow',
            'Pinery Flow',
            'manage_options',
            'pinery-flow',
            [__CLASS__, 'render_page'],
            'dashicons-update',
            58
        );
        add_submenu_page(
            'pinery-flow',
            __('Logs — Pinery Flow', 'pinery-flow'),
            __('Logs', 'pinery-flow'),
            'manage_options',
            'pinery-flow-logs',
            [__CLASS__, 'render_logs_page']
        );
    }

    public static function register_settings() {
        // Migrate old xAI key to new generic key
        if (empty(get_option('pinery_flow_api_key', '')) && !empty(get_option('pinery_flow_xai_api_key', ''))) {
            update_option('pinery_flow_api_key', get_option('pinery_flow_xai_api_key'));
        }

        // API
        register_setting('pinery_flow_settings', 'pinery_flow_ai_provider', ['sanitize_callback' => 'sanitize_text_field', 'default' => 'xai']);
        register_setting('pinery_flow_settings', 'pinery_flow_api_key', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_amazon_tag', ['sanitize_callback' => 'sanitize_text_field']);

        // Creators API
        register_setting('pinery_flow_settings', 'pinery_flow_creators_enabled',      ['sanitize_callback' => 'absint', 'default' => 0]);
        register_setting('pinery_flow_settings', 'pinery_flow_creators_client_id',     ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_creators_client_secret', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_creators_marketplace',   ['sanitize_callback' => 'sanitize_text_field', 'default' => 'www.amazon.com']);
        register_setting('pinery_flow_settings', 'pinery_flow_creators_price_ttl',     ['sanitize_callback' => 'absint', 'default' => 60]);

        // Content
        register_setting('pinery_flow_settings', 'pinery_flow_products_per_run', ['sanitize_callback' => 'absint', 'default' => 5]);
        register_setting('pinery_flow_settings', 'pinery_flow_post_status', ['sanitize_callback' => 'sanitize_text_field', 'default' => 'publish']);
        register_setting('pinery_flow_settings', 'pinery_flow_default_author', ['sanitize_callback' => 'absint', 'default' => 1]);
        register_setting('pinery_flow_settings', 'pinery_flow_auto_seo', ['sanitize_callback' => 'absint', 'default' => 1]);
        register_setting('pinery_flow_settings', 'pinery_flow_categories', ['sanitize_callback' => [__CLASS__, 'sanitize_cat_selection']]);

        // Image
        register_setting('pinery_flow_settings', 'pinery_flow_image_source', ['sanitize_callback' => 'sanitize_text_field', 'default' => 'ai']);
        register_setting('pinery_flow_settings', 'pinery_flow_image_ratio', ['sanitize_callback' => 'sanitize_text_field', 'default' => '9:16']);
        register_setting('pinery_flow_settings', 'pinery_flow_show_price_overlay', ['sanitize_callback' => 'absint', 'default' => 1]);
        register_setting('pinery_flow_settings', 'pinery_flow_price_color', ['sanitize_callback' => 'sanitize_hex_color', 'default' => '#ffffff']);
        register_setting('pinery_flow_settings', 'pinery_flow_price_size', ['sanitize_callback' => 'absint', 'default' => 14]);
        register_setting('pinery_flow_settings', 'pinery_flow_rating_color', ['sanitize_callback' => 'sanitize_hex_color', 'default' => '#ffd700']);
        register_setting('pinery_flow_settings', 'pinery_flow_rating_size', ['sanitize_callback' => 'absint', 'default' => 12]);

        // Social — Pinterest
        register_setting('pinery_flow_settings', 'pinery_flow_pinterest_enabled', ['sanitize_callback' => 'absint', 'default' => 0]);
        register_setting('pinery_flow_settings', 'pinery_flow_pinterest_token', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_pinterest_app_id', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_pinterest_app_secret', ['sanitize_callback' => 'sanitize_text_field']);
        register_setting('pinery_flow_settings', 'pinery_flow_pinterest_board', ['sanitize_callback' => 'sanitize_text_field']);

        // Schedule
        register_setting('pinery_flow_settings', 'pinery_flow_cron_minutes', ['sanitize_callback' => 'absint', 'default' => 6]);
        register_setting('pinery_flow_settings', 'pinery_flow_auto_enabled', ['sanitize_callback' => 'absint', 'default' => 0]);

        // Button text
        register_setting('pinery_flow_settings', 'pinery_flow_btn_text', ['sanitize_callback' => 'sanitize_text_field', 'default' => 'Shop on Amazon']);

        // Custom categories
        register_setting('pinery_flow_settings', 'pinery_flow_custom_categories', ['sanitize_callback' => [__CLASS__, 'sanitize_custom_cats']]);
    }

    public static function sanitize_custom_cats($input) {
        if (!is_array($input)) return [];
        $clean = [];
        foreach ($input as $item) {
            $name = sanitize_text_field($item['name'] ?? '');
            $url  = esc_url_raw($item['url'] ?? '');
            if (!empty($name) && !empty($url)) {
                $clean[] = ['name' => $name, 'url' => $url];
            }
        }
        return $clean;
    }

    public static function sanitize_cat_selection($input) {
        if (!is_array($input)) return [];
        $valid = [];
        $tree = Pinery_Flow_Pipeline::amazon_departments();
        foreach ($input as $slug) {
            $slug = sanitize_text_field($slug);
            if (strpos($slug, '/') !== false) {
                list($dept_id, $sub_id) = explode('/', $slug, 2);
                if (isset($tree[$dept_id]['subcategories'][$sub_id])) {
                    $valid[] = $slug;
                }
            } elseif (isset($tree[$slug]) && empty($tree[$slug]['subcategories'])) {
                $valid[] = $slug;
            }
        }
        return $valid;
    }

    public static function sanitize_array($input) {
        return is_array($input) ? array_map('sanitize_text_field', $input) : [];
    }

    /**
     * Check whether any popular SEO plugin is active.
     */
    public static function has_seo_plugin() {
        if (defined('RANK_MATH_VERSION'))          return true;
        if (defined('WPSEO_VERSION'))              return true;
        if (defined('AIOSEO_PLUGIN_VERSION'))     return true;
        if (class_exists('SEOPress'))              return true;
        if (defined('SQUIRRLY_SEO_VERSION'))       return true;
        if (function_exists('the_seo_framework'))  return true;
        return false;
    }

    public static function handle_save_settings() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('pinery_flow_save_settings');

        // List all allowed option keys and their sanitizers
        $options = [
            'pinery_flow_ai_provider'         => 'sanitize_text_field',
            'pinery_flow_api_key'             => 'sanitize_text_field',
            'pinery_flow_amazon_tag'          => 'sanitize_text_field',
            'pinery_flow_products_per_run'    => 'absint',
            'pinery_flow_post_status'         => 'sanitize_text_field',
            'pinery_flow_default_author'      => 'absint',
            'pinery_flow_auto_seo'            => 'absint',
            'pinery_flow_image_source'           => 'sanitize_text_field',
            'pinery_flow_image_ratio'            => 'sanitize_text_field',
            'pinery_flow_show_price_overlay'  => 'absint',
            'pinery_flow_price_color'         => 'sanitize_hex_color',
            'pinery_flow_price_size'          => 'absint',
            'pinery_flow_rating_color'        => 'sanitize_hex_color',
            'pinery_flow_rating_size'         => 'absint',
            'pinery_flow_pinterest_enabled'   => 'absint',
            'pinery_flow_pinterest_token'     => 'sanitize_text_field',
            'pinery_flow_pinterest_app_id'    => 'sanitize_text_field',
            'pinery_flow_pinterest_app_secret'=> 'sanitize_text_field',
            'pinery_flow_pinterest_board'     => 'sanitize_text_field',
            'pinery_flow_cron_minutes'           => 'absint',
            'pinery_flow_auto_enabled'           => 'absint',
            'pinery_flow_btn_text'               => 'sanitize_text_field',
            'pinery_flow_creators_enabled'       => 'absint',
            'pinery_flow_creators_client_id'     => 'sanitize_text_field',
            'pinery_flow_creators_client_secret' => 'sanitize_text_field',
            'pinery_flow_creators_marketplace'   => 'sanitize_text_field',
            'pinery_flow_creators_price_ttl'     => 'absint',
        ];

        foreach ($options as $key => $sanitizer) {
            if (isset($_POST[$key])) {
                $val = $_POST[$key];
                // Checkboxes: absent in POST = 0
            } else {
                $val = 0;
            }
            if ($sanitizer === 'absint') {
                $val = absint($val);
            } elseif ($sanitizer === 'sanitize_hex_color') {
                $val = sanitize_hex_color($val);
            } else {
                $val = sanitize_text_field($val);
            }
            // Skip empty client_secret to avoid overwriting saved credential
            if ($key === 'pinery_flow_creators_client_secret' && empty($val)) continue;

            update_option($key, $val);
        }

        // Categories (array)
        if (isset($_POST['pinery_flow_categories'])) {
            update_option('pinery_flow_categories', self::sanitize_cat_selection($_POST['pinery_flow_categories']));
        } else {
            update_option('pinery_flow_categories', []);
        }

        // Custom categories (array of {name, url})
        if (isset($_POST['pinery_flow_custom_categories'])) {
            update_option('pinery_flow_custom_categories', self::sanitize_custom_cats($_POST['pinery_flow_custom_categories']));
        } else {
            update_option('pinery_flow_custom_categories', []);
        }

        // Force Auto SEO off when an SEO plugin is active (avoid duplicate meta tags)
        if (self::has_seo_plugin()) {
            update_option('pinery_flow_auto_seo', 0);
        }

        wp_cache_flush();

        set_transient('pinery_flow_notice', ['success', __('Settings saved.', 'pinery-flow')], 60);
        wp_redirect(admin_url('admin.php?page=pinery-flow'));
        exit;
    }

    public static function handle_manual_run() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('pinery_flow_manual_run');

        $result = Pinery_Flow_Pipeline::run();

        if (is_wp_error($result)) {
            Pinery_Flow_Cron::log(0, 'manual: ' . $result->get_error_message());
            set_transient('pinery_flow_notice', ['error', $result->get_error_message()], 60);
        } else {
            $count = count($result);
            Pinery_Flow_Cron::log($count, 'manual: ok');
            set_transient('pinery_flow_notice', ['success', sprintf(__('Pipeline complete! Created %d posts.', 'pinery-flow'), $count)], 60);
        }

        wp_redirect(admin_url('admin.php?page=pinery-flow'));
        exit;
    }

    public static function handle_clear_logs() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('pinery_flow_clear_logs');
        update_option('pinery_flow_detail_logs', []);
        wp_redirect(admin_url('admin.php?page=pinery-flow-logs&cleared=1'));
        exit;
    }

    public static function handle_pinterest_callback() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        if (empty($_GET['code']) || empty($_GET['state']) || !wp_verify_nonce($_GET['state'], 'pinterest_oauth')) {
            wp_die('Invalid OAuth state or missing code.');
        }

        $app_id     = get_option('pinery_flow_pinterest_app_id', '');
        $app_secret = get_option('pinery_flow_pinterest_app_secret', '');
        $redirect   = admin_url('admin-post.php?action=pinery_flow_pinterest_callback');
        $code       = sanitize_text_field($_GET['code']);

        $body = ['grant_type' => 'authorization_code', 'code' => $code, 'redirect_uri' => $redirect];

        if ($app_secret) {
            // Standard tier: use Basic auth
            $response = wp_remote_post('https://api.pinterest.com/v5/oauth/token', [
                'headers' => [
                    'Authorization' => 'Basic ' . base64_encode($app_id . ':' . $app_secret),
                    'Content-Type'  => 'application/x-www-form-urlencoded',
                ],
                'body' => http_build_query($body),
                'timeout' => 15,
            ]);
        } else {
            // Trial tier: public client mode (no secret)
            $body['client_id'] = $app_id;
            $response = wp_remote_post('https://api.pinterest.com/v5/oauth/token', [
                'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
                'body'    => http_build_query($body),
                'timeout' => 15,
            ]);
        }

        if (is_wp_error($response)) {
            set_transient('pinery_flow_notice', ['error', 'OAuth error: ' . $response->get_error_message()], 60);
            wp_redirect(admin_url('admin.php?page=pinery-flow'));
            exit;
        }

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

        if (!empty($body['access_token'])) {
            update_option('pinery_flow_pinterest_token', sanitize_text_field($body['access_token']));
            if (!empty($body['refresh_token'])) {
                update_option('pinery_flow_pinterest_refresh_token', sanitize_text_field($body['refresh_token']));
            }
            if (!empty($body['expires_in'])) {
                update_option('pinery_flow_pinterest_token_expiry', time() + (int) $body['expires_in']);
            }
            set_transient('pinery_flow_notice', ['success', __('Pinterest connected successfully!', 'pinery-flow')], 60);
        } else {
            $err = $body['message'] ?? 'Unknown error';
            set_transient('pinery_flow_notice', ['error', 'Pinterest OAuth failed: ' . esc_html($err)], 60);
        }

        wp_redirect(admin_url('admin.php?page=pinery-flow'));
        exit;
    }

    public static function handle_pinterest_disconnect() {
        if (!current_user_can('manage_options')) wp_die('Unauthorized');
        check_admin_referer('pinery_flow_pinterest_disconnect');
        delete_option('pinery_flow_pinterest_token');
        delete_option('pinery_flow_pinterest_refresh_token');
        delete_option('pinery_flow_pinterest_token_expiry');
        set_transient('pinery_flow_notice', ['success', __('Pinterest disconnected.', 'pinery-flow')], 60);
        wp_redirect(admin_url('admin.php?page=pinery-flow'));
        exit;
    }

    public static function render_page() {
        // Handle form submission
        $notice = null;
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['pinery_save'])) {
            if (!current_user_can('manage_options')) wp_die('Unauthorized');
            if (!wp_verify_nonce($_POST['pinery_settings_nonce'] ?? '', 'pinery_flow_save_settings')) {
                wp_die(__('Security check failed. Please refresh the page and try again.', 'pinery-flow'));
            }

            $options = [
                'pinery_flow_ai_provider'         => 'sanitize_text_field',
                'pinery_flow_api_key'             => 'sanitize_text_field',
                'pinery_flow_amazon_tag'          => 'sanitize_text_field',
                'pinery_flow_products_per_run'    => 'absint',
                'pinery_flow_post_status'         => 'sanitize_text_field',
                'pinery_flow_default_author'      => 'absint',
                'pinery_flow_auto_seo'            => 'absint',
                'pinery_flow_image_source'           => 'sanitize_text_field',
            'pinery_flow_image_ratio'            => 'sanitize_text_field',
                'pinery_flow_show_price_overlay'  => 'absint',
                'pinery_flow_price_color'         => 'sanitize_hex_color',
                'pinery_flow_price_size'          => 'absint',
                'pinery_flow_rating_color'        => 'sanitize_hex_color',
                'pinery_flow_rating_size'         => 'absint',
                'pinery_flow_pinterest_enabled'   => 'absint',
                'pinery_flow_pinterest_token'     => 'sanitize_text_field',
                'pinery_flow_pinterest_app_id'    => 'sanitize_text_field',
                'pinery_flow_pinterest_app_secret'=> 'sanitize_text_field',
                'pinery_flow_pinterest_board'     => 'sanitize_text_field',
                'pinery_flow_cron_minutes'           => 'absint',
                'pinery_flow_auto_enabled'           => 'absint',
                'pinery_flow_btn_text'               => 'sanitize_text_field',
                'pinery_flow_creators_enabled'       => 'absint',
                'pinery_flow_creators_client_id'     => 'sanitize_text_field',
                'pinery_flow_creators_client_secret' => 'sanitize_text_field',
                'pinery_flow_creators_marketplace'   => 'sanitize_text_field',
                'pinery_flow_creators_price_ttl'     => 'absint',
                'pinery_flow_creators_partner_tag'   => 'sanitize_text_field',
            ];

            foreach ($options as $key => $sanitizer) {
                $val = isset($_POST[$key]) ? $_POST[$key] : 0;
                if ($sanitizer === 'absint') $val = absint($val);
                elseif ($sanitizer === 'sanitize_hex_color') $val = sanitize_hex_color($val);
                else $val = sanitize_text_field($val);
                // Skip empty client_secret to avoid overwriting saved credential
                if ($key === 'pinery_flow_creators_client_secret' && empty($val)) continue;
                update_option($key, $val);
            }

            if (isset($_POST['pinery_flow_categories'])) {
                update_option('pinery_flow_categories', self::sanitize_cat_selection($_POST['pinery_flow_categories']));
            } else {
                update_option('pinery_flow_categories', []);
            }

            if (isset($_POST['pinery_flow_custom_categories'])) {
                update_option('pinery_flow_custom_categories', self::sanitize_custom_cats($_POST['pinery_flow_custom_categories']));
            } else {
                update_option('pinery_flow_custom_categories', []);
            }

            // Force Auto SEO off when an SEO plugin is active (avoid duplicate meta tags)
            if (self::has_seo_plugin()) {
                update_option('pinery_flow_auto_seo', 0);
            }

            $notice = ['success', __('Settings saved.', 'pinery-flow')];
        }

        if (!$notice) {
            $notice = get_transient('pinery_flow_notice');
        }
        $last_run = get_option('pinery_flow_last_run', '');
        $published_count = count(get_option('pinery_flow_published_products', []));
        ?>
        <div class="wrap" style="max-width:780px;">
            <h1>Pinery Flow</h1>
            <p style="color:#666;font-size:14px;">
                <?php _e('AI-powered Amazon affiliate content pipeline. Generates lifestyle images, writes copy, and auto-publishes to your site.', 'pinery-flow'); ?>
            </p>

            <?php if ($notice): ?>
                <div class="notice notice-<?php echo esc_attr($notice[0]); ?> is-dismissible" style="margin:15px 0;">
                    <p><?php echo esc_html($notice[1]); ?></p>
                </div>
            <?php endif; ?>

            <!-- Status Card -->
            <div class="card" style="max-width:100%; padding:16px 20px; margin:16px 0; background:#fff; border:1px solid #ccd0d4; border-radius:4px;">
                <h3 style="margin-top:0;"><?php _e('Pipeline Status', 'pinery-flow'); ?></h3>
                <?php if (function_exists('pinery_flow_has_license') && !pinery_flow_has_license()): ?>
                    <p style="color:#d63638;font-weight:600;">
                        ⚠ <?php _e('No active license — pipeline is disabled.', 'pinery-flow'); ?>
                        <?php if (function_exists('pinery_flow_fs')): ?>
                            <a href="<?php echo esc_url(pinery_flow_fs()->get_account_url()); ?>" style="margin-left:8px;">
                                <?php _e('Activate License →', 'pinery-flow'); ?>
                            </a>
                        <?php endif; ?>
                    </p>
                <?php else: ?>
                <p>
                    <strong><?php _e('Last run:', 'pinery-flow'); ?></strong>
                    <?php echo $last_run ? esc_html($last_run) : __('Never', 'pinery-flow'); ?>
                    &nbsp;|&nbsp;
                    <strong><?php _e('Published:', 'pinery-flow'); ?></strong> <?php echo (int) $published_count; ?> <?php _e('products', 'pinery-flow'); ?>
                </p>
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>" style="display:inline;">
                    <?php wp_nonce_field('pinery_flow_manual_run'); ?>
                    <input type="hidden" name="action" value="pinery_flow_manual_run">
                    <button type="submit" class="button button-primary" onclick="return confirm('<?php esc_attr_e('Run the pipeline now? This may take 2-5 minutes.', 'pinery-flow'); ?>')">
                        <?php _e('Run Pipeline Now', 'pinery-flow'); ?>
                    </button>
                </form>
                <?php endif; ?>
            </div>

            <!-- Logs -->
            <?php self::render_logs(); ?>

            <form method="post" action="<?php echo admin_url('admin.php?page=pinery-flow'); ?>">
                <input type="hidden" name="pinery_settings_nonce" value="<?php echo wp_create_nonce('pinery_flow_save_settings'); ?>">
                <input type="hidden" name="pinery_save" value="1">
                <table class="form-table">
                    <!-- API Settings -->
                    <tr><th colspan="2"><h2><?php _e('API Settings', 'pinery-flow'); ?></h2></th></tr>
                    <tr>
                        <th><label><?php _e('AI Provider', 'pinery-flow'); ?></label></th>
                        <td>
                            <?php $provider = get_option('pinery_flow_ai_provider', 'xai'); ?>
                            <label style="margin-right:20px;">
                                <input type="radio" name="pinery_flow_ai_provider" value="xai" <?php checked('xai', $provider); ?> />
                                xAI (Grok)
                            </label>
                            <label style="margin-right:20px;">
                                <input type="radio" name="pinery_flow_ai_provider" value="openai" <?php checked('openai', $provider); ?> />
                                OpenAI (GPT + Image 2)
                            </label>
                            <label>
                                <input type="radio" name="pinery_flow_ai_provider" value="gemini" <?php checked('gemini', $provider); ?> />
                                Google Gemini
                            </label>
                            <p class="description"><?php _e('Select which AI provider to use for text and image generation.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_api_key"><?php _e('API Key', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="text" name="pinery_flow_api_key" id="pinery_flow_api_key"
                                   value="<?php echo esc_attr(get_option('pinery_flow_api_key', '')); ?>"
                                   class="regular-text" style="width:100%;max-width:400px;" />
                            <p class="description" id="pinery-key-help">
                                <?php $config = Pinery_Flow_Pipeline::get_provider_config(); ?>
                                <?php _e('Get your API key from', 'pinery-flow'); ?>
                                <a href="<?php echo esc_url($config['key_link']); ?>" target="_blank" id="pinery-key-link"><?php echo esc_html($config['key_link']); ?></a>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_amazon_tag"><?php _e('Amazon Affiliate Tag', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="text" name="pinery_flow_amazon_tag" id="pinery_flow_amazon_tag"
                                   value="<?php echo esc_attr(get_option('pinery_flow_amazon_tag', '')); ?>"
                                   class="regular-text" placeholder="yourtag-20" />
                            <p class="description"><?php _e('Your Amazon Associates tracking ID.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>

                    <!-- Creators API Settings -->
                    <tr><th colspan="2"><h3 style="margin-bottom:0;"><?php _e('Amazon Creators API', 'pinery-flow'); ?></h3></th></tr>
                    <tr>
                        <th><?php _e('Enable Creators API', 'pinery-flow'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="pinery_flow_creators_enabled" value="1" <?php checked(1, get_option('pinery_flow_creators_enabled', 0)); ?> />
                                <?php _e('Use Amazon Creators API instead of HTML scraping (more compliant, requires API credentials)', 'pinery-flow'); ?>
                            </label>
                            <p class="description">
                                <?php _e('You need a Client ID and Client Secret from', 'pinery-flow'); ?>
                                <a href="https://affiliate-program.amazon.com/creatorsapi" target="_blank">Amazon Associates Central → Tools → Creators API</a>.
                            </p>
                            <p style="color:#d63638;font-weight:600;margin:4px 0 0;">
                                ⚠ <?php _e('Requires at least 10 qualifying shipped sales in the last 30 days to activate. Until then, keep this enabled — the plugin will automatically fall back to HTML scraping.', 'pinery-flow'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_creators_client_id"><?php _e('Client ID', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="text" name="pinery_flow_creators_client_id" id="pinery_flow_creators_client_id"
                                   value="<?php echo esc_attr(get_option('pinery_flow_creators_client_id', '')); ?>"
                                   class="regular-text" style="width:100%;max-width:400px;" />
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_creators_client_secret"><?php _e('Client Secret', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="password" name="pinery_flow_creators_client_secret" id="pinery_flow_creators_client_secret"
                                   value="<?php echo get_option('pinery_flow_creators_client_secret', '') ? '••••••••' : ''; ?>"
                                   class="regular-text" style="width:100%;max-width:400px;"
                                   placeholder="<?php esc_attr_e('Leave blank to keep unchanged', 'pinery-flow'); ?>" />
                            <p class="description"><?php _e('For security, the saved secret is not displayed. Enter a new value only if you need to change it.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_creators_marketplace"><?php _e('Marketplace', 'pinery-flow'); ?></label></th>
                        <td>
                            <select name="pinery_flow_creators_marketplace" id="pinery_flow_creators_marketplace">
                                <?php
                                $mkp = get_option('pinery_flow_creators_marketplace', 'www.amazon.com');
                                $markets = [
                                    'www.amazon.com' => 'United States (amazon.com)',
                                    'www.amazon.ca'  => 'Canada (amazon.ca)',
                                    'www.amazon.co.uk' => 'United Kingdom (amazon.co.uk)',
                                    'www.amazon.de'  => 'Germany (amazon.de)',
                                    'www.amazon.fr'  => 'France (amazon.fr)',
                                    'www.amazon.it'  => 'Italy (amazon.it)',
                                    'www.amazon.es'  => 'Spain (amazon.es)',
                                    'www.amazon.co.jp' => 'Japan (amazon.co.jp)',
                                ];
                                foreach ($markets as $val => $label):
                                ?>
                                    <option value="<?php echo esc_attr($val); ?>" <?php selected($val, $mkp); ?>><?php echo esc_html($label); ?></option>
                                <?php endforeach; ?>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_creators_price_ttl"><?php _e('Price Cache (minutes)', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="number" name="pinery_flow_creators_price_ttl" id="pinery_flow_creators_price_ttl"
                                   value="<?php echo esc_attr(get_option('pinery_flow_creators_price_ttl', 60)); ?>"
                                   min="5" max="1440" class="small-text" />
                            <p class="description"><?php _e('How long to cache real-time prices before refreshing. Default 60 min. Lower = more API calls.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>

                    <!-- Content Settings -->
                    <tr><th colspan="2"><h2><?php _e('Content Settings', 'pinery-flow'); ?></h2></th></tr>
                    <tr>
                        <th><label for="pinery_flow_products_per_run"><?php _e('Products Per Run', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="number" name="pinery_flow_products_per_run" id="pinery_flow_products_per_run"
                                   value="<?php echo esc_attr(get_option('pinery_flow_products_per_run', 5)); ?>"
                                   min="1" max="20" class="small-text" />
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_post_status"><?php _e('Default Post Status', 'pinery-flow'); ?></label></th>
                        <td>
                            <select name="pinery_flow_post_status" id="pinery_flow_post_status">
                                <option value="publish" <?php selected('publish', get_option('pinery_flow_post_status', 'publish')); ?>><?php _e('Publish immediately', 'pinery-flow'); ?></option>
                                <option value="draft" <?php selected('draft', get_option('pinery_flow_post_status', 'publish')); ?>><?php _e('Save as draft (review first)', 'pinery-flow'); ?></option>
                            </select>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_default_author"><?php _e('Default Author', 'pinery-flow'); ?></label></th>
                        <td>
                            <?php wp_dropdown_users([
                                'name'              => 'pinery_flow_default_author',
                                'id'                => 'pinery_flow_default_author',
                                'selected'          => get_option('pinery_flow_default_author', 1),
                                'show_option_none'  => false,
                            ]); ?>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_btn_text"><?php _e('Buy Button Text', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="text" name="pinery_flow_btn_text" id="pinery_flow_btn_text"
                                   value="<?php echo esc_attr(get_option('pinery_flow_btn_text', 'Shop on Amazon')); ?>"
                                   class="regular-text" />
                        </td>
                    </tr>
                    <tr>
                        <th><?php _e('Auto SEO', 'pinery-flow'); ?></th>
                        <td>
                            <?php $has_seo = self::has_seo_plugin(); ?>
                            <label>
                                <input type="checkbox" name="pinery_flow_auto_seo" value="1"
                                    <?php checked(1, get_option('pinery_flow_auto_seo', 1) && !$has_seo); ?>
                                    <?php if ($has_seo): ?>disabled<?php endif; ?> />
                                <?php _e('Add SEO meta tags automatically (no plugin required)', 'pinery-flow'); ?>
                            </label>
                            <?php if ($has_seo): ?>
                                <p style="color:#d63638;font-weight:600;margin:8px 0 0;">
                                    <?php _e('Auto SEO has been disabled because an SEO plugin is active. Duplicate meta tags would harm your rankings.', 'pinery-flow'); ?>
                                </p>
                            <?php endif; ?>
                            <p class="description">
                                <?php _e('Each post automatically gets:', 'pinery-flow'); ?><br>
                                &bull; <code>&lt;meta name="description"&gt;</code> — <?php _e('AI-generated summary (155 characters)', 'pinery-flow'); ?><br>
                                &bull; <code>&lt;meta name="keywords"&gt;</code> — <?php _e('Product keywords extracted from title', 'pinery-flow'); ?><br>
                                &bull; <strong>Open Graph</strong> — <?php _e('og:title, og:description, og:image (Facebook, LinkedIn)', 'pinery-flow'); ?><br>
                                &bull; <strong>Twitter Card</strong> — <?php _e('summary_large_image (Twitter/X)', 'pinery-flow'); ?><br>
                                &bull; <strong>JSON-LD Schema</strong> — <?php _e('Product rich snippet with price & rating (Google)', 'pinery-flow'); ?><br>
                                <?php _e('Works standalone. Also fills Rank Math fields if installed.', 'pinery-flow'); ?>
                            </p>
                        </td>
                    </tr>

                    <!-- Built-in Categories — Hierarchical -->
                    <tr>
                        <th><?php _e('Amazon Categories', 'pinery-flow'); ?></th>
                        <td>
                            <?php
                            $saved_cats = get_option('pinery_flow_categories', []);
                            $all_departments = Pinery_Flow_Pipeline::amazon_departments();

                            if (!is_array($saved_cats)) {
                                $saved_cats = [];
                            }
                            ?>
                            <div id="pinery-cat-tree" style="max-height:500px; overflow-y:auto; border:1px solid #ccd0d4; border-radius:4px; padding:12px; background:#fff;">
                                <!-- Quick actions -->
                                <div style="margin-bottom:12px; padding-bottom:10px; border-bottom:1px solid #eee; display:flex; gap:10px; flex-wrap:wrap;">
                                    <button type="button" class="button button-small pinery-select-all"><?php _e('Select All', 'pinery-flow'); ?></button>
                                    <button type="button" class="button button-small pinery-deselect-all"><?php _e('Deselect All', 'pinery-flow'); ?></button>
                                    <span style="color:#999;font-size:12px;line-height:28px;margin-left:4px;">
                                        <?php _e('Expand departments below to pick subcategories.', 'pinery-flow'); ?>
                                    </span>
                                </div>
                                <?php foreach ($all_departments as $dept_id => $dept):
                                    $has_subs = !empty($dept['subcategories']);
                                    $dept_slug_class = 'pinery-dept-' . $dept_id;
                                ?>
                                <div class="pinery-dept" style="margin-bottom:2px;">
                                    <div class="pinery-dept-header" style="display:flex; align-items:center; padding:8px 6px; cursor:pointer; border-radius:3px; background:#f8f9fa; user-select:none;"
                                         data-dept="<?php echo esc_attr($dept_id); ?>">
                                        <span class="pinery-dept-arrow" style="display:inline-block;width:16px;font-size:11px;transition:transform 0.15s;margin-right:4px;">&#9654;</span>
                                        <span style="flex:1;font-weight:600;font-size:13px;"><?php echo esc_html($dept['name']); ?></span>
                                        <?php if ($has_subs): ?>
                                        <span class="pinery-dept-count" style="font-size:11px;color:#888;margin-right:8px;"><?php echo count($dept['subcategories']); ?> <?php _e('subcategories', 'pinery-flow'); ?></span>
                                        <button type="button" class="button button-small pinery-dept-select-all" style="font-size:11px;margin-right:4px;" data-dept="<?php echo esc_attr($dept_id); ?>">
                                            <?php _e('All', 'pinery-flow'); ?>
                                        </button>
                                        <?php else: ?>
                                        <label style="margin:0;font-weight:normal;">
                                            <input type="checkbox" name="pinery_flow_categories[]" value="<?php echo esc_attr($dept_id); ?>"
                                                   <?php checked(in_array($dept_id, $saved_cats)); ?> />
                                            <?php _e('Scrape this department', 'pinery-flow'); ?>
                                        </label>
                                        <?php endif; ?>
                                    </div>
                                    <?php if ($has_subs): ?>
                                    <div class="pinery-dept-subs" style="display:none; padding:6px 6px 6px 28px; grid-template-columns:repeat(auto-fill, minmax(200px, 1fr)); gap:2px 8px;">
                                        <?php foreach ($dept['subcategories'] as $sub_id => $sub):
                                            $full_slug = $dept_id . '/' . $sub_id;
                                        ?>
                                        <label style="display:block; padding:3px 6px; cursor:pointer; font-size:12px; border-radius:2px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;"
                                               class="pinery-sub-label"
                                               data-dept="<?php echo esc_attr($dept_id); ?>">
                                            <input type="checkbox" name="pinery_flow_categories[]" value="<?php echo esc_attr($full_slug); ?>"
                                                   <?php checked(in_array($full_slug, $saved_cats)); ?>
                                                   class="pinery-sub-check" data-dept="<?php echo esc_attr($dept_id); ?>" />
                                            <?php echo esc_html($sub['name']); ?>
                                        </label>
                                        <?php endforeach; ?>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php endforeach; ?>
                            </div>
                            <p class="description" style="margin-top:8px;">
                                <?php _e('Select specific subcategories to scrape. Expand a department to see its subcategories. Departments without subcategories can be selected directly.', 'pinery-flow'); ?>
                            </p>
                        </td>
                    </tr>

                    <!-- Custom Categories -->
                    <tr>
                        <th><?php _e('Custom Categories', 'pinery-flow'); ?></th>
                        <td id="pinery-custom-cats">
                            <?php
                            $custom_cats = get_option('pinery_flow_custom_categories', []);
                            if (empty($custom_cats)) $custom_cats = [['name' => '', 'url' => '']];
                            foreach ($custom_cats as $idx => $item):
                            ?>
                                <div class="pinery-custom-cat-row" style="display:flex; gap:8px; margin-bottom:8px; align-items:center;">
                                    <input type="text" name="pinery_flow_custom_categories[<?php echo (int)$idx; ?>][name]"
                                           value="<?php echo esc_attr($item['name'] ?? ''); ?>"
                                           placeholder="<?php esc_attr_e('Category name', 'pinery-flow'); ?>"
                                           style="width:160px;" />
                                    <input type="url" name="pinery_flow_custom_categories[<?php echo (int)$idx; ?>][url]"
                                           value="<?php echo esc_attr($item['url'] ?? ''); ?>"
                                           placeholder="<?php esc_attr_e('Amazon Best Sellers URL', 'pinery-flow'); ?>"
                                           style="flex:1; min-width:320px;" />
                                    <button type="button" class="button pinery-remove-cat" style="color:#b32d2e; border-color:#b32d2e;" title="<?php esc_attr_e('Remove', 'pinery-flow'); ?>">&times;</button>
                                </div>
                            <?php endforeach; ?>
                            <button type="button" class="button" id="pinery-add-cat">+ <?php _e('Add Category URL', 'pinery-flow'); ?></button>
                            <p class="description">
                                <?php _e('Add any Amazon Best Sellers category URL. Works for any department: electronics, home, beauty, books, etc. The URL format should be:', 'pinery-flow'); ?><br/>
                                <code>https://www.amazon.com/Best-Sellers-.../zgbs/...</code>
                            </p>
                        </td>
                    </tr>

                    <!-- Image Settings -->
                    <tr><th colspan="2"><h2><?php _e('Image Settings', 'pinery-flow'); ?></h2></th></tr>
                    <tr>
                        <th><?php _e('Featured Image Source', 'pinery-flow'); ?></th>
                        <td>
                            <?php $img_src = get_option('pinery_flow_image_source', 'ai'); ?>
                            <label style="margin-right:20px;">
                                <input type="radio" name="pinery_flow_image_source" value="ai" <?php checked('ai', $img_src); ?> />
                                <?php _e('AI Generated (lifestyle image)', 'pinery-flow'); ?>
                            </label>
                            <label>
                                <input type="radio" name="pinery_flow_image_source" value="amazon" <?php checked('amazon', $img_src); ?> />
                                <?php _e('Amazon Original (product photo)', 'pinery-flow'); ?>
                            </label>
                            <p class="description"><?php _e('Use AI-generated lifestyle images or the original Amazon product photo as the featured image.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_image_ratio"><?php _e('Image Aspect Ratio', 'pinery-flow'); ?></label></th>
                        <td>
                            <select name="pinery_flow_image_ratio" id="pinery_flow_image_ratio">
                                <option value="9:16" <?php selected('9:16', get_option('pinery_flow_image_ratio', '9:16')); ?>>9:16 — Pinterest / Phone</option>
                                <option value="4:5" <?php selected('4:5', get_option('pinery_flow_image_ratio', '9:16')); ?>>4:5 — Instagram Optimal</option>
                                <option value="2:3" <?php selected('2:3', get_option('pinery_flow_image_ratio', '9:16')); ?>>2:3 — Classic Portrait</option>
                                <option value="1:1" <?php selected('1:1', get_option('pinery_flow_image_ratio', '9:16')); ?>>1:1 — Square</option>
                            </select>
                        </td>
                    </tr>

                    <tr>
                        <th><label for="pinery_flow_show_price_overlay"><?php _e('Price + Rating Overlay', 'pinery-flow'); ?></label></th>
                        <td>
                            <label>
                                <input type="checkbox" name="pinery_flow_show_price_overlay" value="1" <?php checked(1, get_option('pinery_flow_show_price_overlay', 1)); ?> />
                                <?php _e('Show price and star rating on product image', 'pinery-flow'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php _e('Overlay Style', 'pinery-flow'); ?></th>
                        <td>
                            <div style="display:flex; gap:20px; flex-wrap:wrap; align-items:flex-start;">
                                <div>
                                    <label style="display:block;font-weight:600;margin-bottom:4px;"><?php _e('Price Color', 'pinery-flow'); ?></label>
                                    <input type="color" name="pinery_flow_price_color" value="<?php echo esc_attr(get_option('pinery_flow_price_color', '#ffffff')); ?>" style="width:80px;height:30px;" />
                                </div>
                                <div>
                                    <label style="display:block;font-weight:600;margin-bottom:4px;"><?php _e('Price Size (px)', 'pinery-flow'); ?></label>
                                    <input type="number" name="pinery_flow_price_size" value="<?php echo esc_attr(get_option('pinery_flow_price_size', 14)); ?>" min="8" max="30" class="small-text" style="width:80px;height:30px;" />
                                </div>
                                <div>
                                    <label style="display:block;font-weight:600;margin-bottom:4px;"><?php _e('Rating Color', 'pinery-flow'); ?></label>
                                    <input type="color" name="pinery_flow_rating_color" value="<?php echo esc_attr(get_option('pinery_flow_rating_color', '#ffd700')); ?>" style="width:80px;height:30px;" />
                                </div>
                                <div>
                                    <label style="display:block;font-weight:600;margin-bottom:4px;"><?php _e('Rating Size (px)', 'pinery-flow'); ?></label>
                                    <input type="number" name="pinery_flow_rating_size" value="<?php echo esc_attr(get_option('pinery_flow_rating_size', 12)); ?>" min="8" max="30" class="small-text" style="width:80px;height:30px;" />
                                </div>
                            </div>
                        </td>
                    </tr>

                    <!-- Social -->
                    <tr><th colspan="2"><h2><?php _e('Social', 'pinery-flow'); ?></h2></th></tr>
                    <tr>
                        <th><?php _e('Pinterest', 'pinery-flow'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="pinery_flow_pinterest_enabled" value="1" <?php checked(1, get_option('pinery_flow_pinterest_enabled', 0)); ?> />
                                <?php _e('Auto-publish Pins when posts are created', 'pinery-flow'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><?php _e('Authentication', 'pinery-flow'); ?></th>
                        <td>
                            <?php $saved_token = get_option('pinery_flow_pinterest_token', ''); ?>
                            <div style="margin-bottom:12px;">
                                <strong><?php _e('Method 1 — Manual Token (Trial)', 'pinery-flow'); ?></strong>
                                <p class="description" style="margin:2px 0 4px;">
                                    <?php _e('Trial apps have no App Secret. Generate a token from your', 'pinery-flow'); ?>
                                    <a href="https://developers.pinterest.com/apps/" target="_blank"><?php _e('Pinterest App dashboard', 'pinery-flow'); ?></a>
                                    <?php _e('and paste it here.', 'pinery-flow'); ?>
                                </p>
                                <input type="password" name="pinery_flow_pinterest_token" id="pinery_flow_pinterest_token"
                                       value="<?php echo esc_attr($saved_token); ?>"
                                       class="regular-text" style="width:100%;max-width:400px;" placeholder="pina_XXX..." />
                            </div>
                            <div style="border-top:1px solid #ddd;padding-top:12px;">
                                <strong><?php _e('Method 2 — OAuth Connect (Standard)', 'pinery-flow'); ?></strong>
                                <p class="description" style="margin:2px 0 4px;"><?php _e('Standard apps with App Secret can use one-click OAuth. Required for the upgrade demo video.', 'pinery-flow'); ?></p>
                                <div style="display:flex;gap:10px;margin-bottom:6px;flex-wrap:wrap;">
                                    <input type="text" name="pinery_flow_pinterest_app_id"
                                           value="<?php echo esc_attr(get_option('pinery_flow_pinterest_app_id', '')); ?>"
                                           placeholder="<?php esc_attr_e('App ID', 'pinery-flow'); ?>" style="width:200px;" />
                                    <input type="password" name="pinery_flow_pinterest_app_secret"
                                           value="<?php echo esc_attr(get_option('pinery_flow_pinterest_app_secret', '')); ?>"
                                           placeholder="<?php esc_attr_e('App Secret', 'pinery-flow'); ?>" style="width:200px;" />
                                </div>
                                <?php
                                $app_id = get_option('pinery_flow_pinterest_app_id', '');
                                $app_secret = get_option('pinery_flow_pinterest_app_secret', '');
                                $callback_url = admin_url('admin-post.php?action=pinery_flow_pinterest_callback');
                                $auth_url = 'https://www.pinterest.com/oauth/?' . http_build_query([
                                    'client_id'     => $app_id,
                                    'redirect_uri'  => $callback_url,
                                    'response_type' => 'code',
                                    'scope'         => 'pins:write,boards:read',
                                    'state'         => wp_create_nonce('pinterest_oauth'),
                                ]);
                                ?>
                                <a href="<?php echo esc_url($auth_url); ?>" class="button button-secondary" <?php if (!$app_id || !$app_secret) echo 'disabled'; ?>>
                                    <?php _e('Connect Pinterest', 'pinery-flow'); ?>
                                </a>
                                <?php if ($saved_token): ?>
                                    <form method="post" action="<?php echo admin_url('admin-post.php'); ?>" style="display:inline;margin-left:6px;">
                                        <?php wp_nonce_field('pinery_flow_pinterest_disconnect'); ?>
                                        <input type="hidden" name="action" value="pinery_flow_pinterest_disconnect">
                                        <button type="submit" class="button button-small" style="color:#b32d2e;border-color:#b32d2e;"><?php _e('Clear Token', 'pinery-flow'); ?></button>
                                    </form>
                                <?php endif; ?>
                                <p class="description"><?php _e('Redirect URI:', 'pinery-flow'); ?> <code><?php echo esc_html($callback_url); ?></code></p>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_pinterest_board"><?php _e('Board ID', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="text" name="pinery_flow_pinterest_board" id="pinery_flow_pinterest_board"
                                   value="<?php echo esc_attr(get_option('pinery_flow_pinterest_board', '')); ?>"
                                   class="regular-text" placeholder="123456789012345678" />
                            <p class="description">
                                <?php _e('Numeric board ID from board URL:', 'pinery-flow'); ?>
                                <code>/pinboard/username/board-name/<strong>123456789012345678</strong>/</code>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <td colspan="2" style="padding-top:0;">
                            <div style="background:#f0f6fc; border-left:4px solid #2271b1; padding:10px 14px; margin-top:8px; font-size:13px; line-height:1.6;">
                                <strong><?php _e('Trial vs Standard', 'pinery-flow'); ?></strong><br>
                                <?php _e('<strong>Trial</strong>: Use Method 1 (manual token). Pins only visible to you. No review needed.', 'pinery-flow'); ?><br>
                                <?php _e('<strong>Standard</strong>: Use Method 2 (OAuth). Pins are public. Requires demo video + app review.', 'pinery-flow'); ?><br>
                                <?php _e('Apply for upgrade at', 'pinery-flow'); ?>
                                <a href="https://developers.pinterest.com/apps/" target="_blank">developers.pinterest.com/apps</a>.
                                <?php _e('App Secret appears only after Standard approval.', 'pinery-flow'); ?>
                            </div>
                        </td>
                    </tr>
                    <tr><th colspan="2"><h2><?php _e('Schedule', 'pinery-flow'); ?></h2></th></tr>
                    <tr>
                        <th><?php _e('Auto-run', 'pinery-flow'); ?></th>
                        <td>
                            <label>
                                <input type="checkbox" name="pinery_flow_auto_enabled" value="1" <?php checked(1, get_option('pinery_flow_auto_enabled', 0)); ?> />
                                <?php _e('Enable scheduled automatic runs', 'pinery-flow'); ?>
                            </label>
                        </td>
                    </tr>
                    <tr>
                        <th><label for="pinery_flow_cron_minutes"><?php _e('Run Every (hours)', 'pinery-flow'); ?></label></th>
                        <td>
                            <input type="number" name="pinery_flow_cron_minutes" id="pinery_flow_cron_minutes"
                                   value="<?php echo esc_attr(get_option('pinery_flow_cron_minutes', 6)); ?>"
                                   min="1" max="168" class="small-text" />
                            <span style="margin-left:4px;"><?php _e('hours', 'pinery-flow'); ?></span>
                            <p class="description"><?php _e('How often to scrape and generate new content. 6 hours is a good default.', 'pinery-flow'); ?></p>
                        </td>
                    </tr>
                </table>

                <?php submit_button(); ?>
            </form>
        </div>

        <script>
        (function() {
            // Dynamic provider help link
            var providerLinks = {
                xai:    { label: 'console.x.ai', url: 'https://console.x.ai' },
                openai: { label: 'platform.openai.com/api-keys', url: 'https://platform.openai.com/api-keys' },
                gemini: { label: 'aistudio.google.com/apikey', url: 'https://aistudio.google.com/apikey' },
            };
            var radios = document.querySelectorAll('input[name="pinery_flow_ai_provider"]');
            var keyLink = document.getElementById('pinery-key-link');
            radios.forEach(function(r) {
                r.addEventListener('change', function() {
                    var info = providerLinks[this.value];
                    if (keyLink && info) {
                        keyLink.href = info.url;
                        keyLink.textContent = info.label;
                    }
                });
            });

            // Custom categories
            var container = document.getElementById('pinery-custom-cats');
            var addBtn    = document.getElementById('pinery-add-cat');

            function reindex() {
                var rows = container.querySelectorAll('.pinery-custom-cat-row');
                rows.forEach(function(row, i) {
                    row.querySelectorAll('input').forEach(function(input) {
                        input.name = input.name.replace(/\[\d+\]/, '[' + i + ']');
                    });
                });
            }

            if (addBtn) {
                addBtn.addEventListener('click', function() {
                    var idx = container.querySelectorAll('.pinery-custom-cat-row').length;
                    var div = document.createElement('div');
                    div.className = 'pinery-custom-cat-row';
                    div.style.cssText = 'display:flex;gap:8px;margin-bottom:8px;align-items:center;';
                    div.innerHTML =
                        '<input type="text" name="pinery_flow_custom_categories[' + idx + '][name]" placeholder="<?php esc_attr_e('Category name', 'pinery-flow'); ?>" style="width:160px;" />' +
                        '<input type="url" name="pinery_flow_custom_categories[' + idx + '][url]" placeholder="<?php esc_attr_e('Amazon Best Sellers URL', 'pinery-flow'); ?>" style="flex:1;min-width:320px;" />' +
                        '<button type="button" class="button pinery-remove-cat" style="color:#b32d2e;border-color:#b32d2e;" title="<?php esc_attr_e('Remove', 'pinery-flow'); ?>">&times;</button>';
                    container.insertBefore(div, addBtn);
                });

                container.addEventListener('click', function(e) {
                    if (e.target.classList.contains('pinery-remove-cat')) {
                        var rows = container.querySelectorAll('.pinery-custom-cat-row');
                        if (rows.length > 1) {
                            e.target.closest('.pinery-custom-cat-row').remove();
                            reindex();
                        } else {
                            var inputs = rows[0].querySelectorAll('input');
                            inputs[0].value = '';
                            inputs[1].value = '';
                        }
                    }
                });
            }

            // Department accordion
            var tree = document.getElementById('pinery-cat-tree');
            if (!tree) return;

            // Toggle department expansion
            tree.addEventListener('click', function(e) {
                var header = e.target.closest('.pinery-dept-header');
                if (!header) return;

                // Ignore clicks on buttons and checkboxes
                if (e.target.tagName === 'BUTTON' || e.target.tagName === 'INPUT') return;
                if (e.target.closest('button') || e.target.closest('label')) return;

                var dept = header.closest('.pinery-dept');
                var subs = dept.querySelector('.pinery-dept-subs');
                var arrow = header.querySelector('.pinery-dept-arrow');
                if (subs) {
                    var isOpen = subs.style.display !== 'none';
                    subs.style.display = isOpen ? 'none' : 'grid';
                    if (arrow) arrow.style.transform = isOpen ? 'rotate(0deg)' : 'rotate(90deg)';
                }
            });

            // "All" button per department
            tree.addEventListener('click', function(e) {
                var btn = e.target.closest('.pinery-dept-select-all');
                if (!btn) return;
                var deptId = btn.getAttribute('data-dept');
                var checks = tree.querySelectorAll('.pinery-sub-check[data-dept="' + deptId + '"]');
                var allChecked = true;
                checks.forEach(function(c) { if (!c.checked) allChecked = false; });
                checks.forEach(function(c) { c.checked = !allChecked; });
            });

            // Select All / Deselect All
            var selectAllBtn = tree.querySelector('.pinery-select-all');
            var deselectAllBtn = tree.querySelector('.pinery-deselect-all');
            if (selectAllBtn) {
                selectAllBtn.addEventListener('click', function() {
                    tree.querySelectorAll('input[type="checkbox"]').forEach(function(c) { c.checked = true; });
                });
            }
            if (deselectAllBtn) {
                deselectAllBtn.addEventListener('click', function() {
                    tree.querySelectorAll('input[type="checkbox"]').forEach(function(c) { c.checked = false; });
                });
            }

            // Highlight hover
            tree.addEventListener('mouseover', function(e) {
                var label = e.target.closest('.pinery-sub-label');
                if (label) label.style.background = '#f0f6fc';
            });
            tree.addEventListener('mouseout', function(e) {
                var label = e.target.closest('.pinery-sub-label');
                if (label) label.style.background = '';
            });
        })();
        </script>
        <?php
    }

    public static function render_logs() {
        $logs = get_option('pinery_flow_run_logs', []);
        if (empty($logs)) return;

        // Show last 10 runs
        $logs = array_slice($logs, -10);
        ?>
        <div class="card" style="max-width:100%; padding:16px 20px; margin:16px 0; background:#fff; border:1px solid #ccd0d4; border-radius:4px;">
            <h3 style="margin-top:0;"><?php _e('Recent Runs', 'pinery-flow'); ?></h3>
            <table class="widefat striped" style="border:1px solid #ccd0d4;">
                <thead><tr><th><?php _e('Time', 'pinery-flow'); ?></th><th><?php _e('Posts Created', 'pinery-flow'); ?></th><th><?php _e('Status', 'pinery-flow'); ?></th></tr></thead>
                <tbody>
                <?php foreach (array_reverse($logs) as $log): ?>
                    <tr>
                        <td><?php echo esc_html($log['time'] ?? ''); ?></td>
                        <td><?php echo (int) ($log['count'] ?? 0); ?></td>
                        <td><?php echo esc_html($log['status'] ?? 'ok'); ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    public static function render_logs_page() {
        $logs = get_option('pinery_flow_detail_logs', []);
        $total = count($logs);
        $info_count = count(array_filter($logs, function($l) { return ($l['level'] ?? '') === 'info'; }));
        $warn_count = count(array_filter($logs, function($l) { return ($l['level'] ?? '') === 'warning'; }));
        $err_count  = count(array_filter($logs, function($l) { return ($l['level'] ?? '') === 'error'; }));
        ?>
        <div class="wrap" style="max-width:1100px;">
            <h1><?php _e('Pinery Flow — Logs', 'pinery-flow'); ?></h1>

            <?php if (!empty($_GET['cleared'])): ?>
                <div class="notice notice-success is-dismissible"><p><?php _e('Logs cleared.', 'pinery-flow'); ?></p></div>
            <?php endif; ?>

            <!-- Stats bar -->
            <div style="display:flex; gap:16px; margin:16px 0; flex-wrap:wrap;">
                <div style="padding:10px 18px; background:#fff; border:1px solid #ccd0d4; border-radius:4px; text-align:center; min-width:80px;">
                    <div style="font-size:24px;font-weight:700;"><?php echo (int)$total; ?></div>
                    <div style="font-size:11px;color:#666;"><?php _e('Total', 'pinery-flow'); ?></div>
                </div>
                <div style="padding:10px 18px; background:#fff; border:1px solid #ccd0d4; border-radius:4px; text-align:center; min-width:80px; border-left:4px solid #2271b1;">
                    <div style="font-size:24px;font-weight:700;color:#2271b1;"><?php echo (int)$info_count; ?></div>
                    <div style="font-size:11px;color:#666;"><?php _e('Info', 'pinery-flow'); ?></div>
                </div>
                <div style="padding:10px 18px; background:#fff; border:1px solid #ccd0d4; border-radius:4px; text-align:center; min-width:80px; border-left:4px solid #dba617;">
                    <div style="font-size:24px;font-weight:700;color:#dba617;"><?php echo (int)$warn_count; ?></div>
                    <div style="font-size:11px;color:#666;"><?php _e('Warning', 'pinery-flow'); ?></div>
                </div>
                <div style="padding:10px 18px; background:#fff; border:1px solid #ccd0d4; border-radius:4px; text-align:center; min-width:80px; border-left:4px solid #d63638;">
                    <div style="font-size:24px;font-weight:700;color:#d63638;"><?php echo (int)$err_count; ?></div>
                    <div style="font-size:11px;color:#666;"><?php _e('Error', 'pinery-flow'); ?></div>
                </div>
            </div>

            <!-- Controls -->
            <div style="display:flex; gap:12px; margin-bottom:12px; align-items:center; flex-wrap:wrap;">
                <label>
                    <input type="checkbox" id="pinery-auto-refresh" />
                    <?php _e('Auto-refresh (10s)', 'pinery-flow'); ?>
                </label>
                <select id="pinery-level-filter" style="margin-left:8px;">
                    <option value="all"><?php _e('All levels', 'pinery-flow'); ?></option>
                    <option value="info"><?php _e('Info', 'pinery-flow'); ?></option>
                    <option value="warning"><?php _e('Warning', 'pinery-flow'); ?></option>
                    <option value="error"><?php _e('Error', 'pinery-flow'); ?></option>
                </select>
                <input type="text" id="pinery-search" placeholder="<?php esc_attr_e('Search logs...', 'pinery-flow'); ?>" style="width:200px;" />
                <form method="post" action="<?php echo admin_url('admin-post.php'); ?>" style="margin-left:auto;">
                    <?php wp_nonce_field('pinery_flow_clear_logs'); ?>
                    <input type="hidden" name="action" value="pinery_flow_clear_logs">
                    <button type="submit" class="button" style="color:#b32d2e;border-color:#b32d2e;" onclick="return confirm('<?php esc_attr_e('Delete all log entries?', 'pinery-flow'); ?>')">
                        <?php _e('Clear All Logs', 'pinery-flow'); ?>
                    </button>
                </form>
            </div>

            <!-- Log table -->
            <table class="widefat striped" id="pinery-log-table" style="border:1px solid #ccd0d4;">
                <thead>
                    <tr>
                        <th style="width:150px;"><?php _e('Time', 'pinery-flow'); ?></th>
                        <th style="width:70px;"><?php _e('Level', 'pinery-flow'); ?></th>
                        <th style="width:100px;"><?php _e('Step', 'pinery-flow'); ?></th>
                        <th><?php _e('Message', 'pinery-flow'); ?></th>
                        <th style="width:180px;"><?php _e('Context', 'pinery-flow'); ?></th>
                    </tr>
                </thead>
                <tbody>
                <?php if (empty($logs)): ?>
                    <tr><td colspan="5" style="text-align:center;padding:40px;color:#888;"><?php _e('No logs yet. Run the pipeline to see output.', 'pinery-flow'); ?></td></tr>
                <?php else: ?>
                <?php foreach (array_reverse($logs) as $log):
                    $level = $log['level'] ?? 'info';
                    $colors = ['info' => '#2271b1', 'warning' => '#dba617', 'error' => '#d63638'];
                    $color = $colors[$level] ?? '#666';
                ?>
                    <tr class="pinery-log-row" data-level="<?php echo esc_attr($level); ?>">
                        <td style="font-size:11px;white-space:nowrap;"><?php echo esc_html($log['time'] ?? ''); ?></td>
                        <td><span style="display:inline-block;padding:1px 8px;border-radius:3px;font-size:11px;font-weight:600;color:#fff;background:<?php echo esc_attr($color); ?>"><?php echo esc_html(strtoupper($level)); ?></span></td>
                        <td style="font-size:12px;"><?php echo esc_html($log['step'] ?? ''); ?></td>
                        <td><?php echo esc_html($log['message'] ?? ''); ?></td>
                        <td style="font-size:11px;color:#888;max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="<?php echo esc_attr($log['context'] ?? ''); ?>"><?php echo esc_html($log['context'] ?? ''); ?></td>
                    </tr>
                <?php endforeach; ?>
                <?php endif; ?>
                </tbody>
            </table>
        </div>

        <script>
        (function() {
            var autoRefresh = document.getElementById('pinery-auto-refresh');
            var levelFilter = document.getElementById('pinery-level-filter');
            var searchInput = document.getElementById('pinery-search');
            var timer = null;

            function filterRows() {
                var level = levelFilter.value;
                var search = searchInput.value.toLowerCase();
                var rows = document.querySelectorAll('.pinery-log-row');
                rows.forEach(function(row) {
                    var show = true;
                    if (level !== 'all' && row.getAttribute('data-level') !== level) show = false;
                    if (search && row.textContent.toLowerCase().indexOf(search) === -1) show = false;
                    row.style.display = show ? '' : 'none';
                });
            }

            levelFilter.addEventListener('change', filterRows);
            searchInput.addEventListener('input', filterRows);

            if (autoRefresh) {
                autoRefresh.addEventListener('change', function() {
                    if (this.checked) {
                        timer = setInterval(function() { location.reload(); }, 10000);
                    } else {
                        clearInterval(timer);
                    }
                });
            }
        })();
        </script>
        <?php
    }
}
