<?php

namespace App\Http\Controllers\Website;

use App\Http\Controllers\Controller;
use App\Models\SubDistrict;
use App\Models\WeatherSubDistrict;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class ParameterListWeatherSubDistrictController extends Controller
{
    public function index()
    {
        return view('website.app.parameter-list-weather-sub-district');
    }

    public function getDataParameterListWeatherSubDistrict($year)
    {
        $subDistricts = SubDistrict::select('id', 'sub_district', 'latitude', 'longitude')->get();
        $listWeatherSubDictrict = WeatherSubDistrict::select(
            'weather_sub_districts.id as weather_id',
            'weather_sub_districts.allsky_sfc_sw_dwn',
            'weather_sub_districts.prectotcorr',
            'weather_sub_districts.rh2m',
            'weather_sub_districts.t2m',
            'weather_sub_districts.ws2m',
            'weather_sub_districts.month',
            'weather_sub_districts.year',
            'sub_district.id as sub_district_id',
            'sub_district.sub_district',
            'sub_district.latitude',
            'sub_district.longitude'
        )
            ->join('sub_district', 'weather_sub_districts.sub_district_id', '=', 'sub_district.id')
            ->where('weather_sub_districts.year', $year)
            ->get();


        return response()->json([
            'subDistrict' => $subDistricts,
            'listWeatherSubDistrict' => $listWeatherSubDictrict
        ]);
    }

    public function updateListParameterWeatherSubDistrict($years)
    {
        $subDistrictALl = SubDistrict::select('id', 'sub_district', 'latitude', 'longitude')->get();

        set_time_limit(300);
        try {
            foreach ($subDistrictALl as $subDistrict) {
                $responseWeather = Http::get("https://power.larc.nasa.gov/api/temporal/monthly/point?start={$years}&end={$years}&latitude={$subDistrict['latitude']}&longitude={$subDistrict['longitude']}&community=ag&parameters=prectotcorr,T2M,WS2M,RH2M,ALLSKY_SFC_SW_DWN&format=json&header=true&time-standard=lst");

                // Periksa apakah respons sukses (status kode 200)
                if (!$responseWeather->successful()) {
                    throw new Exception("Gagal mendapatkan data dari API");
                }

                // Ambil data JSON dari respons
                $weatherData = $responseWeather->json()['properties']['parameter'];

                // radiasi matahari
                foreach ($weatherData["ALLSKY_SFC_SW_DWN"] as $key => $value) {
                    $year = substr($key, 0, 4);
                    $month = substr($key, 4, 2);

                    WeatherSubDistrict::updateOrCreate(
                        [
                            'sub_district_id' => $subDistrict['id'],
                            'month' => $month,
                            'year' => $year,
                        ],
                        [
                            'allsky_sfc_sw_dwn' => $weatherData["ALLSKY_SFC_SW_DWN"][$key] ?? null,
                            'prectotcorr' => $weatherData["PRECTOTCORR"][$key] ?? null,
                            'rh2m' => $weatherData["RH2M"][$key] ?? null,
                            't2m' => $weatherData["T2M"][$key] ?? null,
                            'ws2m' => $weatherData["WS2M"][$key] ?? null,
                        ]
                    );
                }

                // Periksa apakah struktur data sesuai harapan
                if (!isset($weatherData)) {
                    throw new Exception("Struktur respons API tidak sesuai");
                }
            }

            return response()->json(['success' => true, 'message' => 'Data cuaca berhasil disimpan!']);
        } catch (\Exception $e) {
            // Tangani kesalahan dan tampilkan pesan error
            return response()->json([
                'success' => false,
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
