<?php

namespace App\Http\Controllers\Website;

use App\Exports\ParameterVillageExport;
use App\Http\Controllers\Controller;
use App\Models\Village;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ParameterVillageController extends Controller
{
    public function index()
    {
        return view('website.app.parameter-village');
    }

    public function getDataVillage()
    {
        $allDataVillage = Village::select('village.id as village_id', 'village.village', 'village.latitude', 'village.longitude', 'sub_district.sub_district')
            ->join('sub_district', 'sub_district.id', '=', 'village.sub_district_id')
            ->get();

        return response()->json([
            'allVillage' => $allDataVillage
        ]);
    }

    public function excelParameterVillage($latitude, $longitude, $year)
    {
        $village = Village::select('village.village', 'sub_district.sub_district')
            ->join('sub_district', 'sub_district.id', '=', 'village.sub_district_id')
            ->where('village.latitude', $latitude)
            ->where('village.longitude', $longitude)
            ->first();

        $dataParameterVillage = $this->generateParameterVillage($village['sub_district'], $village['village'], $latitude, $longitude, $year);
        return Excel::download(new ParameterVillageExport($dataParameterVillage), 'parameter-cuaca-' . $village['sub_district'] . '-' . $village['village'] . '-tahun-' . $year . '.xlsx');
    }

    public function generateParameterVillage($sub_district, $village, $latitude, $longitude, $year)
    {
        $villageParameter = [];
        $client = new Client();

        $url = "https://power.larc.nasa.gov/api/temporal/monthly/point?start={$year}&end={$year}&latitude={$latitude}&longitude={$longitude}&community=ag&parameters=prectotcorr,T2M,WS2M,RH2M,ALLSKY_SFC_SW_DWN&format=json&header=true&time-standard=lst";

        try {
            // Kirim permintaan GET ke URL
            $response = $client->request('GET', $url);

            $data = json_decode($response->getBody()->getContents(), true);

            $villageParameter[$village] = [
                $village,
                $sub_district,
                $year,
                $data['properties']['parameter'],
            ];
        } catch (\Exception $e) {
            // Tangani kesalahan jika terjadi
            echo "Error untuk latitude {$latitude} dan longitude {$longitude}: " . $e->getMessage() . "\n";
        }

        return $villageParameter;
    }
}
