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

class VMO_Promotion_Configured_Connector extends VMO_Promotion_Base_Connector {
    protected $provider_profile = array();

    public function __construct($platform_key, $platform_label, array $capabilities = array(), array $provider_profile = array()) {
        parent::__construct($platform_key, $platform_label, $capabilities);
        $this->provider_profile = $provider_profile;
    }

    public function connect_account(array $input) {
        $settings = $this->get_settings();
        $missing = $this->get_missing_required_fields($settings);

        return array(
            'platform_key' => $this->platform_key,
            'platform_label' => $this->platform_label,
            'connect_supported' => !empty($this->capabilities['connect_supported']),
            'credentials_ready' => empty($missing),
            'missing_fields' => $missing,
            'callback_url' => $this->get_callback_url(),
            'webhook_url' => $this->get_webhook_url(),
            'message' => empty($missing)
                ? 'Provider credentials are present. Complete the provider-side OAuth, asset linking, and app approval steps to activate this connector.'
                : 'Provider credentials are still incomplete. Add the missing fields in VMO Settings before attempting connection.',
        );
    }

    public function handle_callback(array $request) {
        $user_id = (int) ($request['user_id'] ?? 0);

        if (class_exists('VMO_Promotion_Data_Store')) {
            VMO_Promotion_Data_Store::get_instance()->log_event(
                $user_id,
                'provider_callback_received',
                sprintf('OAuth callback received for %s.', $this->platform_label),
                array(
                    'platform_key' => $this->platform_key,
                    'request' => array(
                        'code' => isset($request['code']) ? 'present' : 'missing',
                        'state' => sanitize_text_field($request['state'] ?? ''),
                        'error' => sanitize_key($request['error'] ?? ''),
                    ),
                )
            );
        }

        return array(
            'success' => true,
            'platform_key' => $this->platform_key,
            'platform_label' => $this->platform_label,
            'message' => 'Provider callback received, but this platform is still using the generic configured connector. Add a concrete connector to activate live OAuth completion.',
        );
    }

    public function validate_scopes(array $input) {
        $settings = $this->get_settings();
        $granted_scopes = array_values(array_filter(array_map('sanitize_text_field', (array) ($settings['configured_scopes'] ?? array()))));
        $required_scopes = array_values(array_filter(array_map('sanitize_text_field', (array) ($this->provider_profile['suggested_scopes'] ?? array()))));
        $missing_scopes = array_values(array_diff($required_scopes, $granted_scopes));

        return array(
            'valid' => empty($missing_scopes),
            'platform_key' => $this->platform_key,
            'missing_scopes' => $missing_scopes,
            'granted_scopes' => $granted_scopes,
            'required_scopes' => $required_scopes,
        );
    }

    public function list_accounts(array $input) {
        $user_id = (int) ($input['user_id'] ?? 0);
        $accounts = array();
        if ($user_id > 0 && class_exists('VMO_Promotion_Data_Store')) {
            $all_accounts = VMO_Promotion_Data_Store::get_instance()->get_connected_accounts($user_id);
            foreach ($all_accounts as $row) {
                if (sanitize_key($row['platform_key'] ?? '') === $this->platform_key) {
                    $accounts[] = $row;
                }
            }
        }

        return array(
            'platform_key' => $this->platform_key,
            'accounts' => $accounts,
        );
    }

    public function register_webhook(array $input) {
        $settings = $this->get_settings();
        return array(
            'platform_key' => $this->platform_key,
            'webhook_supported' => !empty($this->capabilities['webhooks']),
            'webhook_url' => $this->get_webhook_url(),
            'configured' => !empty($settings['webhook_secret']) || empty($this->capabilities['webhooks']),
            'message' => !empty($this->capabilities['webhooks'])
                ? 'Webhook endpoint is available. Provider-specific verification and event subscription still need to be completed in the real connector.'
                : 'This provider does not use webhooks in the current capability model.',
        );
    }

    public function list_ad_accounts(array $input) {
        $settings = $this->get_settings();

        return array(
            'platform_key' => $this->platform_key,
            'ad_management_supported' => !empty($this->capabilities['ad_management']),
            'ad_account_id' => sanitize_text_field($settings['ad_account_id'] ?? ''),
            'marketing_api_status' => sanitize_key($settings['marketing_api_status'] ?? 'not_requested'),
            'message' => !empty($this->capabilities['ad_management'])
                ? 'Provider ad-management settings are stored. Live ad-account discovery depends on the concrete connector implementation.'
                : 'This provider is not currently modeled as an ad-management connector.',
        );
    }

    public function create_ad_draft(array $input) {
        $settings = $this->get_settings();
        $ready = !empty($settings['ads_enabled']) && !empty($settings['ad_account_id']);

        return array(
            'platform_key' => $this->platform_key,
            'draft_created' => $ready,
            'message' => $ready
                ? 'Provider ad settings are present. Concrete campaign creation depends on the provider-specific ads connector.'
                : 'Provider ads settings are incomplete. Enable ads and record the ad account ID before creating ad drafts.',
        );
    }

    public function launch_ad_campaign(array $input) {
        return new WP_Error('provider_not_ready', sprintf('%s ad campaign launch is not activated yet in this connector.', $this->platform_label));
    }

    public function fetch_ad_metrics(array $input) {
        return new WP_Error('provider_not_ready', sprintf('%s ad metrics are not normalized yet in this connector.', $this->platform_label));
    }

    public function receive_webhook($payload) {
        $payload_text = is_scalar($payload) ? (string) $payload : wp_json_encode($payload);
        if (class_exists('VMO_Promotion_Data_Store')) {
            VMO_Promotion_Data_Store::get_instance()->log_event(
                0,
                'provider_webhook_received',
                sprintf('Webhook received for %s.', $this->platform_label),
                array(
                    'platform_key' => $this->platform_key,
                    'payload' => $payload_text,
                )
            );
        }

        return array(
            'success' => true,
            'platform_key' => $this->platform_key,
            'accepted' => true,
            'message' => 'Webhook payload received. Platform-specific processing still depends on the concrete connector implementation.',
        );
    }

    protected function get_settings() {
        if (!class_exists('VMO_Promotion_Admin_Settings')) {
            return array();
        }

        return VMO_Promotion_Admin_Settings::get_provider_settings($this->platform_key);
    }

    protected function get_missing_required_fields(array $settings = array()) {
        if (!class_exists('VMO_Promotion_Admin_Settings')) {
            return array();
        }

        return VMO_Promotion_Admin_Settings::get_missing_required_fields($this->platform_key, $settings);
    }

    protected function get_callback_url() {
        if (!class_exists('VMO_Promotion_Admin_Settings')) {
            return '';
        }

        return VMO_Promotion_Admin_Settings::get_provider_callback_url($this->platform_key);
    }

    protected function get_webhook_url() {
        if (!class_exists('VMO_Promotion_Admin_Settings')) {
            return '';
        }

        return VMO_Promotion_Admin_Settings::get_provider_webhook_url($this->platform_key);
    }
}
