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

class VMO_Promotion_Provider_Registry {
    private static $instance = null;
    private $catalog = array();
    private $connectors = array();

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

        return self::$instance;
    }

    private function __construct() {
        $this->catalog = $this->build_catalog();
    }

    public function normalize_platform_key($platform) {
        $platform = strtolower(trim((string) $platform));
        $platform = str_replace(array('&', '/', '-', '(', ')'), ' ', $platform);
        $platform = preg_replace('/\s+/', '_', $platform);
        $platform = sanitize_key($platform);

        $aliases = array(
            'google_business_profile' => 'google_business_profile',
            'discord_community' => 'discord_community',
            'whatsapp_channels' => 'whatsapp_channels',
            'x' => 'x',
        );

        return $aliases[$platform] ?? $platform;
    }

    public function get_catalog() {
        return $this->catalog;
    }

    public function get_provider($platform) {
        $key = $this->normalize_platform_key($platform);
        return $this->catalog[$key] ?? array();
    }

    public function get_provider_profile($platform) {
        $key = $this->normalize_platform_key($platform);
        if (class_exists('VMO_Promotion_Admin_Settings')) {
            $profiles = VMO_Promotion_Admin_Settings::get_provider_profiles();
            return $profiles[$key] ?? array();
        }

        return array();
    }

    public function get_provider_config($platform) {
        $key = $this->normalize_platform_key($platform);
        if (class_exists('VMO_Promotion_Admin_Settings')) {
            $raw = VMO_Promotion_Admin_Settings::get_provider_settings($key);
            $missing_required_fields = VMO_Promotion_Admin_Settings::get_missing_required_fields($key, $raw);
            $credentials_ready = VMO_Promotion_Admin_Settings::has_required_credentials($key, $raw);
            $callback_url = VMO_Promotion_Admin_Settings::get_provider_callback_url($key);
            $webhook_url = VMO_Promotion_Admin_Settings::get_provider_webhook_url($key);
        } else {
            $all = get_option('vmo_promotion_provider_settings', array());
            if (!is_array($all)) {
                $all = array();
            }
            $raw = isset($all[$key]) && is_array($all[$key]) ? $all[$key] : array();
            $missing_required_fields = array();
            $credentials_ready = !empty($raw);
            $callback_url = '';
            $webhook_url = '';
        }

        $connector_enabled = !empty($raw['connector_enabled']);
        $admin_ready = $connector_enabled && $credentials_ready;

        return array(
            'admin_ready' => $admin_ready,
            'credentials_ready' => $credentials_ready,
            'connector_enabled' => $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_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' => array_values(array_filter(array_map('sanitize_text_field', (array) ($raw['configured_scopes'] ?? array())))),
            'ad_account_id' => sanitize_text_field($raw['ad_account_id'] ?? ''),
            'ad_scopes' => array_values(array_filter(array_map('sanitize_text_field', (array) ($raw['ad_scopes'] ?? array())))),
            'default_target_id' => sanitize_text_field($raw['default_target_id'] ?? ''),
            'default_target_label' => sanitize_text_field($raw['default_target_label'] ?? ''),
            'missing_required_fields' => array_values(array_map('sanitize_key', $missing_required_fields)),
            'callback_url' => esc_url_raw($callback_url),
            'webhook_url' => esc_url_raw($webhook_url),
        );
    }

    public function get_connector($platform) {
        $provider = $this->get_provider($platform);
        if (empty($provider)) {
            return null;
        }

        $key = $provider['platform_key'];
        if (!isset($this->connectors[$key])) {
            $this->connectors[$key] = $this->instantiate_connector($provider);
        }

        return $this->connectors[$key];
    }

    public function build_ui_matrix(array $connected_accounts = array()) {
        $matrix = array();
        foreach ($this->catalog as $provider) {
            $matrix[] = $this->build_provider_row($provider, $connected_accounts);
        }

        usort($matrix, function($a, $b) {
            if ($a['rollout_wave'] === $b['rollout_wave']) {
                return strcmp($a['label'], $b['label']);
            }
            return (int) $a['rollout_wave'] <=> (int) $b['rollout_wave'];
        });

        return $matrix;
    }

    private function build_provider_row(array $provider, array $connected_accounts) {
        $platform_key = $provider['platform_key'];
        $config = $this->get_provider_config($platform_key);
        $accounts = array_values(array_filter($connected_accounts, function($row) use ($platform_key) {
            return sanitize_key($row['platform_key'] ?? '') === $platform_key;
        }));

        $status_key = 'admin_setup_required';
        if ($config['admin_ready']) {
            $status_key = 'not_connected';
            if (in_array($config['app_review_status'], array('pending', 'in_review'), true)) {
                $status_key = 'awaiting_provider_approval';
            } elseif (
                !empty($provider['capabilities']['domain_verification_required'])
                && !in_array($config['domain_verification_status'], array('verified', 'not_required'), true)
            ) {
                $status_key = 'awaiting_provider_approval';
            } elseif (in_array($config['app_review_status'], array('rejected', 'disabled'), true)) {
                $status_key = 'publishing_disabled';
            } elseif (!empty($accounts)) {
                $status_key = 'connected_limited';
                foreach ($accounts as $account) {
                    $auth_status = sanitize_key($account['auth_status'] ?? '');
                    if (in_array($auth_status, array('expired', 'refresh_needed', 'needs_reconnect'), true)) {
                        $status_key = 'needs_reconnect';
                        break;
                    }
                    if (!empty($account['publish_enabled'])) {
                        $status_key = 'ready_to_publish';
                    }
                }
            }
        }

        $capabilities = $provider['capabilities'];
        $ad_management = 'No';
        if (!empty($capabilities['ad_management'])) {
            if (!empty($config['ads_enabled']) && $config['admin_ready'] && in_array($config['marketing_api_status'], array('approved', 'limited'), true)) {
                $ad_management = 'Credential-Ready';
            } elseif (!empty($config['ads_enabled']) && $config['admin_ready']) {
                $ad_management = 'Setup In Progress';
            } else {
                $ad_management = 'Coming Soon';
            }
        }

        $effective = array(
            'draft_generation' => 'Yes',
            'direct_publish' => ($config['publish_enabled'] && $config['admin_ready'] && !empty($accounts) && ($capabilities['publish_text'] || $capabilities['publish_image'] || $capabilities['publish_video'] || $capabilities['publish_carousel'])) ? 'Yes' : 'No',
            'media_upload' => ($config['publish_enabled'] && $config['admin_ready'] && ($capabilities['publish_image'] || $capabilities['publish_video'] || $capabilities['publish_carousel'])) ? 'Yes' : 'No',
            'replies' => ($config['reply_enabled'] && $config['admin_ready'] && !empty($accounts) && ($capabilities['reply_read'] || $capabilities['reply_write'])) ? 'Yes' : (($capabilities['reply_read'] || $capabilities['reply_write']) ? 'Limited' : 'No'),
            'metrics' => ($config['metrics_enabled'] && $config['admin_ready'] && !empty($accounts) && !empty($capabilities['metrics_read'])) ? 'Yes' : (!empty($capabilities['metrics_read']) ? 'Partial' : 'No'),
            'ad_management' => $ad_management,
            'webhooks' => !empty($capabilities['webhooks']) ? 'Yes' : 'No',
        );

        return array(
            'platform_key' => $platform_key,
            'label' => $provider['label'],
            'category' => $provider['category'],
            'rollout_wave' => $provider['rollout_wave'],
            'status_key' => $status_key,
            'status_label' => $this->status_label($status_key),
            'connected_accounts' => count($accounts),
            'config' => $config,
            'capabilities' => $capabilities,
            'effective_support' => $effective,
        );
    }

    private function status_label($status_key) {
        $labels = array(
            'admin_setup_required' => 'Admin Setup Required',
            'not_connected' => 'Not Connected',
            'connected_limited' => 'Connected, Limited',
            'ready_to_publish' => 'Ready to Publish',
            'awaiting_provider_approval' => 'Awaiting Provider Approval',
            'publishing_disabled' => 'Publishing Disabled',
            'needs_reconnect' => 'Needs Reconnect',
        );

        return $labels[$status_key] ?? 'Not Connected';
    }

    private function instantiate_connector(array $provider) {
        $key = $provider['platform_key'];
        $profile = $this->get_provider_profile($key);

        if (
            in_array($key, array('instagram', 'facebook', 'threads'), true)
            && class_exists('VMO_Promotion_Meta_Connector')
        ) {
            return new VMO_Promotion_Meta_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'linkedin' && class_exists('VMO_Promotion_LinkedIn_Connector')) {
            return new VMO_Promotion_LinkedIn_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'google_business_profile' && class_exists('VMO_Promotion_Google_Business_Profile_Connector')) {
            return new VMO_Promotion_Google_Business_Profile_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'youtube' && class_exists('VMO_Promotion_YouTube_Connector')) {
            return new VMO_Promotion_YouTube_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'telegram' && class_exists('VMO_Promotion_Telegram_Connector')) {
            return new VMO_Promotion_Telegram_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'mastodon' && class_exists('VMO_Promotion_Mastodon_Connector')) {
            return new VMO_Promotion_Mastodon_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'tiktok' && class_exists('VMO_Promotion_TikTok_Connector')) {
            return new VMO_Promotion_TikTok_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'x' && class_exists('VMO_Promotion_X_Connector')) {
            return new VMO_Promotion_X_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'pinterest' && class_exists('VMO_Promotion_Pinterest_Connector')) {
            return new VMO_Promotion_Pinterest_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'discord_community' && class_exists('VMO_Promotion_Discord_Connector')) {
            return new VMO_Promotion_Discord_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'reddit' && class_exists('VMO_Promotion_Reddit_Connector')) {
            return new VMO_Promotion_Reddit_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if ($key === 'tumblr' && class_exists('VMO_Promotion_Tumblr_Connector')) {
            return new VMO_Promotion_Tumblr_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if (class_exists('VMO_Promotion_Configured_Connector')) {
            return new VMO_Promotion_Configured_Connector($key, $provider['label'], $provider['capabilities'], $profile);
        }

        if (class_exists('VMO_Promotion_Null_Connector')) {
            return new VMO_Promotion_Null_Connector($key, $provider['label'], $provider['capabilities']);
        }

        error_log('VMO Promotions: no connector class available for ' . $key . '; returning null connector instance.');
        return null;
    }

    private function build_catalog() {
        return array(
            'instagram' => $this->provider('instagram', 'Instagram', 'social', 1, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => true,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'facebook' => $this->provider('facebook', 'Facebook', 'social', 1, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => true,
                'reply_read' => true,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'threads' => $this->provider('threads', 'Threads', 'social', 1, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => false,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'linkedin' => $this->provider('linkedin', 'LinkedIn', 'professional', 1, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'google_business_profile' => $this->provider('google_business_profile', 'Google Business Profile', 'local', 1, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => true,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => true,
                'domain_verification_required' => true,
            )),
            'tiktok' => $this->provider('tiktok', 'TikTok', 'social', 2, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'pinterest' => $this->provider('pinterest', 'Pinterest', 'social', 2, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => true,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'x' => $this->provider('x', 'X', 'social', 2, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => false,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => true,
                'metrics_read' => true,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'youtube' => $this->provider('youtube', 'YouTube', 'video', 2, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => false,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => true,
                'reply_write' => true,
                'metrics_read' => true,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => true,
            )),
            'reddit' => $this->provider('reddit', 'Reddit', 'community', 3, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => false,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'telegram' => $this->provider('telegram', 'Telegram', 'community', 3, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => true,
                'ad_management' => false,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
            'discord_community' => $this->provider('discord_community', 'Discord Community', 'community', 3, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
            'snapchat' => $this->provider('snapchat', 'Snapchat', 'social', 4, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'tumblr' => $this->provider('tumblr', 'Tumblr', 'community', 4, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => false,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
            'mastodon' => $this->provider('mastodon', 'Mastodon', 'community', 4, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => true,
                'reply_write' => true,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
            'whatsapp_channels' => $this->provider('whatsapp_channels', 'WhatsApp Channels', 'community', 4, array(
                'connect_supported' => true,
                'publish_text' => true,
                'publish_image' => true,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => true,
                'domain_verification_required' => false,
            )),
            'vibe_co' => $this->provider('vibe_co', 'Vibe.co', 'streaming_tv', 2, array(
                'connect_supported' => true,
                'publish_text' => false,
                'publish_image' => false,
                'publish_video' => true,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => true,
                'webhooks' => false,
                'ad_management' => true,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
        );
    }

    private function provider($platform_key, $label, $category, $rollout_wave, array $capabilities) {
        return array(
            'platform_key' => $platform_key,
            'label' => $label,
            'category' => $category,
            'rollout_wave' => (int) $rollout_wave,
            'capabilities' => wp_parse_args($capabilities, array(
                'connect_supported' => false,
                'publish_text' => false,
                'publish_image' => false,
                'publish_video' => false,
                'publish_carousel' => false,
                'reply_read' => false,
                'reply_write' => false,
                'metrics_read' => false,
                'webhooks' => false,
                'ad_management' => false,
                'app_review_required' => false,
                'domain_verification_required' => false,
            )),
        );
    }
}
