<?php

namespace App\Http\Controllers\Website;

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

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

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

        return response()->json([
            'allSubDistrict' => $allSubDistrict,
        ]);
    }

    public function excelParameterPhSubDistrict($latitude, $longitude)
    {
        $subDistrict = SubDistrict::select('sub_district')
            ->where('latitude', $latitude)
            ->where('longitude', $longitude)
            ->first();

        $dataParameterPhSubDistrict = $this->generateParameterPhSubDistrict($subDistrict['sub_district'], $latitude, $longitude);

        return Excel::download(new ParameterPhSubDistrictExport($dataParameterPhSubDistrict), 'parameter-ph-tanah-' . $subDistrict['sub_district'] . '.xlsx');
    }

    public function generateParameterPhSubDistrict($subdistrict, $latitude, $longitude)
    {
        $subDistrictParameterPh = [];
        $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);
            $dataPhH2O = json_decode($responsePhH2O->getBody()->getContents(), true);

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

        return $subDistrictParameterPh;
    }
}
