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

class VMO_Promotion_Telegram_Connector extends VMO_Promotion_Configured_Connector {
    private $store;

    public function __construct($platform_key, $platform_label, array $capabilities = array(), array $provider_profile = array()) {
        parent::__construct($platform_key, $platform_label, $capabilities, $provider_profile);
        $this->store = class_exists('VMO_Promotion_Data_Store') ? VMO_Promotion_Data_Store::get_instance() : null;
    }

    public function connect_account(array $input) {
        $settings = $this->get_settings();
        $missing = $this->get_missing_required_fields($settings);
        if (!empty($missing)) {
            return new WP_Error(
                'missing_credentials',
                sprintf('Missing required credentials for %s: %s.', $this->platform_label, implode(', ', array_map(array('VMO_Promotion_Admin_Settings', 'label_for_field'), $missing))),
                array(
                    'platform_key' => $this->platform_key,
                    'missing_fields' => $missing,
                )
            );
        }

        $me = $this->telegram_request($settings['bot_token'], 'getMe');
        if (is_wp_error($me)) {
            return $me;
        }

        $result = (array) ($me['result'] ?? array());
        $user_id = (int) ($input['user_id'] ?? 0);
        $account = array(
            'platform_key' => 'telegram',
            'platform_label' => 'Telegram',
            'external_account_id' => sanitize_text_field($result['id'] ?? ''),
            'display_name' => sanitize_text_field($result['username'] ?? $result['first_name'] ?? 'Telegram Bot'),
            'auth_status' => 'connected',
            'granted_scopes' => array('bot_api'),
            'access_token' => sanitize_text_field($settings['bot_token'] ?? ''),
            'refresh_token' => '',
            'token_expires_at' => '',
            'refresh_status' => 'not_applicable',
            'app_review_status' => 'approved',
            'publish_enabled' => !empty($settings['publish_enabled']),
            'reply_enabled' => !empty($settings['reply_enabled']),
            'metrics_enabled' => !empty($settings['metrics_enabled']),
            'connection_metadata' => array(
                'connection_role' => 'telegram_bot',
                'bot_username' => sanitize_text_field($result['username'] ?? ''),
                'default_target_id' => sanitize_text_field($settings['default_target_id'] ?? ''),
                'default_target_label' => sanitize_text_field($settings['default_target_label'] ?? ''),
            ),
        );

        $saved = $this->store ? $this->store->upsert_connected_account($user_id, $account) : $account;
        return array(
            'success' => true,
            'platform_key' => 'telegram',
            'platform_label' => 'Telegram',
            'requires_redirect' => false,
            'connected_accounts' => !empty($saved) ? array($saved) : array(),
            'connected_accounts_count' => !empty($saved) ? 1 : 0,
            'message' => 'Telegram bot validated and connected.',
        );
    }

    public function handle_callback(array $request) {
        return new WP_Error('provider_not_ready', 'Telegram does not use an OAuth callback in this connector. Validate the bot token directly from VMO Settings.');
    }

    public function refresh_auth(array $input) {
        return $this->connect_account($input);
    }

    public function list_accounts(array $input) {
        return parent::list_accounts($input);
    }

    public function register_webhook(array $input) {
        $settings = $this->get_settings();
        if (empty($settings['bot_token'])) {
            return new WP_Error('missing_credentials', 'Telegram bot token is required before registering a webhook.');
        }

        $payload = array(
            'url' => $this->get_webhook_url(),
        );
        if (!empty($settings['webhook_secret'])) {
            $payload['secret_token'] = sanitize_text_field($settings['webhook_secret']);
        }

        $response = $this->telegram_request($settings['bot_token'], 'setWebhook', $payload);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'platform_key' => 'telegram',
            'webhook_supported' => true,
            'webhook_url' => $this->get_webhook_url(),
            'configured' => !empty($response['ok']),
            'message' => sanitize_text_field($response['description'] ?? 'Telegram webhook registered.'),
        );
    }

    public function receive_webhook($payload) {
        $data = is_array($payload) ? $payload : array('body' => $payload);
        $body = json_decode((string) ($data['body'] ?? ''), true);
        if (!is_array($body)) {
            $body = array();
        }

        if ($this->store) {
            $this->store->log_event(
                0,
                'telegram_webhook_received',
                'Telegram webhook received.',
                array(
                    'platform_key' => 'telegram',
                    'payload' => $body,
                )
            );
        }

        return array(
            'success' => true,
            'platform_key' => 'telegram',
            'accepted' => true,
        );
    }

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

        $target = $this->get_publish_target($account);
        if ($target === '') {
            return new WP_Error('missing_publish_target', 'Set a default Telegram target chat ID or @channelusername in VMO Settings before publishing.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $response = $this->telegram_request($account['access_token'], 'sendMessage', array(
            'chat_id' => $target,
            'text' => $this->get_caption($content_item),
        ));

        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['result']['message_id'] ?? ''),
            'message' => 'Published to Telegram.',
            'response' => $response,
        );
    }

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

        $target = $this->get_publish_target($account);
        if ($target === '') {
            return new WP_Error('missing_publish_target', 'Set a default Telegram target chat ID or @channelusername in VMO Settings before publishing.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $asset = $this->extract_asset($content_item);
        if (empty($asset['url'])) {
            return $this->publish_text_post($input);
        }

        $mime = strtolower((string) ($asset['type'] ?? ''));
        if (strpos($mime, 'video/') === 0) {
            $response = $this->telegram_request($account['access_token'], 'sendVideo', array(
                'chat_id' => $target,
                'video' => $asset['url'],
                'caption' => $this->get_caption($content_item),
                'supports_streaming' => 'true',
            ));
        } else {
            $response = $this->telegram_request($account['access_token'], 'sendPhoto', array(
                'chat_id' => $target,
                'photo' => $asset['url'],
                'caption' => $this->get_caption($content_item),
            ));
        }

        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['result']['message_id'] ?? ''),
            'message' => 'Published media post to Telegram.',
            'response' => $response,
        );
    }

    public function list_replies(array $input) {
        return new WP_Error('provider_not_ready', 'Telegram reply ingestion is webhook-driven and not yet normalized into a read API in this build.');
    }

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

        $target = sanitize_text_field($input['chat_id'] ?? $this->get_publish_target($account));
        $message = sanitize_textarea_field($input['message'] ?? '');
        if ($target === '' || $message === '') {
            return new WP_Error('missing_reply_context', 'A Telegram target chat and reply message are required.');
        }

        $body = array(
            'chat_id' => $target,
            'text' => $message,
        );
        $reply_to_message_id = (int) ($input['comment_id'] ?? 0);
        if ($reply_to_message_id > 0) {
            $body['reply_parameters'] = wp_json_encode(array(
                'message_id' => $reply_to_message_id,
            ));
        }

        $response = $this->telegram_request($account['access_token'], 'sendMessage', $body);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'platform_key' => 'telegram',
            'provider_reply_id' => sanitize_text_field($response['result']['message_id'] ?? ''),
            'message' => 'Reply sent to Telegram.',
            'response' => $response,
        );
    }

    private function telegram_request($bot_token, $method, array $body = array()) {
        $url = 'https://api.telegram.org/bot' . rawurlencode((string) $bot_token) . '/' . ltrim($method, '/');
        $response = wp_remote_post($url, array(
            'timeout' => 30,
            'body' => $body,
        ));

        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 || empty($data['ok'])) {
            return new WP_Error(
                'provider_api_error',
                sanitize_text_field($data['description'] ?? 'Telegram API request failed.'),
                array(
                    'platform_key' => 'telegram',
                    'status' => $status,
                    'response' => $data,
                )
            );
        }

        return $data;
    }

    private function get_publish_account(array $input) {
        $account = (array) ($input['connected_account'] ?? array());
        if (!empty($account['access_token']) || !empty($account['id'])) {
            return $this->hydrate_account($account, (int) ($input['user_id'] ?? 0));
        }

        return $this->hydrate_account(array(), (int) ($input['user_id'] ?? 0));
    }

    private function hydrate_account(array $account, $user_id) {
        if (!$this->store || !method_exists($this->store, 'get_connected_account_auth_rows') || $user_id <= 0) {
            return $account;
        }

        $rows = $this->store->get_connected_account_auth_rows($user_id, 'telegram');
        if (empty($rows)) {
            return $account;
        }

        if (!empty($account['id'])) {
            foreach ($rows as $row) {
                if ((int) $row['id'] === (int) $account['id']) {
                    return $row;
                }
            }
        }

        return $rows[0];
    }

    private function get_publish_target(array $account) {
        $metadata = (array) ($account['connection_metadata'] ?? array());
        if (!empty($metadata['default_target_id'])) {
            return sanitize_text_field($metadata['default_target_id']);
        }

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

    private function get_caption(array $content_item) {
        $caption = sanitize_textarea_field($content_item['caption_master'] ?? '');
        $cta = esc_url_raw($content_item['cta_url'] ?? '');
        if ($cta !== '' && strpos($caption, $cta) === false) {
            $caption = trim($caption . "\n\n" . $cta);
        }

        return trim($caption);
    }

    private function extract_asset(array $content_item) {
        $bundle = (array) ($content_item['media_bundle'] ?? array());
        $assets = array_values((array) ($bundle['manual_assets'] ?? array()));
        if (empty($assets)) {
            return array();
        }

        return (array) $assets[0];
    }
}
