<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pengaturan_model extends CI_Model {

    private $table = 'pengaturan';
    private $id    = 1; // Selalu row ID = 1

    // ================================================================
    // GET
    // ================================================================
    public function get() {
        $this->db->select('p.*');

        // Ketua RT: prioritas dari warga → users, fallback ke kolom manual
        $this->db->select('COALESCE(u_kt.nama_lengkap, p.nama_ketua_rt) AS nama_ketua_rt');
        $this->db->select('COALESCE(w_kt.nik, p.nik_ketua_rt) AS nik_ketua_rt');

        // Sekretaris RT
        $this->db->select('u_sk.nama_lengkap AS nama_sekretaris_rt, w_sk.nik AS nik_sekretaris_rt');

        // Bendahara RT
        $this->db->select('u_bn.nama_lengkap AS nama_bendahara_rt, w_bn.nik AS nik_bendahara_rt');

        $this->db->from($this->table . ' p');

        $this->db->join('warga w_kt', 'w_kt.id = p.ketua_rt_warga_id',      'left');
        $this->db->join('users u_kt', 'u_kt.id = w_kt.user_id',             'left');

        $this->db->join('warga w_sk', 'w_sk.id = p.sekretaris_rt_warga_id', 'left');
        $this->db->join('users u_sk', 'u_sk.id = w_sk.user_id',             'left');

        $this->db->join('warga w_bn', 'w_bn.id = p.bendahara_rt_warga_id',  'left');
        $this->db->join('users u_bn', 'u_bn.id = w_bn.user_id',             'left');

        $this->db->where('p.id', $this->id);
        return $this->db->get()->row();
    }

    // ================================================================
    // SAVE — update row ID = 1 (pengaturan umum)
    // ================================================================
    public function save($data) {
        $allowed = [
            'nama_rt', 'nama_rw', 'nama_kelurahan', 'nama_kecamatan',
            'nama_kota', 'nama_provinsi', 'kode_pos', 'no_telp',
            'alamat_sekretariat', 'logo',
            'ketua_rt_warga_id', 'sekretaris_rt_warga_id', 'bendahara_rt_warga_id',
            'foto_ketua_rt', 'foto_sekretaris_rt', 'foto_bendahara_rt',
            'foto_ketua_rw', 'foto_lurah',
            'nama_ketua_rw', 'nik_ketua_rw',
            'nama_lurah', 'jabatan_lurah', 'nip_lurah',
            'footer_surat',
            'peraturan_rt',
            'kode_bmkg',
            'cuaca_latitude', 'cuaca_longitude', 'cuaca_kota',
            'youtube_api_key',
            'timezone',
            // ── Sebutan jabatan (fleksibel per daerah) ──────────────
            'sebutan_rt',
            'sebutan_rw',
            'sebutan_ketua_rt',
            'sebutan_sekretaris',
            'sebutan_bendahara',
            'sebutan_ketua_rw',
            'sebutan_lurah',
            // ── WAHA WhatsApp API ────────────────────────────────────
            'waha_base_url',
            'waha_api_key',
            'waha_session',
            'waha_enabled',
        ];

        $data = array_intersect_key($data, array_flip($allowed));
        $this->db->where('id', $this->id);
        return $this->db->update($this->table, $data);
    }

    // ================================================================
    // SAVE PERATURAN RT — khusus update kolom peraturan_rt saja
    // ================================================================
    public function save_peraturan($teks) {
        $this->db->where('id', $this->id);
        return $this->db->update($this->table, [
            'peraturan_rt' => $teks,
        ]);
    }

      // ================================================================
    // GENERATE API KEY baru (random 32 hex chars)
    // ================================================================
    public function generate_api_key() {
        $key = bin2hex(random_bytes(16)); // 32 karakter hex
        $this->db->where('id', $this->id);
        $this->db->update($this->table, ['api_key' => $key]);
        return $key;
    }

    // ================================================================
    // SAVE WAHA — khusus update konfigurasi WAHA
    // ================================================================
    public function save_waha($data) {
        $allowed = ['waha_base_url', 'waha_api_key', 'waha_session', 'waha_enabled'];
        $data = array_intersect_key($data, array_flip($allowed));
        $this->db->where('id', $this->id);
        return $this->db->update($this->table, $data);
    }
 

    // ================================================================
    // MASTER JABATAN
    // ================================================================
    public function get_all_jabatan() {
        return $this->db->order_by('urutan', 'ASC')->get('master_jabatan')->result();
    }

    public function get_jabatan_by_id($id) {
        return $this->db->get_where('master_jabatan', ['id' => $id])->row();
    }

    public function insert_jabatan($data) {
        return $this->db->insert('master_jabatan', $data);
    }

    public function update_jabatan($id, $data) {
        return $this->db->where('id', $id)->update('master_jabatan', $data);
    }

    public function delete_jabatan($id) {
        return $this->db->where('id', $id)->delete('master_jabatan');
    }

    // ================================================================
    // STRUKTUR ORGANISASI (Data Pengurus)
    // ================================================================
    public function get_struktur() {
        $this->db->select('so.*, mj.nama_jabatan, mj.kategori, u.nama_lengkap AS nama_warga, w.nik AS nik_warga');
        $this->db->from('struktur_organisasi so');
        $this->db->join('master_jabatan mj', 'mj.id = so.jabatan_id');
        $this->db->join('warga w',           'w.id  = so.warga_id', 'left');
        $this->db->join('users u',           'u.id  = w.user_id',    'left');
        $this->db->order_by('so.urutan', 'ASC');
        return $this->db->get()->result();
    }

    public function save_struktur($data) {
        // Karena ini tabel mapping, biasanya kita truncate/delete dan insert ulang 
        // atau update jika ID ada. Untuk kemudahan, kita pakai update_batch atau manual.
        if (isset($data['id']) && !empty($data['id'])) {
            $id = $data['id'];
            unset($data['id']);
            return $this->db->where('id', $id)->update('struktur_organisasi', $data);
        } else {
            return $this->db->insert('struktur_organisasi', $data);
        }
    }

    public function delete_struktur($id) {
        return $this->db->where('id', $id)->delete('struktur_organisasi');
    }

    // ================================================================
    // WARGA LIST — untuk dropdown pengurus
    // ================================================================
    public function get_warga_list() {
        $sql = "SELECT id, nama_lengkap, nik
                FROM warga
                WHERE status_meninggal = 0
                ORDER BY nama_lengkap ASC";
        return $this->db->query($sql)->result();
    }
}