<?php

namespace App\Http\Controllers\Website;

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

class ParameterListWeatherVillageController extends Controller
{
    public function index()
    {
        $listSubDistrict = SubDistrict::all();

        return view('website.app.parameter-list-weather-village', compact('listSubDistrict'));
    }

    public function getDataParameterListWeatherVillage($years, $subDistrictId)
    {
        $villageBySubDistrictId = Village::select('id', 'sub_district_id', 'village', 'latitude', 'longitude')
            ->where('sub_district_id', $subDistrictId)->get();

        $listWeatherSubDictrict = WeatherVillage::select(
            'weather_villages.id as weather_id',
            'weather_villages.allsky_sfc_sw_dwn',
            'weather_villages.prectotcorr',
            'weather_villages.rh2m',
            'weather_villages.t2m',
            'weather_villages.ws2m',
            'weather_villages.month',
            'weather_villages.year',
            'village.id as village_id',
            'village.sub_district_id as sub_district_id',
            'village.village',
            'village.latitude',
            'village.longitude'
        )
            ->join('village', 'weather_villages.village_id', '=', 'village.id')
            ->where('weather_villages.year', $years)
            ->where('village.sub_district_id', $subDistrictId)
            ->get();

        return response()->json([
            'villageBySubDistrictId' => $villageBySubDistrictId,
            'listWeatherVillageBySubDistrict' => $listWeatherSubDictrict,
        ]);
    }

    public function updateListParameterWeatherVillage($years, $subDistrictId)
    {

        $villageBySubDistrictId = Village::select('id', 'sub_district_id', 'village', 'latitude', 'longitude')
            ->where('sub_district_id', $subDistrictId)->get();

        if (count($villageBySubDistrictId) > 0) {
            set_time_limit(200);
            try {
                foreach ($villageBySubDistrictId as $village) {
                    $responseWeather = Http::get("https://power.larc.nasa.gov/api/temporal/monthly/point?start={$years}&end={$years}&latitude={$village['latitude']}&longitude={$village['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);

                        WeatherVillage::updateOrCreate(
                            [
                                'village_id' => $village['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);
            }
        }
    }
}
