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

class VMO_Promotion_Orchestrator {
    private static $instance = null;
    private $store;
    private $registry;

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

        return self::$instance;
    }

    private function __construct() {
        $this->store = class_exists('VMO_Promotion_Data_Store') ? VMO_Promotion_Data_Store::get_instance() : null;
        $this->registry = class_exists('VMO_Promotion_Provider_Registry') ? VMO_Promotion_Provider_Registry::get_instance() : null;
    }

    public function get_state($user_id) {
        $defaults = $this->default_settings();
        $default_queue = $this->default_queue();

        if (!$this->store) {
            return array(
                'settings' => $defaults,
                'queue' => $default_queue,
                'connected_accounts' => array(),
                'campaign' => array(),
            );
        }

        return $this->store->get_dashboard_state((int) $user_id, $defaults, $default_queue);
    }

    public function save_state($user_id, array $settings, array $queue) {
        if (!$this->store) {
            return array(
                'settings' => $settings,
                'queue' => $queue,
                'connected_accounts' => array(),
                'campaign' => array(),
            );
        }

        return $this->store->save_dashboard_state((int) $user_id, $settings, $queue);
    }

    public function get_provider_matrix($user_id) {
        $connected_accounts = $this->get_connected_accounts($user_id);
        return $this->registry ? $this->registry->build_ui_matrix($connected_accounts) : array();
    }

    public function get_connected_accounts($user_id) {
        if (!$this->store) {
            return array();
        }

        return $this->store->get_connected_accounts((int) $user_id);
    }

    public function get_campaign_summary($user_id) {
        $state = $this->get_state($user_id);
        $campaign = is_array($state['campaign'] ?? null) ? $state['campaign'] : array();

        return array(
            'id' => (int) ($campaign['id'] ?? 0),
            'campaign_type' => sanitize_key($campaign['campaign_type'] ?? 'social_posting'),
            'title' => sanitize_text_field($campaign['title'] ?? 'Social Media Posting Workspace'),
            'status' => sanitize_key($campaign['status'] ?? 'draft'),
            'approval_mode' => sanitize_key($campaign['approval_mode'] ?? 'manual'),
            'budget_mode' => sanitize_key($campaign['budget_mode'] ?? 'guided'),
        );
    }

    public function build_context($user_id, array $settings) {
        $profile = function_exists('vmo_get_consultation_profile') ? vmo_get_consultation_profile($user_id) : array();
        $insights = function_exists('vmo_get_cached_industry_insights') ? vmo_get_cached_industry_insights($user_id) : array();
        $business_name = sanitize_text_field($profile['business_name'] ?? (get_user_meta($user_id, 'business_name', true) ?: wp_get_current_user()->display_name ?: 'The business'));
        $industry = sanitize_text_field($profile['industry'] ?? (get_user_meta($user_id, 'business_type', true) ?: 'General'));
        $audience = sanitize_textarea_field($profile['target_audience'] ?? ($profile['ideal_customer'] ?? ''));
        $offers = $profile['core_offerings'] ?? ($profile['services'] ?? ($profile['products'] ?? array()));
        if (is_array($offers)) {
            $offers = implode(', ', array_map('sanitize_text_field', array_slice($offers, 0, 8)));
        }
        $location = sanitize_text_field($profile['location'] ?? ($profile['business_location'] ?? ''));
        $has_published_site = function_exists('vmo_user_has_published_site') ? vmo_user_has_published_site($user_id) : false;
        $has_payments = !empty(get_user_meta($user_id, 'vmo_pay_account_id', true));
        $insight_lines = array();
        if (is_array($insights)) {
            foreach (array('opportunities', 'threats', 'competitors') as $bucket) {
                foreach ((array) ($insights[$bucket] ?? array()) as $item) {
                    if (is_array($item)) {
                        $item = $item['title'] ?? $item['name'] ?? $item['summary'] ?? '';
                    }
                    $item = sanitize_text_field((string) $item);
                    if ($item !== '') {
                        $insight_lines[] = $item;
                    }
                    if (count($insight_lines) >= 6) {
                        break 2;
                    }
                }
            }
        }

        return array(
            'business_name' => $business_name !== '' ? $business_name : 'The business',
            'industry' => $industry,
            'audience' => $audience,
            'offers' => sanitize_textarea_field((string) $offers),
            'location' => $location,
            'has_published_site' => $has_published_site ? 'yes' : 'no',
            'has_payments' => $has_payments ? 'yes' : 'no',
            'insights' => implode('; ', $insight_lines),
            'platforms' => implode(', ', (array) ($settings['selected_platforms'] ?? array())),
            'goal' => sanitize_textarea_field($settings['goal'] ?? ''),
            'cta_destination' => sanitize_text_field($settings['cta_destination'] ?? ''),
            'cadence' => sanitize_text_field($settings['cadence'] ?? ''),
        );
    }

    private function default_settings() {
        if (function_exists('vmo_promotion_default_settings')) {
            return vmo_promotion_default_settings();
        }

        return array(
            'goal' => 'Help me create and distribute strategic social posts that attract the right followers, increase engagement, and promote my products effectively.',
            'social_mode' => 'ai',
            'selected_platforms' => array('Instagram', 'Facebook', 'LinkedIn', 'TikTok', 'YouTube'),
            'auto_post' => false,
            'reply_mode' => true,
            'promo_budget' => 6800,
            'cadence' => '5 posts per week',
            'cta_destination' => 'ai_recommend',
            'manual_notes' => '',
            'manual_assets' => array(),
            'latest_strategy' => array(),
            'latest_posts' => array(),
            'latest_engagement' => array(),
        );
    }

    private function default_queue() {
        if (function_exists('vmo_promotion_default_queue')) {
            return vmo_promotion_default_queue();
        }

        return array();
    }
}
