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

class RsApiController{
    public static function rsValidateApiToken($token) {
        if(empty($token)){
            return $token;
        }
        $apiUrl = RS_API_URL . "/properties/validate_api_for_wp";
        $response = wp_remote_get($apiUrl, [
            'headers' => [
                'Api-Token' => $token,
                'Accept' => 'application/json'
            ],
            'timeout' => 10
        ]);
        if(is_wp_error($response)){
            add_settings_error(
                'rs_zoddak_api_token',
                'api_connection_failed',
                'No se pudo conectar a la API. Por favor, verifica la URL y el token.',
            );
            return get_option('rs_zoddak_api_token');
        }
        $body_raw = wp_remote_retrieve_body($response);
        $body = json_decode($body_raw, true);

        $status_code = $body['status_code']; // ← ESTE CAMBIO
        if($status_code == '401' || $status_code == '403'){
            add_settings_error(
                'rs_zoddak_api_token',
                'api_invalid_token',
                $body['message'] ?? 'Token inválido',  // 'content' no existe, es 'message'
            );
            return get_option('rs_zoddak_api_token');
        }
        if($status_code == 200){
            add_settings_error(
                'rs_zoddak_api_token',
                'api_valid_token',
                'Token verificado con exito.',
                'updated'
            );
            return $token;
        }
        add_settings_error(
            'rs_zoddak_api_token',
            'api_unknown_error',
            'No se pudo verificar el token. Código de estado:' . print_r($body, true)
        );
        return get_option('rs_zoddak_api_token');
    }
    public static function get_types()
    {
        $apiUrl = RS_API_URL . '/types/get_types';
        $token = esc_attr(get_option('rs_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 [];
        }
        $types =  $body['data'];
        return $types;
    }
    public static function get_areas()
    {
        $apiUrl = RS_API_URL . '/locations/get_location_for_resales';
        $token = esc_attr(get_option('rs_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 [];
        }
        $areas =  $body['areas'];
        return $areas;
    }

}