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

class VMO_Promotion_Google_Business_Profile_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),
            'redirect_uri' => $this->get_callback_url(),
            'response_type' => 'code',
            'scope' => implode(' ', $scopes),
            'state' => $state,
            'access_type' => 'offline',
            'include_granted_scopes' => 'true',
            'prompt' => 'consent',
        ), 'https://accounts.google.com/o/oauth2/v2/auth');
    }

    protected function get_token_endpoint() {
        return 'https://oauth2.googleapis.com/token';
    }

    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();
        }

        $accounts_response = $this->api_get('https://mybusiness.googleapis.com/v4/accounts', $access_token);
        if (is_wp_error($accounts_response)) {
            return $accounts_response;
        }

        $connected = array();
        foreach ((array) ($accounts_response['accounts'] ?? array()) as $account) {
            $account_name = sanitize_text_field($account['name'] ?? '');
            $account_id = preg_replace('/^accounts\//', '', $account_name);
            if ($account_name === '') {
                continue;
            }

            $locations_response = $this->api_get('https://mybusiness.googleapis.com/v4/' . $account_name . '/locations', $access_token, array(
                'pageSize' => 100,
            ));

            if (is_wp_error($locations_response)) {
                $connected[] = array(
                    'platform_key' => 'google_business_profile',
                    'platform_label' => 'Google Business Profile',
                    'external_account_id' => $account_id,
                    'display_name' => sanitize_text_field($account['accountName'] ?? ('Google Business Profile Account ' . $account_id)),
                    'auth_status' => 'connected',
                    'connection_metadata' => array(
                        'connection_role' => 'gbp_account',
                        'account_name' => $account_name,
                    ),
                );
                continue;
            }

            foreach ((array) ($locations_response['locations'] ?? array()) as $location) {
                $location_name = sanitize_text_field($location['name'] ?? '');
                if ($location_name === '') {
                    continue;
                }

                $location_id = preg_replace('/^accounts\/[^\/]+\/locations\//', '', $location_name);
                $display_name = sanitize_text_field(
                    $location['locationName']
                    ?? $location['title']
                    ?? $location['storeCode']
                    ?? ('Google Business Profile Location ' . $location_id)
                );

                $connected[] = array(
                    'platform_key' => 'google_business_profile',
                    'platform_label' => 'Google Business Profile',
                    'external_account_id' => $location_id,
                    'display_name' => $display_name,
                    'auth_status' => 'connected',
                    'connection_metadata' => array(
                        'connection_role' => 'gbp_location',
                        'account_name' => $account_name,
                        'location_name' => $location_name,
                        'account_id' => $account_id,
                    ),
                );
            }
        }

        return $connected;
    }

    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 Google Business Profile location is required before publishing.');
        }

        $location_name = sanitize_text_field($account['connection_metadata']['location_name'] ?? '');
        if ($location_name === '') {
            return new WP_Error('missing_location', 'This Google Business Profile account is missing the location resource name required for publishing.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $payload = array(
            'summary' => $this->get_post_caption($content_item),
            'topicType' => 'STANDARD',
        );

        $cta_url = esc_url_raw($content_item['cta_url'] ?? '');
        if ($cta_url !== '') {
            $payload['callToAction'] = array(
                'actionType' => 'LEARN_MORE',
                'url' => $cta_url,
            );
        }

        $response = $this->api_post('https://mybusiness.googleapis.com/v4/' . $location_name . '/localPosts', $account['access_token'], $payload);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['name'] ?? ''),
            'message' => 'Published to Google Business Profile.',
            'response' => $response,
        );
    }

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

        $location_name = sanitize_text_field($account['connection_metadata']['location_name'] ?? '');
        if ($location_name === '') {
            return new WP_Error('missing_location', 'This Google Business Profile account is missing the location resource name required for publishing.');
        }

        $content_item = (array) ($input['content_item'] ?? array());
        $asset = $this->extract_primary_asset($content_item);

        $payload = array(
            'summary' => $this->get_post_caption($content_item),
            'topicType' => 'STANDARD',
        );

        $cta_url = esc_url_raw($content_item['cta_url'] ?? '');
        if ($cta_url !== '') {
            $payload['callToAction'] = array(
                'actionType' => 'LEARN_MORE',
                'url' => $cta_url,
            );
        }

        if (!empty($asset['url'])) {
            $mime = strtolower((string) ($asset['type'] ?? ''));
            $payload['media'] = array(array(
                'mediaFormat' => strpos($mime, 'video/') === 0 ? 'VIDEO' : 'PHOTO',
                'sourceUrl' => $asset['url'],
            ));
        }

        $response = $this->api_post('https://mybusiness.googleapis.com/v4/' . $location_name . '/localPosts', $account['access_token'], $payload);
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'provider_post_id' => sanitize_text_field($response['name'] ?? ''),
            'message' => 'Published media post to Google Business Profile.',
            'response' => $response,
        );
    }

    public function list_replies(array $input) {
        $account = $this->get_platform_account_record($input);
        if (empty($account['access_token'])) {
            return new WP_Error('missing_connected_account', 'A connected Google Business Profile location is required before loading reviews.');
        }

        $location_name = sanitize_text_field($account['connection_metadata']['location_name'] ?? '');
        if ($location_name === '') {
            return new WP_Error('missing_location', 'This Google Business Profile account is missing the location resource name required for loading reviews.');
        }

        $response = $this->api_get('https://mybusiness.googleapis.com/v4/' . $location_name . '/reviews', $account['access_token'], array(
            'pageSize' => 100,
        ));
        if (is_wp_error($response)) {
            return $response;
        }

        return array(
            'platform_key' => 'google_business_profile',
            'replies' => array_values((array) ($response['reviews'] ?? array())),
        );
    }

    public function reply_to_comment(array $input) {
        $account = $this->get_platform_account_record($input);
        $review_name = sanitize_text_field($input['comment_id'] ?? '');
        $message = sanitize_textarea_field($input['message'] ?? '');

        if (empty($account['access_token']) || $review_name === '' || $message === '') {
            return new WP_Error('missing_reply_context', 'A connected Google Business Profile location, review name, and reply message are required.');
        }

        $response = $this->api_put('https://mybusiness.googleapis.com/v4/' . $review_name . '/reply', $account['access_token'], wp_json_encode(array(
            'comment' => $message,
        )), array(
            'Content-Type' => 'application/json',
        ));

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

        return array(
            'platform_key' => 'google_business_profile',
            'message' => 'Review reply updated.',
            'response' => $response,
        );
    }

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