<?php

namespace App\Http\Controllers\Website;

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

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

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

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

        if (count($villageBySubDistrictId) > 0) {
            set_time_limit(300);
            try {
                foreach ($villageBySubDistrictId as $village) {
                    $responsePh = Http::retry(3, 1000)->get("https://rest.isric.org/soilgrids/v2.0/properties/query?lon={$village['longitude']}&lat={$village['latitude']}&property=phh2o");

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

                    // Ambil data JSON dari respons
                    $phDataAPI = $responsePh->json()['properties']['layers'][0]['depths'];

                    // Inisialisasi array dengan nilai default
                    $phData = [
                        'village_id' => $village['id'],
                        'meter_0_5' => null,
                        'meter_5_15' => null,
                        'meter_15_30' => null,
                        'meter_30_60' => null,
                        'meter_60_100' => null,
                        'meter_100_200' => null,
                    ];

                    // Looping untuk membaca data dari array
                    foreach ($phDataAPI as $value) {
                        $meanValue = ($value['values']['mean'] ?? 55) / 10; // Jika null, gunakan 0
                        switch ($value['label']) {
                            case '0-5cm':
                                $phData['meter_0_5'] = $meanValue;
                                break;
                            case '5-15cm':
                                $phData['meter_5_15'] = $meanValue;
                                break;
                            case '15-30cm':
                                $phData['meter_15_30'] = $meanValue;
                                break;
                            case '30-60cm':
                                $phData['meter_30_60'] = $meanValue;
                                break;
                            case '60-100cm':
                                $phData['meter_60_100'] = $meanValue;
                                break;
                            case '100-200cm':
                                $phData['meter_100_200'] = $meanValue;
                                break;
                        }
                    }

                    // Simpan data ke database
                    PhVillage::updateOrCreate(
                        ['village_id' => $village['id']],
                        $phData
                    );

                    // Periksa apakah struktur data sesuai harapan
                    if (!isset($phData)) {
                        throw new Exception("Struktur respons API tidak sesuai");
                    }
                }
            } catch (\Exception $e) {
                // Tangani kesalahan dan tampilkan pesan error
                return response()->json([
                    'success' => false,
                    'message' => $e->getMessage()
                ], 500);
            }
        }
    }

    public function getDataParameterListPhVillage($subDistrictId)
    {
        $listPhVillage = PhVillage::select(
            'ph_villages.id as phv_id',
            'ph_villages.village_id as phv_village_id',
            'ph_villages.meter_0_5',
            'ph_villages.meter_5_15',
            'ph_villages.meter_15_30',
            'ph_villages.meter_30_60',
            'ph_villages.meter_60_100',
            'ph_villages.meter_100_200',
            'village.id as village_id',
            'village.sub_district_id as sub_district_id',
            'village.village',
        )
            ->join('village', 'ph_villages.village_id', '=', 'village.id')
            ->where('village.sub_district_id', $subDistrictId)
            ->get();

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