<?php

namespace App\Http\Controllers\Website;

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

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

    public function getDataPhVillage()
    {
        $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 excelParameterPhVillage($latitude, $longitude)
    {
        $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();

        $dataParameterPhVillage = $this->generateParameterPhVillage($village['sub_district'], $village['village'], $latitude, $longitude);

        return Excel::download(new ParameterPhVillageExport($dataParameterPhVillage), 'parameter-ph-tanah-' . $village['sub_district'] . '-' . $village['village'] . '.xlsx');
    }

    public function generateParameterPhVillage($sub_district, $village, $latitude, $longitude)
    {
        $villageParameterPh = [];
        $client = new Client();

        $urlPhH2O = "https://rest.isric.org/soilgrids/v2.0/properties/query?lon={$longitude}&lat={$latitude}&property=phh2o";

        try {
            $responsePhH2O = $client->request('GET', $urlPhH2O);
            $responsePhH2O = $client->request('GET', $urlPhH2O);
            $dataPhH2O = json_decode($responsePhH2O->getBody()->getContents(), true);

            $villageParameterPh[$village] = [
                $village,
                $sub_district,
                $dataPhH2O['properties']['layers'][0]['depths'],
            ];
        } catch (\Exception $e) {
            echo "Error untuk latitude {$latitude} dan longitude {$longitude}: " . $e->getMessage() . "\n";
        }

        return $villageParameterPh;
    }
}
