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

class ApiController{

    public static function validateApiToken($token) {
        if(!$token){
            $token = get_option('zoddak_api_token', '');
        }
        error_log('🔍 Validando token API: ' . $token);
        $sandbox = get_option('zoddak_activate_sandbox', 0);
        if(!empty($sandbox) && !empty($token)){
            $apiUrl = esc_attr(get_option('zoddak_api_url') . '/sandbox');
            $response = wp_remote_get($apiUrl, [
                'headers' => [
                    'Api-Token' => $token,
                    'Accept' => 'application/json'
                ],
                'timeout' => 10
            ]);
        }elseif(empty($token)){
            add_settings_error(
                'zoddak_api_token',
                'api_empty_token',
                'El token de API está vacío. Por favor, introduce un token válido.'
            );
            return;
        }else{
            $apiUrl = esc_attr(get_option('zoddak_api_url', 'https://api.zoddak.com/v1/developments'));
            $response = wp_remote_get($apiUrl, [
                'headers' => [
                    'Api-Token' => $token,
                    'Accept' => 'application/json'
                ],
                'timeout' => 10
            ]);
        }
        if(is_wp_error($response)){
            add_settings_error(
                'zoddak_api_token',
                'api_connection_failed',
                'No se pudo conectar a la API. Por favor, verifica la URL y el token.',
            );
            error_log('🔴 Error WP_Error en validateApiToken: ' . $response->get_error_message());
            add_settings_error('zoddak_api_token', 'api_connection_failed', 'Error al conectar con la API: ' . esc_html($response->get_error_message()));
            return get_option('zoddak_api_token');
        }
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status_code = $body['status'];
        if($status_code === 401 || $status_code === 403){
            add_settings_error(
                'zoddak_api_token',
                'api_invalid_token',
                $body['content'],
            );
            return get_option('zoddak_api_token');
        }
        if($status_code === 200){
            add_settings_error(
                'zoddak_api_token',
                'api_valid_token',
                'Token verificado con exito.',
                'updated'
            );
            return $token;
        }
        add_settings_error(
            'zoddak_api_token',
            'api_unknown_error',
            'No se pudo verificar el token. Código de estado:' . $status_code
        );
        return get_option('zoddak_api_token');
    }
    public static function get_areas()
    {
        $cache_key = 'zoddak_areas';
        $cached = get_transient($cache_key);
        $apiUrl = 'https://api.zoddak.com/v1/locations';
        $token = esc_attr(get_option('zoddak_api_token', ''));
        $response = wp_remote_get($apiUrl, [
            'headers' => [
                'Api-Token' => $token,
                'Accept' => 'application/json'
            ],
            'timeout' => 10
        ]);
        if(is_wp_error($response)){
            add_settings_error(
                'zoddak_api_token',
                'api_connection_failed',
                'No se pudo conectar a la API. Por favor, verifica la URL y el token.',
            );
            error_log('🔴 Error WP_Error en validateApiToken: ' . $response->get_error_message());
            return [];
        }
        $body = json_decode(wp_remote_retrieve_body($response), true);
        if (!is_array($body)) {
            error_log('🔴 Zoddak get_areas: JSON inválido. HTTP ' . $http_code . ' Body: ' . $body);
            return [];
        }
        $api_status = isset($body['status']) ? (int)$body['status'] : $http_code;
        if($api_status !== 200) {
            $msg = $body['content'] ?? $body['message'] ?? 'Respuesta desconocida';
            error_log("🔴 Zoddak get_areas: API status {$api_status}. Msg: " . (is_string($msg) ? $msg : json_encode($msg)));
            return [];
        }
        $locations = reset($body['zones']) ?? [];
        $zones = reset($body['zones'])['provinces']?? [];
        return $zones;
    }


    public static function get_property_stage()
    {
        $cache_key = 'zoddak_property_stages';
        $cached = get_transient($cache_key);

        if ($cached !== false) {
            return $cached;
        }

        $apiUrl = 'https://api.zoddak.com/v1/stages';
        $token = esc_attr(get_option('zoddak_api_token', ''));

        if (empty($token)) {
            return [];
        }

        $response = wp_remote_get($apiUrl, [
            'headers' => [
                'Api-Token' => $token,
                'Accept' => 'application/json'
            ],
            'timeout' => 10
        ]);

        $body = json_decode(wp_remote_retrieve_body($response), true);
        $stages = $body['stages'] ?? [];

        // Caché 6 horas
        set_transient($cache_key, $stages, 6 * HOUR_IN_SECONDS);

        return $stages;
    }

}