<?php
namespace auctionforge\inc\api;

use WP_REST_Controller;
use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;
use WP_Error;
use auctionforge\inc\helpers\SettingsHelper;

/**
 * Proxy for BidSpirit API calls to avoid CORS issues in Safari Private mode
 */
class BidSpiritProxy extends WP_REST_Controller {
    
    protected $namespace = 'auctionforge/v1';
    protected $bidspirit_server;
    
    public function __construct() {
        // Get BidSpirit server URL using SettingsHelper (same as rest of plugin)
        $this->bidspirit_server = SettingsHelper::getOption('server', '');
    }
    
    public function register_routes() {
        // Proxy for PayTrace lev.paytrace.com API (blocked in Safari Private)
        register_rest_route($this->namespace, '/paytrace/hpf-info', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'proxy_paytrace_hpf_info'],
                'permission_callback' => '__return_true',
            ]
        ]);
        
        // Proxy for getPayTraceSetupSecret
        register_rest_route($this->namespace, '/bidspirit/paytrace-secret', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'get_paytrace_secret'],
                'permission_callback' => '__return_true', // Allow public access
                'args' => [
                    'sessionId' => [
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field'
                    ]
                ]
            ]
        ]);
        
        // General proxy for any BidSpirit API call
        register_rest_route($this->namespace, '/bidspirit/proxy', [
            [
                'methods' => WP_REST_Server::CREATABLE,
                'callback' => [$this, 'proxy_bidspirit_api'],
                'permission_callback' => '__return_true',
                'args' => [
                    'apiAction' => [
                        'required' => true,
                        'type' => 'string',
                        'sanitize_callback' => 'sanitize_text_field'
                    ],
                    'data' => [
                        'required' => true,
                        'type' => 'object'
                    ]
                ]
            ]
        ]);
    }
    
    /**
     * Get PayTrace setup secret from BidSpirit
     */
    public function get_paytrace_secret(WP_REST_Request $request) {
        // Get sessionId and authToken from JSON body
        $json_params = $request->get_json_params();
        $session_id = isset($json_params['sessionId']) ? $json_params['sessionId'] : $request->get_param('sessionId');
        $auth_token = isset($json_params['authToken']) ? $json_params['authToken'] : $request->get_param('authToken');
        
        if (empty($session_id)) {
            return new WP_Error(
                'missing_session_id',
                'Session id is mandatory',
                ['status' => 400]
            );
        }
        
        if (empty($this->bidspirit_server)) {
            return new WP_Error(
                'no_bidspirit_server',
                'BidSpirit server URL not configured',
                ['status' => 500]
            );
        }
        
        $api_url = rtrim($this->bidspirit_server, '/') . 
                   '/api/thirdparty/v1/users/paymentMethods/getPayTraceSetupSecret.api';
        
        // Build headers - include auth token if provided
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json'
        ];
        
        if (!empty($auth_token)) {
            $headers['BIDSPIRIT-AUTH-TOKEN'] = $auth_token;
        }
        
        // Make request to BidSpirit
        $response = wp_remote_post($api_url, [
            'headers' => $headers,
            'body' => json_encode([
                'sessionId' => $session_id
            ]),
            'timeout' => 15,
            'sslverify' => true
        ]);
        
        if (is_wp_error($response)) {
            return new WP_Error(
                'bidspirit_api_error',
                'Failed to contact BidSpirit API: ' . $response->get_error_message(),
                ['status' => 502]
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        if ($status_code !== 200) {
            return new WP_Error(
                'bidspirit_api_error',
                'BidSpirit API returned error: ' . $status_code,
                ['status' => $status_code]
            );
        }
        
        // Return the same structure as BidSpirit
        return new WP_REST_Response($data, 200);
    }
    
    /**
     * General proxy for BidSpirit API calls
     */
    public function proxy_bidspirit_api(WP_REST_Request $request) {
        $api_action = $request->get_param('apiAction');
        $data = $request->get_param('data');
        
        if (empty($this->bidspirit_server)) {
            return new WP_Error(
                'no_bidspirit_server',
                'BidSpirit server URL not configured',
                ['status' => 500]
            );
        }
        
        // Whitelist allowed API actions for security
        $allowed_actions = [
            'users/paymentMethods/getPayTraceSetupSecret',
            'users/paymentMethods/getPaymentMethods',
            'users/paymentMethods/checkPaymentMethodSaved',
            'users/paymentMethods/removePaymentMethod',
            'users/paymentMethods/saveCardFromPayTrace'
        ];
        
        if (!in_array($api_action, $allowed_actions)) {
            return new WP_Error(
                'unauthorized_action',
                'API action not allowed through proxy',
                ['status' => 403]
            );
        }
        
        $api_url = rtrim($this->bidspirit_server, '/') . 
                   '/api/thirdparty/v1/' . $api_action . '.api';
        
        // Make request to BidSpirit
        $response = wp_remote_post($api_url, [
            'headers' => [
                'Content-Type' => 'application/json',
                'Accept' => 'application/json'
            ],
            'body' => json_encode($data),
            'timeout' => 15,
            'sslverify' => true
        ]);
        
        if (is_wp_error($response)) {
            return new WP_Error(
                'bidspirit_api_error',
                'Failed to contact BidSpirit API: ' . $response->get_error_message(),
                ['status' => 502]
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return new WP_REST_Response($data, $status_code);
    }
    
    /**
     * Proxy for PayTrace hpf_info.json API (blocked in Safari Private mode)
     */
    public function proxy_paytrace_hpf_info(WP_REST_Request $request) {
        // Get the request body
        $json_params = $request->get_json_params();
        $body = $json_params ? json_encode($json_params) : '{}';
        
        // Get original URL and headers from custom headers
        $original_url = $request->get_header('X-PayTrace-Original-URL');
        $captured_headers_json = $request->get_header('X-PayTrace-Headers');
        
        error_log('[PayTrace Proxy] === NEW REQUEST ===');
        error_log('[PayTrace Proxy] Original URL: ' . ($original_url ?: 'not provided'));
        error_log('[PayTrace Proxy] Captured headers: ' . ($captured_headers_json ?: 'none'));
        error_log('[PayTrace Proxy] Request body: ' . $body);
        
        // Determine target URL
        if ($original_url) {
            $api_url = $original_url;
        } else {
            // Fallback to default
            $is_sandbox = defined('PAYTRACE_SANDBOX') && PAYTRACE_SANDBOX;
            $api_url = $is_sandbox 
                ? 'https://lev.sandbox.paytrace.com/v1/guest/hpf_info.json'
                : 'https://lev.paytrace.com/v1/guest/hpf_info.json';
        }
        
        error_log('[PayTrace Proxy] Target URL: ' . $api_url);
        
        // Build headers - start with PayTrace CORS requirements
        $headers = [
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
            'Origin' => 'https://secure.paytrace.com',
            'Referer' => 'https://secure.paytrace.com/'
        ];
        
        // Add captured headers from PTPayment.setup
        if ($captured_headers_json) {
            $captured_headers = json_decode($captured_headers_json, true);
            if ($captured_headers && is_array($captured_headers)) {
                error_log('[PayTrace Proxy] Adding captured headers: ' . print_r($captured_headers, true));
                $headers = array_merge($headers, $captured_headers);
            }
        }
        
        // Forward all request headers that might be important
        $forward_headers = ['Authorization', 'X-Requested-With', 'User-Agent'];
        foreach ($forward_headers as $header_name) {
            $header_value = $request->get_header($header_name);
            if ($header_value) {
                $headers[$header_name] = $header_value;
                error_log('[PayTrace Proxy] Forwarding header: ' . $header_name . ' = ' . $header_value);
            }
        }
        
        error_log('[PayTrace Proxy] Final headers: ' . print_r($headers, true));
        
        // Make request to PayTrace API
        $response = wp_remote_post($api_url, [
            'headers' => $headers,
            'body' => $body,
            'timeout' => 15,
            'sslverify' => true
        ]);
        
        if (is_wp_error($response)) {
            return new WP_Error(
                'paytrace_api_error',
                'Failed to connect to PayTrace API: ' . $response->get_error_message(),
                ['status' => 500]
            );
        }
        
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = wp_remote_retrieve_body($response);
        
        error_log('[PayTrace Proxy] Response code: ' . $response_code);
        error_log('[PayTrace Proxy] Response body: ' . substr($response_body, 0, 500));
        
        // Parse JSON response
        $parsed_body = json_decode($response_body, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            error_log('[PayTrace Proxy] JSON decode error: ' . json_last_error_msg());
            return new WP_Error(
                'invalid_response',
                'Invalid JSON response from PayTrace API',
                ['status' => 502]
            );
        }
        
        // Create response with CORS headers
        $wp_response = new WP_REST_Response($parsed_body, $response_code);
        $wp_response->header('Access-Control-Allow-Origin', '*');
        $wp_response->header('Access-Control-Allow-Methods', 'POST, OPTIONS');
        $wp_response->header('Access-Control-Allow-Headers', 'Content-Type, Accept');
        $wp_response->header('Access-Control-Allow-Credentials', 'true');
        
        return $wp_response;
    }
}
