<?php

// namespace App\Classes;

// use Illuminate\Support\Facades\Http;

// class OpenMeteo
// {

//     public static function Crawl(float $lat, float $lng): ?array
//     {
//         $url = 'https://api.open-meteo.com/v1/forecast';
        
//         $response = Http::timeout(30)->get($url, [
//             'latitude' => $lat,
//             'longitude' => $lng,
//             'current' => 'temperature_2m,relative_humidity_2m,apparent_temperature,is_day,wind_speed_10m,wind_direction_10m,wind_gusts_10m,precipitation,rain,showers,snowfall,weather_code,cloud_cover,pressure_msl,surface_pressure,visibility',
//             'hourly' => 'temperature_2m,relative_humidity_2m,dew_point_2m,apparent_temperature,precipitation,precipitation_probability,showers,rain,snowfall,snow_depth,weather_code,surface_pressure,pressure_msl,cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,visibility,evapotranspiration,et0_fao_evapotranspiration,vapour_pressure_deficit,wind_speed_10m,wind_direction_10m,uv_index,is_day,sunshine_duration',
//             'daily' => 'weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant,shortwave_radiation_sum,et0_fao_evapotranspiration,sunrise,sunset,daylight_duration,uv_index_max,sunshine_duration,uv_index_clear_sky_max,rain_sum,showers_sum,snowfall_sum,precipitation_sum,precipitation_hours,precipitation_probability_max',
//             'timezone' => 'Asia/Tehran',
//         ]);

//         if ($response->successful()) {
//             return $response->json();
//         }

//         return null;
//     }
// }

// namespace App\Classes;

// use Illuminate\Support\Facades\Http;
// use Illuminate\Support\Facades\Log;
// use Illuminate\Http\Client\ConnectionException;
// use Exception;

// class OpenMeteo
// {
//     public static function Crawl(float $lat, float $lng): ?array
//     {
//         $url = 'https://api.open-meteo.com/v1/forecast';
        
//         try {

//             $response = Http::retry(3, 500, function (Exception $exception) {
//                 return $exception instanceof ConnectionException;
//             })
//             ->timeout(30)
//             ->withHeaders([
//                 // ارسال User-Agent الزامی برای بسیاری از API های رایگان
//                 'User-Agent' => 'YourAppName/1.0 (your-email@example.com)',
//                 'Accept'     => 'application/json',
//             ])
//             ->withOptions([
//                 // اجبار cURL به استفاده از IPv4 برای جلوگیری از گیر کردن در شبکه IPv6
//                 'curl' => [
//                     CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
//                 ],
//                 // اگر در محیط لوکال هستید و خطای SSL دارید، مقدار زیر را false کنید
//                 // 'verify' => false, 
//             ])
//             ->get($url, [
//                 'latitude' => $lat,
//                 'longitude' => $lng,
//                 'current' => 'temperature_2m,relative_humidity_2m,apparent_temperature,is_day,wind_speed_10m,wind_direction_10m,wind_gusts_10m,precipitation,rain,showers,snowfall,weather_code,cloud_cover,pressure_msl,surface_pressure,visibility',
//                 'hourly' => 'temperature_2m,relative_humidity_2m,dew_point_2m,apparent_temperature,precipitation,precipitation_probability,showers,rain,snowfall,snow_depth,weather_code,surface_pressure,pressure_msl,cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,visibility,evapotranspiration,et0_fao_evapotranspiration,vapour_pressure_deficit,wind_speed_10m,wind_direction_10m,uv_index,is_day,sunshine_duration',
//                 'daily' => 'weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant,shortwave_radiation_sum,et0_fao_evapotranspiration,sunrise,sunset,daylight_duration,uv_index_max,sunshine_duration,uv_index_clear_sky_max,rain_sum,showers_sum,snowfall_sum,precipitation_sum,precipitation_hours,precipitation_probability_max',
//                 'timezone' => 'Asia/Tehran',
//             ]);

//             if ($response->successful()) {
//                 return $response->json();
//             }

//             Log::warning('OpenMeteo API returned error', [
//                 'status' => $response->status(),
//                 'body' => $response->body(),
//                 'lat' => $lat,
//                 'lng' => $lng
//             ]);

//         } catch (ConnectionException $e) {
//             Log::error('OpenMeteo API Connection Exception', [
//                 'message' => $e->getMessage(),
//                 'lat' => $lat,
//                 'lng' => $lng
//             ]);
//         } catch (Exception $e) {
//             Log::error('OpenMeteo API General Exception', [
//                 'message' => $e->getMessage()
//             ]);
//         }

//         return null;
//     }
// }


namespace App\Classes;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Http\Client\ConnectionException;
use Exception;

class OpenMeteo
{
    // تغییر نوع بازگشتی به array|false
    public static function Crawl(float $lat, float $lng): array|false
    {
        $url = 'https://api.open-meteo.com/v1/forecast';
        
        try {
            $response = Http::retry(3, 500, function (Exception $exception) {
                return $exception instanceof ConnectionException;
            })
            ->timeout(2)
            ->withHeaders([
                'User-Agent' => 'YourAppName/1.0 (your-email@example.com)',
                'Accept'     => 'application/json',
            ])
            ->withOptions([
                'curl' => [
                    CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4,
                ],
            ])
            ->get($url, [
                'latitude' => $lat,
                'longitude' => $lng,
                'current' => 'temperature_2m,relative_humidity_2m,apparent_temperature,is_day,wind_speed_10m,wind_direction_10m,wind_gusts_10m,precipitation,rain,showers,snowfall,weather_code,cloud_cover,pressure_msl,surface_pressure,visibility',
                'hourly' => 'temperature_2m,relative_humidity_2m,dew_point_2m,apparent_temperature,precipitation,precipitation_probability,showers,rain,snowfall,snow_depth,weather_code,surface_pressure,pressure_msl,cloud_cover,cloud_cover_low,cloud_cover_mid,cloud_cover_high,visibility,evapotranspiration,et0_fao_evapotranspiration,vapour_pressure_deficit,wind_speed_10m,wind_direction_10m,uv_index,is_day,sunshine_duration',
                'daily' => 'weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant,shortwave_radiation_sum,et0_fao_evapotranspiration,sunrise,sunset,daylight_duration,uv_index_max,sunshine_duration,uv_index_clear_sky_max,rain_sum,showers_sum,snowfall_sum,precipitation_sum,precipitation_hours,precipitation_probability_max',
                'timezone' => 'Asia/Tehran',
            ]);

            if ($response->successful()) {
                return $response->json();
            }

            Log::warning('OpenMeteo API returned error', [
                'status' => $response->status(),
                'body' => $response->body(),
                'lat' => $lat,
                'lng' => $lng
            ]);

        } catch (ConnectionException $e) {
            Log::error('OpenMeteo API Connection Exception', [
                'message' => $e->getMessage(),
                'lat' => $lat,
                'lng' => $lng
            ]);
        } catch (Exception $e) {
            Log::error('OpenMeteo API General Exception', [
                'message' => $e->getMessage()
            ]);
        }

        // در صورت بروز هرگونه خطا یا تایم‌اوت، false برمی‌گردد
        return false;
    }
}
