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

class VMO_Promotion_Pinterest_Connector extends VMO_Promotion_OAuth2_Connector {
    protected function build_authorization_url(array $settings, array $scopes, $state) {
        return add_query_arg(array(
            'response_type' => 'code',
            'client_id' => $this->get_client_identifier($settings),
            'redirect_uri' => $this->get_callback_url(),
            'scope' => implode(',', $scopes),
            'state' => $state,
        ), 'https://www.pinterest.com/oauth/');
    }

    protected function get_token_endpoint() {
        return 'https://api.pinterest.com/v5/oauth/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,
            ),
            '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();
        }

        $user = $this->api_get('https://api.pinterest.com/v5/user_account', $access_token);
        if (is_wp_error($user)) {
            return $user;
        }

        $user_account = (array) ($user['items'] ?? $user);
        $username = sanitize_text_field($user_account['username'] ?? '');

        $boards_response = $this->api_get('https://api.pinterest.com/v5/boards', $access_token, array(
            'page_size' => 100,
        ));
        if (is_wp_error($boards_response)) {
            return $boards_response;
        }

        $accounts = array();
        foreach ((array) ($boards_response['items'] ?? array()) as $board) {
            $board_id = sanitize_text_field($board['id'] ?? '');
            if ($board_id === '') {
                continue;
            }

            $accounts[] = array(
                'platform_key' => 'pinterest',
                'platform_label' => 'Pinterest',
                'external_account_id' => $board_id,
                'display_name' => sanitize_text_field($board['name'] ?? ('Pinterest Board ' . $board_id)),
                'auth_status' => 'connected',
                'connection_metadata' => array(
                    'connection_role' => 'pinterest_board',
                    'board_id' => $board_id,
                    'board_name' => sanitize_text_field($board['name'] ?? ''),
                    'board_url' => esc_url_raw($board['url'] ?? ''),
                    'owner_username' => $username,
                    'privacy' => sanitize_text_field($board['privacy'] ?? ''),
                ),
            );
        }

        if (empty($accounts) && $username !== '') {
            $accounts[] = array(
                'platform_key' => 'pinterest',
                'platform_label' => 'Pinterest',
                'external_account_id' => $username,
                'display_name' => $username,
                'auth_status' => 'connected',
                'connection_metadata' => array(
                    'connection_role' => 'pinterest_user',
                    'owner_username' => $username,
                ),
            );
        }

        return $accounts;
    }

    public function publish_text_post(array $input) {
        return new WP_Error('provider_not_ready', 'Pinterest publishing requires an image asset. Use the media publishing flow for this provider.');
    }

    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 Pinterest account is required before publishing.');
        }

        $board_id = $this->get_board_id($account);
        if ($board_id === '') {
            return new WP_Error('missing_publish_target', 'Select or configure a Pinterest board before publishing.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $asset = $this->extract_primary_asset($content_item);
        if (empty($asset['url'])) {
            return new WP_Error('missing_media_asset', 'Pinterest publishing requires a publicly reachable image URL.');
        }

        $mime = strtolower((string) ($asset['type'] ?? ''));
        if (strpos($mime, 'video/') === 0) {
            return new WP_Error('provider_not_ready', 'Pinterest video publishing is not activated yet in this build.');
        }

        $payload = array(
            'board_id' => $board_id,
            'title' => sanitize_text_field($content_item['title'] ?? $asset['name'] ?? 'VMO Pin'),
            'description' => $this->get_post_caption($content_item),
            'media_source' => array(
                'source_type' => 'image_url',
                'url' => esc_url_raw($asset['url']),
            ),
        );

        $cta_url = esc_url_raw($content_item['cta_url'] ?? '');
        if ($cta_url !== '') {
            $payload['link'] = $cta_url;
        }

        $response = $this->api_post('https://api.pinterest.com/v5/pins', $account['access_token'], $payload);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['id'] ?? ''),
            'message' => 'Published image Pin to Pinterest.',
            'response' => $response,
        );
    }

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

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

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

    protected function get_publish_account(array $input) {
        $account = (array) ($input['connected_account'] ?? array());
        if (!empty($account['access_token'])) {
            return $account;
        }

        if (!$this->store || !method_exists($this->store, 'get_connected_account_auth_rows')) {
            return $account;
        }

        $user_id = (int) ($input['user_id'] ?? 0);
        if ($user_id <= 0) {
            return $account;
        }

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

        $settings = $this->get_settings();
        $default_board_id = sanitize_text_field($settings['default_target_id'] ?? '');
        if ($default_board_id !== '') {
            foreach ($rows as $row) {
                if (sanitize_text_field($row['external_account_id'] ?? '') === $default_board_id) {
                    return $row;
                }
                $metadata = (array) ($row['connection_metadata'] ?? array());
                if (sanitize_text_field($metadata['board_id'] ?? '') === $default_board_id) {
                    return $row;
                }
            }
        }

        return $rows[0];
    }

    protected function get_board_id(array $account) {
        $metadata = (array) ($account['connection_metadata'] ?? array());
        $board_id = sanitize_text_field($metadata['board_id'] ?? $account['external_account_id'] ?? '');
        if ($board_id !== '') {
            return $board_id;
        }

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