<?php
class Cuaca_model extends CI_Model {
    public function get_cuaca() {
        $pgtr = $this->db->get('pengaturan')->row();
        $adm4 = !empty($pgtr->kode_bmkg) ? $pgtr->kode_bmkg : '33.15.13.1012';

        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => 'https://api.bmkg.go.id/publik/prakiraan-cuaca?adm4='.$adm4,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => 8,
        ]);
        $res = curl_exec($ch);
        // curl_close($ch); <-- removed, deprecated since PHP 8.5
        if (!$res) return null;

        $data   = json_decode($res, true);
        $lokasi = $data['data'][0]['lokasi']      ?? [];
        $cuaca  = $data['data'][0]['cuaca'][0][0] ?? [];

        return [
            'kelurahan'  => $lokasi['desa']        ?? '-',
            'kecamatan'  => $lokasi['kecamatan']   ?? '-',
            'suhu'       => $cuaca['t']             ?? '-',
            'cuaca'      => $cuaca['weather_desc']  ?? '-',
            'kode_cuaca' => $cuaca['weather']       ?? 1,
            'kelembapan' => $cuaca['hu']            ?? '-',
            'angin'      => $cuaca['ws']            ?? '-',
        ];
    }
}