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

class VMO_Promotion_Admin_Settings {
    const OPTION_KEY = 'vmo_promotion_provider_settings';

    private static $instance = null;

    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }

        return self::$instance;
    }

    private function __construct() {
        add_action('admin_init', array($this, 'register_settings'));
        add_action('admin_post_vmo_promotion_provider_callback', array($this, 'handle_provider_callback'));
        add_action('admin_post_nopriv_vmo_promotion_provider_callback', array($this, 'handle_provider_callback'));
        add_action('rest_api_init', array($this, 'register_rest_routes'));
    }

    public function register_settings() {
        register_setting('vmo_settings_group', self::OPTION_KEY, array($this, 'sanitize_provider_settings'));
    }

    public function sanitize_provider_settings($input) {
        return self::sanitize_settings_array(is_array($input) ? $input : array());
    }

    public static function sanitize_settings_array(array $input) {
        $profiles = self::get_provider_profiles();
        $clean = array();

        foreach ($profiles as $platform_key => $profile) {
            $raw = isset($input[$platform_key]) && is_array($input[$platform_key]) ? $input[$platform_key] : array();
            $clean[$platform_key] = array(
                'connector_enabled' => !empty($raw['connector_enabled']),
                'publish_enabled' => !empty($raw['publish_enabled']),
                'reply_enabled' => !empty($raw['reply_enabled']),
                'metrics_enabled' => !empty($raw['metrics_enabled']),
                'ads_enabled' => !empty($raw['ads_enabled']),
                'app_id' => sanitize_text_field($raw['app_id'] ?? ''),
                'client_id' => sanitize_text_field($raw['client_id'] ?? ''),
                'client_secret' => sanitize_text_field($raw['client_secret'] ?? ''),
                'api_key' => sanitize_text_field($raw['api_key'] ?? ''),
                'api_secret' => sanitize_text_field($raw['api_secret'] ?? ''),
                'bot_token' => sanitize_text_field($raw['bot_token'] ?? ''),
                'access_token' => sanitize_text_field($raw['access_token'] ?? ''),
                'refresh_token' => sanitize_text_field($raw['refresh_token'] ?? ''),
                'base_url' => esc_url_raw($raw['base_url'] ?? ''),
                'webhook_secret' => sanitize_text_field($raw['webhook_secret'] ?? ''),
                'default_target_id' => sanitize_text_field($raw['default_target_id'] ?? ''),
                'default_target_label' => sanitize_text_field($raw['default_target_label'] ?? ''),
                'app_review_status' => sanitize_key($raw['app_review_status'] ?? 'admin_setup_required'),
                'marketing_api_status' => sanitize_key($raw['marketing_api_status'] ?? 'not_requested'),
                'business_verification_status' => sanitize_key($raw['business_verification_status'] ?? 'unknown'),
                'domain_verification_status' => sanitize_key($raw['domain_verification_status'] ?? 'unknown'),
                'configured_scopes' => self::sanitize_scope_list($raw['configured_scopes'] ?? array()),
                'ad_account_id' => sanitize_text_field($raw['ad_account_id'] ?? ''),
                'ad_scopes' => self::sanitize_scope_list($raw['ad_scopes'] ?? array()),
                'rate_limit_notes' => sanitize_textarea_field($raw['rate_limit_notes'] ?? ''),
                'enabled_features' => sanitize_textarea_field($raw['enabled_features'] ?? ''),
                'test_accounts' => sanitize_textarea_field($raw['test_accounts'] ?? ''),
            );
        }

        return $clean;
    }

    public static function get_provider_settings($platform = null) {
        $all = get_option(self::OPTION_KEY, array());
        if (!is_array($all)) {
            $all = array();
        }
        $all = self::sanitize_settings_array($all);

        if ($platform === null) {
            return $all;
        }

        $platform = sanitize_key($platform);
        return $all[$platform] ?? array();
    }

    public static function get_required_fields($platform) {
        $profiles = self::get_provider_profiles();
        return array_values((array) ($profiles[sanitize_key($platform)]['required_fields'] ?? array()));
    }

    public static function get_missing_required_fields($platform, array $settings = array()) {
        $required = self::get_required_fields($platform);
        $missing = array();
        foreach ($required as $field) {
            if (empty($settings[$field])) {
                $missing[] = $field;
            }
        }
        return $missing;
    }

    public static function has_required_credentials($platform, array $settings = array()) {
        return empty(self::get_missing_required_fields($platform, $settings));
    }

    public static function get_provider_callback_url($platform) {
        return admin_url('admin-post.php?action=vmo_promotion_provider_callback&platform=' . rawurlencode(sanitize_key($platform)));
    }

    public static function get_provider_webhook_url($platform) {
        return rest_url('vmo-builder/v1/promotions/providers/' . rawurlencode(sanitize_key($platform)) . '/webhook');
    }

    public function register_rest_routes() {
        register_rest_route('vmo-builder/v1', '/promotions/providers/(?P<platform>[a-z0-9_-]+)/webhook', array(
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => array($this, 'receive_provider_webhook'),
            'permission_callback' => '__return_true',
        ));
    }

    public function receive_provider_webhook(WP_REST_Request $request) {
        $platform = sanitize_key($request->get_param('platform'));
        $registry = class_exists('VMO_Promotion_Provider_Registry') ? VMO_Promotion_Provider_Registry::get_instance() : null;
        $connector = $registry ? $registry->get_connector($platform) : null;

        if ($connector) {
            $result = $connector->receive_webhook(array(
                'body' => $request->get_body(),
                'headers' => $request->get_headers(),
                'params' => $request->get_params(),
                'method' => $request->get_method(),
            ));
            if (!is_wp_error($result) && !empty($result)) {
                return rest_ensure_response($result);
            }
        }

        return new WP_REST_Response(array(
            'success' => true,
            'platform' => $platform,
            'message' => 'Webhook endpoint is registered. A platform-specific connector must handle this provider before live webhook automation will execute.',
        ), 202);
    }

    public function handle_provider_callback() {
        $platform = sanitize_key($_GET['platform'] ?? '');
        if ($platform === '') {
            wp_die('Missing provider platform.', 'Promotion Provider Callback', array('response' => 400));
        }

        $registry = class_exists('VMO_Promotion_Provider_Registry') ? VMO_Promotion_Provider_Registry::get_instance() : null;
        $connector = $registry ? $registry->get_connector($platform) : null;
        $status = 'received';
        $message = 'Callback received.';
        $accounts = 0;

        if ($connector && method_exists($connector, 'handle_callback')) {
            $result = $connector->handle_callback($_GET);
            if (is_wp_error($result)) {
                $status = 'error';
                $message = $result->get_error_message();
            } else {
                $status = !empty($result['success']) ? 'success' : 'received';
                $message = sanitize_text_field($result['message'] ?? $message);
                $accounts = (int) ($result['connected_accounts_count'] ?? 0);
            }
        }

        $settings_url = add_query_arg(array(
            'page' => 'vmo-ai-settings',
            'promotion_provider' => $platform,
            'promotion_callback' => $status,
            'promotion_accounts' => $accounts,
            'promotion_message' => $message,
        ), admin_url('admin.php'));
        wp_safe_redirect($settings_url);
        exit;
    }

    public static function render_settings_section() {
        $profiles = self::get_provider_profiles();
        $values = self::get_provider_settings();
        $waves = array();
        foreach ($profiles as $platform_key => $profile) {
            $waves[(int) $profile['wave']][$platform_key] = $profile;
        }
        ksort($waves);

        echo '<tr><th colspan="2"><hr /><strong>📣 Promotion Command Center Provider Connectors</strong></th></tr>';
        echo '<tr><th scope="row">Provider Credential Inventory</th><td>';
        echo '<p class="description" style="margin-top:0; max-width:980px;">Enter provider credentials here as you obtain them. These settings drive the Promotion Command Center readiness matrix, callback URLs, webhook URLs, connector enablement flags, and the future ads-management inventory. Direct publishing, replies, metrics, and ad workflows only become live for platforms whose credentials and approvals are actually configured.</p>';

        foreach ($waves as $wave => $providers) {
            echo '<div style="margin:16px 0; max-width:1100px; border:1px solid #dcdcde; border-radius:8px; background:#fff;">';
            echo '<div style="padding:12px 16px; border-bottom:1px solid #ebecee; background:#f6f7f7;"><strong>Rollout Wave ' . (int) $wave . '</strong></div>';
            foreach ($providers as $platform_key => $profile) {
                $saved = $values[$platform_key] ?? array();
                $missing = self::get_missing_required_fields($platform_key, $saved);
                $ready = !empty($saved['connector_enabled']) && empty($missing);
                $status = $ready ? 'Credential-ready' : 'Needs setup';
                $status_color = $ready ? '#166534' : '#854d0e';
                $status_bg = $ready ? '#dcfce7' : '#fef3c7';
                $callback_url = self::get_provider_callback_url($platform_key);
                $webhook_url = self::get_provider_webhook_url($platform_key);

                echo '<details style="border-top:1px solid #ebecee;">';
                echo '<summary style="padding:12px 16px; cursor:pointer; display:flex; align-items:center; justify-content:space-between; gap:12px;">';
                echo '<span><strong>' . esc_html($profile['label']) . '</strong> <span style="color:#646970;">(' . esc_html($profile['category']) . ')</span></span>';
                echo '<span style="padding:3px 10px; border-radius:12px; background:' . esc_attr($status_bg) . '; color:' . esc_attr($status_color) . '; font-size:12px;">' . esc_html($status) . '</span>';
                echo '</summary>';
                echo '<div style="padding:16px; border-top:1px solid #ebecee;">';
                echo '<p class="description" style="margin-top:0; max-width:920px;">' . esc_html($profile['notes']) . '</p>';
                echo '<p class="description" style="margin-top:0;"><strong>Required credentials:</strong> ' . esc_html(implode(', ', array_map(array(__CLASS__, 'label_for_field'), $profile['required_fields']))) . '</p>';
                if (!empty($missing)) {
                    echo '<p class="description" style="color:#b45309;"><strong>Missing:</strong> ' . esc_html(implode(', ', array_map(array(__CLASS__, 'label_for_field'), $missing))) . '</p>';
                }

                echo '<div style="display:grid; grid-template-columns:repeat(auto-fit,minmax(220px,1fr)); gap:12px; margin-top:12px;">';
                self::render_checkbox_field($platform_key, 'connector_enabled', 'Enable connector', !empty($saved['connector_enabled']));
                self::render_checkbox_field($platform_key, 'publish_enabled', 'Enable publishing', !empty($saved['publish_enabled']));
                self::render_checkbox_field($platform_key, 'reply_enabled', 'Enable replies', !empty($saved['reply_enabled']));
                self::render_checkbox_field($platform_key, 'metrics_enabled', 'Enable metrics sync', !empty($saved['metrics_enabled']));
                self::render_checkbox_field($platform_key, 'ads_enabled', 'Enable ad management', !empty($saved['ads_enabled']));
                self::render_select_field($platform_key, 'app_review_status', 'App review status', $saved['app_review_status'] ?? 'admin_setup_required', array(
                    'admin_setup_required' => 'Admin Setup Required',
                    'draft' => 'Draft / Internal',
                    'pending' => 'Pending Review',
                    'in_review' => 'In Review',
                    'approved' => 'Approved',
                    'rejected' => 'Rejected',
                    'disabled' => 'Disabled',
                ));
                self::render_select_field($platform_key, 'business_verification_status', 'Business verification', $saved['business_verification_status'] ?? 'unknown', array(
                    'unknown' => 'Unknown',
                    'pending' => 'Pending',
                    'verified' => 'Verified',
                    'rejected' => 'Rejected',
                ));
                self::render_select_field($platform_key, 'domain_verification_status', 'Domain verification', $saved['domain_verification_status'] ?? 'unknown', array(
                    'unknown' => 'Unknown',
                    'pending' => 'Pending',
                    'verified' => 'Verified',
                    'not_required' => 'Not Required',
                ));
                self::render_select_field($platform_key, 'marketing_api_status', 'Marketing / Ads API status', $saved['marketing_api_status'] ?? 'not_requested', array(
                    'not_requested' => 'Not Requested',
                    'internal_only' => 'Internal / Not Submitted',
                    'pending' => 'Pending Review',
                    'in_review' => 'In Review',
                    'approved' => 'Approved',
                    'limited' => 'Approved, Limited',
                    'not_supported' => 'Not Supported',
                ));

                foreach ($profile['fields'] as $field_name) {
                    self::render_input_field($platform_key, $field_name, self::label_for_field($field_name), $saved[$field_name] ?? '', in_array($field_name, array('client_secret', 'api_secret', 'bot_token', 'access_token', 'refresh_token', 'webhook_secret'), true) ? 'password' : 'text');
                }

                echo '<div>';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">OAuth / Provider Callback URL</label>';
                echo '<input type="text" readonly class="regular-text code" style="width:100%;" value="' . esc_attr($callback_url) . '" />';
                echo '</div>';
                echo '<div>';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Webhook URL</label>';
                echo '<input type="text" readonly class="regular-text code" style="width:100%;" value="' . esc_attr($webhook_url) . '" />';
                echo '</div>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Configured scopes</label>';
                echo '<textarea name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][configured_scopes]') . '" rows="3" class="large-text code" style="max-width:100%; width:100%;">' . esc_textarea(implode("\n", (array) ($saved['configured_scopes'] ?? array()))) . '</textarea>';
                echo '<p class="description">One scope per line. Suggested scopes: ' . esc_html(implode(', ', $profile['suggested_scopes'])) . '.</p>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Ad account / business account ID</label>';
                echo '<input type="text" name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][ad_account_id]') . '" value="' . esc_attr($saved['ad_account_id'] ?? '') . '" class="regular-text code" style="width:100%;" autocomplete="off" />';
                echo '<p class="description">' . esc_html($profile['ad_notes'] ?? 'Record the advertising-side account or business identifier used by this provider.') . '</p>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Ad / marketing scopes</label>';
                echo '<textarea name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][ad_scopes]') . '" rows="3" class="large-text code" style="max-width:100%; width:100%;">' . esc_textarea(implode("\n", (array) ($saved['ad_scopes'] ?? array()))) . '</textarea>';
                echo '<p class="description">One scope per line. Suggested ad scopes: ' . esc_html(!empty($profile['suggested_ad_scopes']) ? implode(', ', (array) $profile['suggested_ad_scopes']) : 'Provider-specific marketing review may be required even when scopes are not fixed here.') . '.</p>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Provider notes</label>';
                echo '<textarea name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][rate_limit_notes]') . '" rows="2" class="large-text" style="max-width:100%; width:100%;">' . esc_textarea($saved['rate_limit_notes'] ?? '') . '</textarea>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Enabled features / products</label>';
                echo '<textarea name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][enabled_features]') . '" rows="2" class="large-text" style="max-width:100%; width:100%;">' . esc_textarea($saved['enabled_features'] ?? '') . '</textarea>';
                echo '</div>';

                echo '<div style="margin-top:12px;">';
                echo '<label style="display:block; font-weight:600; margin-bottom:4px;">Test / sandbox accounts</label>';
                echo '<textarea name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][test_accounts]') . '" rows="2" class="large-text" style="max-width:100%; width:100%;">' . esc_textarea($saved['test_accounts'] ?? '') . '</textarea>';
                echo '<p class="description">Use this to record sandbox accounts, provider test users, or business-profile IDs tied to this connector.</p>';
                echo '</div>';

                echo '</div>';
                echo '</details>';
            }
            echo '</div>';
        }

        echo '</td></tr>';
    }

    private static function render_checkbox_field($platform_key, $field_name, $label, $checked) {
        echo '<label style="display:flex; align-items:center; gap:8px;">';
        echo '<input type="checkbox" name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][' . $field_name . ']') . '" value="1" ' . checked(true, $checked, false) . ' />';
        echo esc_html($label);
        echo '</label>';
    }

    private static function render_input_field($platform_key, $field_name, $label, $value, $type = 'text') {
        echo '<div>';
        echo '<label style="display:block; font-weight:600; margin-bottom:4px;">' . esc_html($label) . '</label>';
        echo '<input type="' . esc_attr($type) . '" name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][' . $field_name . ']') . '" value="' . esc_attr($value) . '" class="regular-text code" style="width:100%;" autocomplete="off" />';
        echo '</div>';
    }

    private static function render_select_field($platform_key, $field_name, $label, $value, array $choices) {
        echo '<div>';
        echo '<label style="display:block; font-weight:600; margin-bottom:4px;">' . esc_html($label) . '</label>';
        echo '<select name="' . esc_attr(self::OPTION_KEY . '[' . $platform_key . '][' . $field_name . ']') . '" class="regular-text">';
        foreach ($choices as $choice_value => $choice_label) {
            echo '<option value="' . esc_attr($choice_value) . '" ' . selected($choice_value, $value, false) . '>' . esc_html($choice_label) . '</option>';
        }
        echo '</select>';
        echo '</div>';
    }

    private static function sanitize_scope_list($value) {
        if (is_array($value)) {
            $items = $value;
        } else {
            $items = preg_split('/[\r\n,]+/', (string) $value);
        }

        $items = array_values(array_filter(array_map('sanitize_text_field', array_map('trim', $items))));
        return array_values(array_unique($items));
    }

    public static function label_for_field($field_name) {
        $labels = array(
            'app_id' => 'App ID',
            'client_id' => 'Client ID',
            'client_secret' => 'Client Secret',
            'api_key' => 'API Key',
            'api_secret' => 'API Secret',
            'bot_token' => 'Bot Token',
            'access_token' => 'Access Token',
            'refresh_token' => 'Refresh Token',
            'base_url' => 'Base URL / Instance URL',
            'webhook_secret' => 'Webhook Signing Secret',
            'default_target_id' => 'Default Target / Channel ID',
            'default_target_label' => 'Default Target Label',
            'ad_account_id' => 'Ad Account / Business Account ID',
        );

        return $labels[$field_name] ?? ucwords(str_replace('_', ' ', $field_name));
    }

    public static function get_provider_profiles() {
        return array(
            'instagram' => array(
                'label' => 'Instagram',
                'wave' => 1,
                'category' => 'social',
                'required_fields' => array('app_id', 'client_secret'),
                'fields' => array('app_id', 'client_secret', 'webhook_secret'),
                'suggested_scopes' => array('instagram_basic', 'instagram_content_publish', 'instagram_manage_comments', 'instagram_manage_insights', 'pages_show_list', 'pages_read_engagement', 'pages_manage_metadata'),
                'suggested_ad_scopes' => array('ads_management', 'ads_read', 'business_management'),
                'ad_notes' => 'Instagram ad management typically rides through the Meta ads stack. Record the related ad account or business manager ID here.',
                'notes' => 'Uses Meta app configuration for Instagram business publishing, media publishing, and comment-management workflows.',
            ),
            'facebook' => array(
                'label' => 'Facebook',
                'wave' => 1,
                'category' => 'social',
                'required_fields' => array('app_id', 'client_secret'),
                'fields' => array('app_id', 'client_secret', 'webhook_secret'),
                'suggested_scopes' => array('pages_show_list', 'pages_manage_posts', 'pages_read_engagement', 'pages_manage_metadata'),
                'suggested_ad_scopes' => array('ads_management', 'ads_read', 'business_management'),
                'ad_notes' => 'Facebook ad management uses the same Meta app family plus business and ad account access.',
                'notes' => 'Meta page publishing and page-level engagement depend on the same Meta app family used for Instagram.',
            ),
            'threads' => array(
                'label' => 'Threads',
                'wave' => 1,
                'category' => 'social',
                'required_fields' => array('app_id', 'client_secret'),
                'fields' => array('app_id', 'client_secret'),
                'suggested_scopes' => array('threads_basic', 'threads_content_publish', 'threads_manage_insights'),
                'suggested_ad_scopes' => array('ads_management', 'ads_read', 'business_management'),
                'ad_notes' => 'Treat Threads advertising prep as part of the broader Meta business and ad-account credential inventory.',
                'notes' => 'Threads is handled as a Meta-family connector with its own publishing scope and app review path.',
            ),
            'linkedin' => array(
                'label' => 'LinkedIn',
                'wave' => 1,
                'category' => 'professional',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret'),
                'suggested_scopes' => array('w_member_social', 'r_liteprofile', 'w_organization_social', 'r_organization_social', 'rw_organization_admin'),
                'suggested_ad_scopes' => array('r_ads', 'rw_ads', 'rw_organization_admin'),
                'ad_notes' => 'LinkedIn ad management generally requires organization-admin access plus the ads products approved on the app.',
                'notes' => 'LinkedIn publishing requires OAuth app credentials and the approved scopes required for member or organization posting.',
            ),
            'google_business_profile' => array(
                'label' => 'Google Business Profile',
                'wave' => 1,
                'category' => 'local',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret'),
                'suggested_scopes' => array('https://www.googleapis.com/auth/business.manage'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Google Business Profile itself is not the Google Ads API. Use this field to track the related Google account, MCC, or Google Ads customer relationship needed for paid media later.',
                'notes' => 'Use for local post publishing, review replies, and profile insights. Do not architect new Q&A dependency into this connector.',
            ),
            'tiktok' => array(
                'label' => 'TikTok',
                'wave' => 2,
                'category' => 'social',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret'),
                'suggested_scopes' => array('video.publish', 'user.info.basic'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Record the TikTok Ads Manager account and any approved marketing products tied to this app.',
                'notes' => 'Content posting depends on TikTok app credentials, approved products, and the provider’s explicit setup requirements.',
            ),
            'pinterest' => array(
                'label' => 'Pinterest',
                'wave' => 2,
                'category' => 'social',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret', 'default_target_id', 'default_target_label'),
                'suggested_scopes' => array('boards:read', 'pins:read', 'pins:write', 'user_accounts:read'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Use this to capture the Pinterest business account and any ads-side access once approved.',
                'notes' => 'Pinterest is treated as an organic content connector for board-based Pin publishing. Enter a default board ID if you want VMO to target a specific board by default.',
            ),
            'x' => array(
                'label' => 'X',
                'wave' => 2,
                'category' => 'social',
                'required_fields' => array('client_id', 'client_secret', 'api_key', 'api_secret'),
                'fields' => array('client_id', 'client_secret', 'api_key', 'api_secret'),
                'suggested_scopes' => array('tweet.read', 'tweet.write', 'users.read', 'offline.access'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Track the X Ads account ID and any plan or entitlement status needed for the ads API.',
                'notes' => 'X requires separate budget and API-plan gating. Treat this connector as independently costed and approval-dependent.',
            ),
            'youtube' => array(
                'label' => 'YouTube',
                'wave' => 2,
                'category' => 'video',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret'),
                'suggested_scopes' => array('https://www.googleapis.com/auth/youtube.upload', 'https://www.googleapis.com/auth/youtube.readonly', 'https://www.googleapis.com/auth/youtube.force-ssl'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Paid YouTube promotion usually relies on Google Ads rather than the YouTube data APIs directly. Record the related customer/account mapping here.',
                'notes' => 'YouTube is a video-platform connector. Use the same Google OAuth family but separate publishing logic from Google Business Profile.',
            ),
            'reddit' => array(
                'label' => 'Reddit',
                'wave' => 3,
                'category' => 'community',
                'required_fields' => array('client_id', 'client_secret', 'default_target_id'),
                'fields' => array('client_id', 'client_secret', 'default_target_id', 'default_target_label'),
                'suggested_scopes' => array('identity', 'submit', 'read', 'privatemessages'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Record any Reddit business or ads account identifiers separately while keeping subreddit/community workflows distinct.',
                'notes' => 'Treat Reddit as community posting with stricter contextual expectations. Enter the target subreddit name that VMO should publish into first.',
            ),
            'telegram' => array(
                'label' => 'Telegram',
                'wave' => 3,
                'category' => 'community',
                'required_fields' => array('bot_token', 'default_target_id'),
                'fields' => array('bot_token', 'default_target_id', 'default_target_label', 'webhook_secret'),
                'suggested_scopes' => array('bot_api'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Telegram is tracked here as a community broadcast channel; any paid promotion relationships should be recorded manually if used.',
                'notes' => 'Telegram is handled as a community broadcast connector using bot-based messaging flows. Enter the default chat ID or @channelusername VMO should publish into.',
            ),
            'discord_community' => array(
                'label' => 'Discord Community',
                'wave' => 3,
                'category' => 'community',
                'required_fields' => array('bot_token', 'default_target_id'),
                'fields' => array('client_id', 'client_secret', 'bot_token', 'default_target_id', 'default_target_label'),
                'suggested_scopes' => array('bot', 'applications.commands'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Discord is treated as community distribution. Record any campaign sponsorship or managed community identifiers here if needed.',
                'notes' => 'Discord is treated as community distribution and moderated automation. Enter the default channel or thread ID VMO should publish into.',
            ),
            'snapchat' => array(
                'label' => 'Snapchat',
                'wave' => 4,
                'category' => 'social',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret'),
                'suggested_scopes' => array('snapchat-marketing-api'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Snapchat advertising depends on its marketing stack and allowlisting. Record the business or ads account details tied to that approval.',
                'notes' => 'Later-stage connector. Requires separate provider approval and capability validation before exposure in production.',
            ),
            'tumblr' => array(
                'label' => 'Tumblr',
                'wave' => 4,
                'category' => 'community',
                'required_fields' => array('client_id', 'client_secret'),
                'fields' => array('client_id', 'client_secret', 'api_key', 'api_secret'),
                'suggested_scopes' => array('basic', 'write', 'offline_access'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Track any Tumblr-side sponsored or partner account references here if they become relevant.',
                'notes' => 'Tumblr currently uses OAuth2 in this connector for account discovery and text publishing. Media and broader engagement workflows still require provider-specific follow-up.',
            ),
            'mastodon' => array(
                'label' => 'Mastodon',
                'wave' => 4,
                'category' => 'community',
                'required_fields' => array('base_url', 'client_id', 'client_secret'),
                'fields' => array('base_url', 'client_id', 'client_secret'),
                'suggested_scopes' => array('read', 'write', 'follow'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Mastodon is instance-driven and usually organic/community-led. Keep any paid or sponsorship relationships documented here if needed.',
                'notes' => 'Mastodon requires per-instance configuration. Base URL or instance URL must be entered explicitly.',
            ),
            'whatsapp_channels' => array(
                'label' => 'WhatsApp Channels',
                'wave' => 4,
                'category' => 'community',
                'required_fields' => array('app_id', 'client_secret'),
                'fields' => array('app_id', 'client_secret', 'webhook_secret'),
                'suggested_scopes' => array('whatsapp_business_messaging'),
                'suggested_ad_scopes' => array(),
                'ad_notes' => 'Use this field to track the related Meta business and campaign relationship if WhatsApp-linked promotion is used later.',
                'notes' => 'Treat as a later-stage broadcast connector in the Meta family with its own approval and messaging constraints.',
            ),
        );
    }
}
