<?php

namespace App\Http\Controllers\Website;

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

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

    public function getDataParameterListPhSubDistrict()
    {
        $listPhSubDistrict = PhSubDistrict::select(
            'ph_sub_districts.id as ph_sub_districts_id',
            'ph_sub_districts.meter_0_5',
            'ph_sub_districts.meter_5_15',
            'ph_sub_districts.meter_15_30',
            'ph_sub_districts.meter_30_60',
            'ph_sub_districts.meter_60_100',
            'ph_sub_districts.meter_100_200',
            'sub_district.sub_district'
        )
            ->join('sub_district', 'ph_sub_districts.sub_district_id', '=', 'sub_district.id')
            ->get();

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

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

        // return response()->json(['success' => $subDistrictAll]);
        set_time_limit(300);
        try {
            foreach ($subDistrictAll as $subDistrict) {
                $responsePh = Http::retry(3, 1000)->get("https://rest.isric.org/soilgrids/v2.0/properties/query?lon={$subDistrict['longitude']}&lat={$subDistrict['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 = [
                    'sub_district_id' => $subDistrict['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
                PhSubDistrict::updateOrCreate(
                    ['sub_district_id' => $subDistrict['id']],
                    $phData
                );

                // Periksa apakah struktur data sesuai harapan
                if (!isset($phData)) {
                    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);
        }
    }
}
