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

class VMO_Promotion_Reddit_Connector extends VMO_Promotion_OAuth2_Connector {
    protected function build_authorization_url(array $settings, array $scopes, $state) {
        return add_query_arg(array(
            'client_id' => $this->get_client_identifier($settings),
            'response_type' => 'code',
            'state' => $state,
            'redirect_uri' => $this->get_callback_url(),
            'duration' => 'permanent',
            'scope' => implode(' ', $scopes),
        ), 'https://www.reddit.com/api/v1/authorize');
    }

    protected function get_token_endpoint() {
        return 'https://www.reddit.com/api/v1/access_token';
    }

    protected function request_token(array $body) {
        $settings = $this->get_settings();
        $basic = base64_encode($this->get_client_identifier($settings) . ':' . $this->get_client_secret($settings));
        $response = wp_remote_post($this->get_token_endpoint(), array(
            'timeout' => 20,
            'headers' => array(
                'Accept' => 'application/json',
                'Content-Type' => 'application/x-www-form-urlencoded',
                'Authorization' => 'Basic ' . $basic,
                'User-Agent' => $this->get_user_agent(),
            ),
            'body' => $body,
        ));

        return $this->parse_remote_response($response, true);
    }

    protected function discover_remote_accounts($user_id, array $token_context, array $request_context = array()) {
        $access_token = (string) ($token_context['access_token'] ?? '');
        if ($access_token === '') {
            return array();
        }

        $me = $this->reddit_request('GET', '/api/v1/me', $access_token);
        if (is_wp_error($me)) {
            return $me;
        }

        $name = sanitize_text_field($me['name'] ?? '');
        if ($name === '') {
            return array();
        }

        return array(
            array(
                'platform_key' => 'reddit',
                'platform_label' => 'Reddit',
                'external_account_id' => $name,
                'display_name' => $name,
                'auth_status' => 'connected',
                'connection_metadata' => array(
                    'connection_role' => 'reddit_user',
                    'username' => $name,
                    'icon_img' => esc_url_raw($me['icon_img'] ?? ''),
                    'default_target_id' => sanitize_text_field($this->get_settings()['default_target_id'] ?? ''),
                    'default_target_label' => sanitize_text_field($this->get_settings()['default_target_label'] ?? ''),
                ),
            ),
        );
    }

    public function publish_text_post(array $input) {
        $account = $this->get_platform_account_record($input);
        if (empty($account['access_token'])) {
            return new WP_Error('missing_connected_account', 'A connected Reddit account is required before publishing.');
        }

        $subreddit = $this->get_target_subreddit($account, $input);
        if ($subreddit === '') {
            return new WP_Error('missing_publish_target', 'Set a default subreddit name in VMO Settings before publishing to Reddit.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $title = sanitize_text_field($content_item['title'] ?? '');
        $text = $this->get_post_caption($content_item);

        if ($title === '') {
            $title = $this->truncate_text($text !== '' ? $text : 'VMO Reddit Post', 300);
        }

        $body = array(
            'api_type' => 'json',
            'raw_json' => 1,
            'kind' => 'self',
            'sr' => $subreddit,
            'title' => $title,
            'text' => $text,
        );

        $response = $this->reddit_request('POST', '/api/submit', $account['access_token'], $body);
        if (is_wp_error($response)) {
            return $response;
        }

        $post_id = sanitize_text_field($response['json']['data']['id'] ?? '');
        return array(
            'provider_post_id' => $post_id !== '' ? 't3_' . $post_id : '',
            'message' => 'Published to Reddit.',
            'response' => $response,
        );
    }

    public function publish_media_post(array $input) {
        return new WP_Error('provider_not_ready', 'Reddit media publishing is not activated yet in this build. Text/self-post publishing is available, but image/video submission still needs provider-specific handling.');
    }

    public function list_replies(array $input) {
        return new WP_Error('provider_not_ready', 'Reddit reply ingestion is not activated yet in this build.');
    }

    public function reply_to_comment(array $input) {
        $account = $this->get_platform_account_record($input);
        if (empty($account['access_token'])) {
            return new WP_Error('missing_connected_account', 'A connected Reddit account is required before replying.');
        }

        $thing_id = sanitize_text_field($input['comment_id'] ?? $input['provider_comment_id'] ?? $input['in_reply_to_id'] ?? '');
        if ($thing_id === '') {
            return new WP_Error('missing_comment_id', 'Reddit reply publishing requires a target thing_id.');
        }

        $text = sanitize_textarea_field($input['message'] ?? $input['text'] ?? '');
        if ($text === '' && !empty($input['content_item'])) {
            $text = $this->get_post_caption((array) $input['content_item']);
        }

        if ($text === '') {
            return new WP_Error('missing_reply_text', 'Reddit reply publishing requires reply text.');
        }

        $response = $this->reddit_request('POST', '/api/comment', $account['access_token'], array(
            'api_type' => 'json',
            'raw_json' => 1,
            'thing_id' => $thing_id,
            'text' => $text,
        ));
        if (is_wp_error($response)) {
            return $response;
        }

        $children = (array) ($response['json']['data']['things'] ?? array());
        $reply_id = '';
        foreach ($children as $child) {
            if (sanitize_text_field($child['kind'] ?? '') === 't1') {
                $reply_id = sanitize_text_field($child['data']['name'] ?? '');
                break;
            }
        }

        return array(
            'provider_post_id' => $reply_id,
            'message' => 'Reply published to Reddit.',
            'response' => $response,
        );
    }

    public function fetch_metrics(array $input) {
        return new WP_Error('provider_not_ready', 'Reddit metrics normalization is not finalized yet in this build.');
    }

    protected function reddit_request($method, $path, $access_token, array $body = array()) {
        $args = array(
            'method' => strtoupper($method),
            'timeout' => 30,
            'headers' => array(
                'Accept' => 'application/json',
                'Authorization' => 'Bearer ' . $access_token,
                'User-Agent' => $this->get_user_agent(),
            ),
        );

        if ($args['method'] === 'GET') {
            if (!empty($body)) {
                $path = add_query_arg($body, $path);
            }
        } elseif (!empty($body)) {
            $args['headers']['Content-Type'] = 'application/x-www-form-urlencoded';
            $args['body'] = $body;
        }

        $response = wp_remote_request('https://oauth.reddit.com' . $path, $args);
        if (is_wp_error($response)) {
            return $response;
        }

        $status = (int) wp_remote_retrieve_response_code($response);
        $data = json_decode((string) wp_remote_retrieve_body($response), true);
        if (!is_array($data)) {
            $data = array();
        }

        if ($status >= 400) {
            return new WP_Error(
                'provider_api_error',
                sanitize_text_field($data['message'] ?? $data['error'] ?? 'Reddit API request failed.'),
                array(
                    'platform_key' => 'reddit',
                    'status' => $status,
                    'response' => $data,
                )
            );
        }

        if (!empty($data['json']['errors']) && is_array($data['json']['errors'])) {
            $first = (array) $data['json']['errors'][0];
            return new WP_Error(
                sanitize_key($first[0] ?? 'provider_api_error'),
                sanitize_text_field($first[1] ?? 'Reddit API request failed.'),
                array(
                    'platform_key' => 'reddit',
                    'response' => $data,
                )
            );
        }

        return $data;
    }

    protected function get_target_subreddit(array $account, array $input) {
        $explicit = sanitize_text_field($input['subreddit'] ?? '');
        if ($explicit !== '') {
            return ltrim($explicit, '/r/');
        }

        $metadata = (array) ($account['connection_metadata'] ?? array());
        if (!empty($metadata['default_target_id'])) {
            return ltrim(sanitize_text_field($metadata['default_target_id']), '/r/');
        }

        $settings = $this->get_settings();
        return ltrim(sanitize_text_field($settings['default_target_id'] ?? ''), '/r/');
    }

    protected function get_user_agent() {
        return 'VMO Promotion Connector/1.0';
    }

    protected function truncate_text($value, $limit) {
        $value = trim((string) $value);
        if ($value === '') {
            return '';
        }

        if (function_exists('mb_strlen') && function_exists('mb_substr')) {
            return mb_strlen($value) > $limit ? rtrim(mb_substr($value, 0, $limit - 1)) : $value;
        }

        return strlen($value) > $limit ? rtrim(substr($value, 0, $limit - 1)) : $value;
    }
}
