<?php

namespace PloverCRM\Modules\Integrations\Endpoints;

use WP_REST_Request;
use PloverCRM\Core\Api\AbstractEndpoint;
use PloverCRM\Modules\Integrations\Services\AutomationsLogger;

/**
 * Google OAuth Callback Endpoint
 * 
 * Handles callback from the PloverCRM OAuth proxy server (Managed Mode only).
 */
class GoogleOAuthCallbackEndpoint extends AbstractEndpoint
{
    public function getRoute(): string
    {
        return '/google/oauth/callback';
    }

    public function getMethod()
    {
        return 'GET';
    }

    public function checkPermission(WP_REST_Request $request)
    {
        return true; // Callback is public
    }

    public function handle(WP_REST_Request $request)
    {
        $logger = new AutomationsLogger();
        $oauthData = $request->get_param('google_oauth_data');

        if (empty($oauthData)) {
            $logger->error('Google authorization callback failed', [
                'error' => 'Missing OAuth data from auth server.',
                '_activity' => [
                    'module' => 'integrations',
                    'feature' => 'connections',
                ],
            ]);
            return $this->redirectWithError('Missing OAuth data from auth server.');
        }

        $decoded = base64_decode(urldecode($oauthData));
        if (!$decoded) {
            $logger->error('Google authorization callback failed', [
                'error' => 'Invalid encoding from auth server.',
                '_activity' => [
                    'module' => 'integrations',
                    'feature' => 'connections',
                ],
            ]);
            return $this->redirectWithError('Invalid encoding from auth server.');
        }

        $data = json_decode($decoded, true);

        if (empty($data['success'])) {
            $logger->error('Google authorization callback failed', [
                'error' => (string) ($data['error'] ?? 'Unknown error from auth server.'),
                '_activity' => [
                    'module' => 'integrations',
                    'feature' => 'connections',
                ],
            ]);
            return $this->redirectWithError($data['error'] ?? 'Unknown error from auth server.');
        }

        if (empty($data['refresh_token'])) {
            $logger->error('Google authorization callback failed', [
                'error' => 'No refresh token returned. Please try again.',
                '_activity' => [
                    'module' => 'integrations',
                    'feature' => 'connections',
                ],
            ]);
            return $this->redirectWithError('No refresh token returned. Please try again.');
        }

        // Save Configuration (Managed Mode only)
        $config = [
            'access_token' => sanitize_text_field($data['access_token']),
            'refresh_token' => sanitize_text_field($data['refresh_token']),
            'developer_token' => sanitize_text_field($data['developer_token'] ?? ''),
            'updated_at' => time()
        ];

        update_option('plover_crm_google_config', $config);
        $logger->info('Google authorization connected', [
            'has_developer_token' => !empty($config['developer_token']),
            '_activity' => [
                'module' => 'integrations',
                'feature' => 'connections',
            ],
        ]);

        return $this->redirectWithSuccess();
    }

    private function redirectWithError(string $error)
    {
        $url = add_query_arg([
            'platform' => 'google-ads',
            'oauth' => 'error',
            'message' => $error,
        ], $this->resolveReturnUrl());
        wp_redirect($url);
        exit;
    }

    private function redirectWithSuccess()
    {
        $url = add_query_arg([
            'platform' => 'google-ads',
            'oauth' => 'success',
        ], $this->resolveReturnUrl());
        wp_redirect($url);
        exit;
    }

    private function resolveReturnUrl(): string
    {
        $appRedirect = trim((string) ($_GET['app_redirect'] ?? ''));
        $signature = trim((string) ($_GET['redirect_signature'] ?? ''));

        if ($appRedirect !== '' && $signature !== '') {
            $decodedAppRedirect = rawurldecode($appRedirect);
            $expectedSignature = hash_hmac('sha256', $decodedAppRedirect, wp_salt('auth'));
            $parts = wp_parse_url($decodedAppRedirect);
            $scheme = isset($parts['scheme']) ? strtolower((string) $parts['scheme']) : '';
            $host = (string) ($parts['host'] ?? '');

            if (
                hash_equals($expectedSignature, $signature) &&
                in_array($scheme, ['http', 'https'], true) &&
                $host !== ''
            ) {
                return $decodedAppRedirect;
            }
        }

        return home_url('/plover-crm/connections/');
    }
}
