<?php
/**
 * REST API endpoint for Synastry Chart generation
 *
 * @package EZHoroscope
 */

defined('ABSPATH') || exit;

add_action('rest_api_init', function () {
    register_rest_route('ezhp/v1', '/synastry-chart', [
        'methods'             => 'POST',
        'callback'            => 'ezhp_rest_synastry_chart',
        'permission_callback' => '__return_true',
    ]);
});

// Add no-cache headers to synastry chart responses
add_filter('rest_post_dispatch', function ($response, $server, $request) {
    if ($request->get_route() === '/ezhp/v1/synastry-chart') {
        $response->header('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0');
        $response->header('Pragma', 'no-cache');
        $response->header('Expires', '0');
    }
    return $response;
}, 10, 3);

/**
 * Handle synastry chart API request
 *
 * @param WP_REST_Request $ezhp_request The REST request object.
 * @return array Response with image data or error.
 */
function ezhp_rest_synastry_chart( WP_REST_Request $ezhp_request ) {

    $ezhp_body = $ezhp_request->get_json_params();

    // Person A data
    $ezhp_location_a = isset($ezhp_body['locationA']) ? sanitize_text_field($ezhp_body['locationA']) : '';
    $ezhp_datetime_a = isset($ezhp_body['birthDateTimeLocalA']) ? sanitize_text_field($ezhp_body['birthDateTimeLocalA']) : '';
    $ezhp_name_a = isset($ezhp_body['nameA']) ? sanitize_text_field($ezhp_body['nameA']) : '';

    // Person B data
    $ezhp_location_b = isset($ezhp_body['locationB']) ? sanitize_text_field($ezhp_body['locationB']) : '';
    $ezhp_datetime_b = isset($ezhp_body['birthDateTimeLocalB']) ? sanitize_text_field($ezhp_body['birthDateTimeLocalB']) : '';
    $ezhp_name_b = isset($ezhp_body['nameB']) ? sanitize_text_field($ezhp_body['nameB']) : '';

    // Shared settings
    $ezhp_language = isset($ezhp_body['language']) ? sanitize_text_field($ezhp_body['language']) : 'en';
    $ezhp_house_system = isset($ezhp_body['houseSystem']) ? sanitize_text_field($ezhp_body['houseSystem']) : 'placidus';
    $ezhp_style = isset($ezhp_body['styleSettings']) ? $ezhp_body['styleSettings'] : [];

    // Validation
    if (empty($ezhp_location_a)) {
        return [
            'error' => 'Location for Person A is required.',
        ];
    }

    if (empty($ezhp_datetime_a)) {
        return [
            'error' => 'Birth date and time for Person A is required.',
        ];
    }

    if (empty($ezhp_location_b)) {
        return [
            'error' => 'Location for Person B is required.',
        ];
    }

    if (empty($ezhp_datetime_b)) {
        return [
            'error' => 'Birth date and time for Person B is required.',
        ];
    }

    // Format datetime for API - DO NOT append 'Z' as this is LOCAL time
    $ezhp_datetime_a_formatted = ezhp_format_synastry_datetime($ezhp_datetime_a);
    $ezhp_datetime_b_formatted = ezhp_format_synastry_datetime($ezhp_datetime_b);

    // Build the payload for the external API
    $ezhp_payload = [
        'locationA'           => $ezhp_location_a,
        'birthDateTimeLocalA' => $ezhp_datetime_a_formatted,
        'nameA'               => $ezhp_name_a ?: 'Person A',
        'locationB'           => $ezhp_location_b,
        'birthDateTimeLocalB' => $ezhp_datetime_b_formatted,
        'nameB'               => $ezhp_name_b ?: 'Person B',
        'language'            => $ezhp_language,
        'houseSystem'         => $ezhp_house_system,
        'styleSettings'       => ezhp_sanitize_synastry_style_settings($ezhp_style),
    ];

    $ezhp_api_key = sanitize_text_field(get_option('ezhp_horoscope_activation_guid', ''));

    $ezhp_api_url = 'https://api.ezhoroscope.com/astrology/birth-chart-image/synastry/by-location-styled?apikey=' . rawurlencode($ezhp_api_key);

    // Debug logging (enable WP_DEBUG and WP_DEBUG_LOG in wp-config.php to see)
    if (defined('WP_DEBUG') && WP_DEBUG) {
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        error_log('EZHP Synastry Chart - Payload: ' . wp_json_encode($ezhp_payload));
    }

    $ezhp_response = wp_remote_post($ezhp_api_url, [
        'timeout' => 45, // Synastry charts may take longer
        'headers' => [
            'Content-Type' => 'application/json',
            'Accept'       => 'image/png',
        ],
        'body'    => wp_json_encode($ezhp_payload),
    ]);

    if (is_wp_error($ezhp_response)) {
        return [
            'error' => 'Error contacting API: ' . $ezhp_response->get_error_message(),
        ];
    }

    $ezhp_status_code = wp_remote_retrieve_response_code($ezhp_response);

    if (400 === $ezhp_status_code) {
        $ezhp_error_body = wp_remote_retrieve_body($ezhp_response);
        $ezhp_error_data = json_decode($ezhp_error_body, true);
        
        // Debug logging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            error_log('EZHP Synastry Chart - 400 Error Response: ' . $ezhp_error_body);
        }
        
        $ezhp_error_msg = isset($ezhp_error_data['error']) ? $ezhp_error_data['error'] : 'Invalid request.';
        return [
            'error' => $ezhp_error_msg,
        ];
    }

    if ($ezhp_status_code < 200 || $ezhp_status_code >= 300) {
        return [
            'error' => 'API returned status code: ' . $ezhp_status_code,
        ];
    }

    $ezhp_image_data = wp_remote_retrieve_body($ezhp_response);
    $ezhp_content_type = wp_remote_retrieve_header($ezhp_response, 'content-type');

    // Check if we got an image
    if (strpos($ezhp_content_type, 'image/png') !== false) {
        // Return as base64 data URL
        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
        $ezhp_base64 = base64_encode($ezhp_image_data);
        return [
            'image' => 'data:image/png;base64,' . $ezhp_base64,
        ];
    }

    // Maybe it's JSON with an error
    $ezhp_json_data = json_decode($ezhp_image_data, true);
    if (json_last_error() === JSON_ERROR_NONE && isset($ezhp_json_data['error'])) {
        return [
            'error' => $ezhp_json_data['error'],
        ];
    }

    return [
        'error' => 'Unexpected response from API.',
    ];
}

/**
 * Format datetime for synastry API
 *
 * @param string $ezhp_datetime The datetime string to format.
 * @return string Formatted datetime string.
 */
function ezhp_format_synastry_datetime( $ezhp_datetime ) {
    $ezhp_formatted = $ezhp_datetime;
    
    if (strlen($ezhp_datetime) === 16) {
        // datetime-local format without seconds - just add seconds
        $ezhp_formatted = $ezhp_datetime . ':00';
    } elseif (strlen($ezhp_datetime) === 19) {
        // Has seconds already, use as-is
        $ezhp_formatted = $ezhp_datetime;
    } elseif (substr($ezhp_datetime, -1) === 'Z') {
        // Strip the Z suffix if present - we want local time, not UTC
        $ezhp_formatted = substr($ezhp_datetime, 0, -1);
        // Also strip milliseconds if present (e.g., .000Z -> remove .000)
        if (preg_match('/\.\d{3}$/', $ezhp_formatted)) {
            $ezhp_formatted = substr($ezhp_formatted, 0, -4);
        }
    }
    
    return $ezhp_formatted;
}

/**
 * Sanitize style settings array for synastry chart
 *
 * @param array $ezhp_style The style settings array.
 * @return array Sanitized style settings.
 */
function ezhp_sanitize_synastry_style_settings( $ezhp_style ) {

    $ezhp_sanitized = [];

    // Handle backgroundColor specially to allow 'transparent'
    if (isset($ezhp_style['backgroundColor'])) {
        if ($ezhp_style['backgroundColor'] === 'transparent') {
            $ezhp_sanitized['backgroundColor'] = 'transparent';
        } else {
            $ezhp_sanitized['backgroundColor'] = sanitize_hex_color($ezhp_style['backgroundColor']);
        }
    }

    // String color fields (excluding backgroundColor which is handled above)
    $ezhp_color_fields = [
        'circleColor',
        'pointsColor',
        'signsColor',
        'cuspsColor',
        'lineColor',
        'axisFontColor',
        'legendFontColor',
        'legendBorderColor',
        'colorAries',
        'colorTaurus',
        'colorGemini',
        'colorCancer',
        'colorLeo',
        'colorVirgo',
        'colorLibra',
        'colorScorpio',
        'colorSagittarius',
        'colorCapricorn',
        'colorAquarius',
        'colorPisces',
    ];

    foreach ($ezhp_color_fields as $ezhp_field) {
        if (isset($ezhp_style[$ezhp_field])) {
            $ezhp_sanitized[$ezhp_field] = sanitize_hex_color($ezhp_style[$ezhp_field]);
        }
    }

    // Float fields
    $ezhp_float_fields = [
        'symbolScale',
        'pointsStroke',
        'signsStroke',
        'circleStrong',
        'cuspsStroke',
        'axisStroke',
        'indoorCircleRadiusRatio',
        'innerCircleRadiusRatio',
        'rulerRadius',
    ];

    foreach ($ezhp_float_fields as $ezhp_field) {
        if (isset($ezhp_style[$ezhp_field])) {
            $ezhp_sanitized[$ezhp_field] = floatval($ezhp_style[$ezhp_field]);
        }
    }

    // Integer fields
    $ezhp_int_fields = [
        'pointsTextSize',
        'margin',
        'padding',
        'collisionRadius',
        'shiftInDegrees',
    ];

    foreach ($ezhp_int_fields as $ezhp_field) {
        if (isset($ezhp_style[$ezhp_field])) {
            $ezhp_sanitized[$ezhp_field] = intval($ezhp_style[$ezhp_field]);
        }
    }

    // Boolean fields
    $ezhp_bool_fields = [
        'transparentBackground',
        'strokeOnly',
        'addClickArea',
        'showDignitiesText',
        'debug',
    ];

    foreach ($ezhp_bool_fields as $ezhp_field) {
        if (isset($ezhp_style[$ezhp_field])) {
            $ezhp_sanitized[$ezhp_field] = (bool) $ezhp_style[$ezhp_field];
        }
    }

    // Sign colors array (alternative to individual color fields)
    if (isset($ezhp_style['signColors']) && is_array($ezhp_style['signColors'])) {
        $ezhp_sanitized['signColors'] = [];
        foreach ($ezhp_style['signColors'] as $ezhp_color) {
            $ezhp_sanitized['signColors'][] = sanitize_hex_color($ezhp_color);
        }
    } else {
        // Build signColors array from individual zodiac color fields in zodiac order
        $ezhp_zodiac_order = [
            'colorAries',
            'colorTaurus',
            'colorGemini',
            'colorCancer',
            'colorLeo',
            'colorVirgo',
            'colorLibra',
            'colorScorpio',
            'colorSagittarius',
            'colorCapricorn',
            'colorAquarius',
            'colorPisces',
        ];
        $ezhp_sanitized['signColors'] = [];
        foreach ($ezhp_zodiac_order as $ezhp_zodiac_field) {
            if (isset($ezhp_sanitized[$ezhp_zodiac_field])) {
                $ezhp_sanitized['signColors'][] = $ezhp_sanitized[$ezhp_zodiac_field];
            }
        }
    }

    // Aspect colors (object)
    if (isset($ezhp_style['aspectColors']) && is_array($ezhp_style['aspectColors'])) {
        $ezhp_sanitized['aspectColors'] = [];
        foreach ($ezhp_style['aspectColors'] as $ezhp_key => $ezhp_value) {
            $ezhp_sanitized['aspectColors'][sanitize_text_field($ezhp_key)] = sanitize_hex_color($ezhp_value);
        }
    }

    // Aspect configs (object with color and orbit)
    if (isset($ezhp_style['aspectConfigs']) && is_array($ezhp_style['aspectConfigs'])) {
        $ezhp_sanitized['aspectConfigs'] = [];
        foreach ($ezhp_style['aspectConfigs'] as $ezhp_key => $ezhp_config) {
            if (is_array($ezhp_config)) {
                $ezhp_sanitized['aspectConfigs'][sanitize_text_field($ezhp_key)] = [
                    'color' => isset($ezhp_config['color']) ? sanitize_hex_color($ezhp_config['color']) : '',
                    'orbit' => isset($ezhp_config['orbit']) ? floatval($ezhp_config['orbit']) : 10,
                ];
            }
        }
    }

    return $ezhp_sanitized;
}