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

class DialogKinerja_model extends CI_Model {

    public function get_pegawai_with_unor($pegawai_id) {
        $sql = "
            SELECT p.*, u.nama AS unor_nama, u.unor_atasan_id, u.unor_induk_id,
                   u_atasan.nama AS unor_atasan_nama, u_induk.nama AS unor_induk_nama
            FROM pegawai p
            LEFT JOIN unor u ON p.unor_id = u.unor_id
            LEFT JOIN unor u_atasan ON u.unor_atasan_id = u_atasan.unor_id
            LEFT JOIN unor u_induk ON u.unor_induk_id = u_induk.unor_id
            WHERE p.id_peg = ?
        ";
        return $this->db->query($sql, [$pegawai_id])->row();
    }

    public function get_template_data($pegawai_id, $template) {
		// Ambil data asli milik pegawai yang sedang login
		$this->db->select('field_key, field_value');
		$this->db->from('dialog_kinerja_data dkd');
		$this->db->join('dialog_kinerja dk', 'dk.id = dkd.dialog_id');
		$this->db->where('dk.pegawai_id', $pegawai_id);
		$this->db->where('dk.template', $template);
		$query = $this->db->get();

		$data = [];
		foreach ($query->result() as $row) {
			$data[$row->field_key] = $row->field_value;
		}

		// LOGIKA: Ambil RHK Atasan yang mengintervensi pegawai ini
		if ($template == 1) {
			$atasan = $this->db->query("SELECT pimpinan_id FROM pimpinan_bawahan WHERE bawahan_id = ?", [$pegawai_id])->row();
			
			if ($atasan) {
				// Query mencari field_key 'rhk_bawahan_X_Y' yang berisi ID pegawai ini
				// Lalu mengambil teks dari 'rhk_rhk_X'
				$sql_intervensi = "
					SELECT dkd_teks.field_value as teks_rhk, 
						dkd_bawahan.field_key as key_bawahan
					FROM dialog_kinerja_data dkd_bawahan
					JOIN dialog_kinerja dk ON dkd_bawahan.dialog_id = dk.id
					JOIN dialog_kinerja_data dkd_teks ON dkd_teks.dialog_id = dk.id
					WHERE dk.pegawai_id = ? 
					AND dkd_bawahan.field_key LIKE 'rhk_bawahan_%'
					AND dkd_bawahan.field_value LIKE ? 
					AND dkd_teks.field_key = CONCAT('rhk_rhk_', SUBSTRING_INDEX(SUBSTRING_INDEX(dkd_bawahan.field_key, '_', 3), '_', -1))
					ORDER BY dkd_bawahan.id ASC
				";
				
				$search_id = '%"' . $pegawai_id . '"%';
				$results = $this->db->query($sql_intervensi, [$atasan->pimpinan_id, $search_id])->result();
				
				$list_rhk_intervensi = [];
				foreach ($results as $res) {
					$val = $res->teks_rhk;
					$decoded = json_decode($val, true);
					$list_rhk_intervensi[] = is_array($decoded) ? ($decoded[0] ?? '') : $val;
				}

				// Simpan daftar RHK intervensi (termasuk yang duplikat teksnya karena beda indikator)
				$data['raw_rhk_intervensi'] = $list_rhk_intervensi;
			}
		}
		
		return $data;
	}

    public function save_template($pegawai_id, $template, $data) {
        $form_level = $data['form_level'] ?? null;
        unset($data['form_level']);

        $identity_fields = ['nama', 'nip', 'jabatan', 'unit_kerja', 'opd'];
        foreach ($identity_fields as $f) unset($data[$f]);

        $this->db->where(['pegawai_id' => $pegawai_id, 'template' => $template]);
        $existing = $this->db->get('dialog_kinerja')->row();
        $dialog_id = $existing ? $existing->id : null;

        if (!$dialog_id) {
            $this->db->insert('dialog_kinerja', [
                'pegawai_id' => $pegawai_id,
                'template' => $template,
                'status' => 'completed'
            ]);
            $dialog_id = $this->db->insert_id();
        }

        // Hapus data lama agar tidak duplikat (Sesuai kodingan asli Anda)
        // Catatan: Jika ingin cascade lama juga terhapus, kita hapus dulu berdasarkan ID data yang akan dihapus
        $old_data_ids = $this->db->select('id')->where('dialog_id', $dialog_id)->get('dialog_kinerja_data')->result_array();
        if(!empty($old_data_ids)){
            $ids = array_column($old_data_ids, 'id');
            $this->db->where_in('rhk_atasan_id', $ids)->delete('rhk_cascade');
        }
        $this->db->where('dialog_id', $dialog_id)->delete('dialog_kinerja_data');

        foreach ($data as $key => $value) {
            if ($value === '' || $value === null) continue;
            
            // Simpan value asli untuk diproses jika array
            $raw_value = $value;
            if (is_array($value)) $value = json_encode($value);

            $rhk_id = null;
            $rhk_atasan_id = null;

            if (preg_match('/^rhk_rhk_(\d+)$/', $key, $matches)) {
                $rhk_id = (int) $matches[1];
            } 
            elseif (preg_match('/^rhk_atasan_id_(\d+)$/', $key, $matches)) {
                $rhk_id = (int) $matches[1];
                $rhk_atasan_id = (int) $value; 
            }

            $insert_data = [
                'dialog_id'     => $dialog_id,
                'field_key'     => $key,
                'field_value'   => $value,
                'level'         => $form_level,
                'rhk_id'        => $rhk_id,
                'rhk_atasan_id' => $rhk_atasan_id
            ];

            $this->db->insert('dialog_kinerja_data', $insert_data);
            $current_dkd_id = $this->db->insert_id();

            // --- LOGIKA BARU: OTOMATIS MASUK KE rhk_cascade ---
            // Mencocokkan pattern input 'rhk_bawahan_X_Y'
            if (preg_match('/^rhk_bawahan_(\d+)_(\d+)$/', $key, $matches)) {
                $bawahan_ids = is_array($raw_value) ? $raw_value : json_decode($value, true);
                
                if (is_array($bawahan_ids)) {
                    foreach ($bawahan_ids as $bid) {
                        // Simpan ke rhk_cascade
                        // rhk_bawahan_id diisi ID Pegawai
                        // rhk_atasan_id diisi ID Primary Key dari dialog_kinerja_data barusan
                        $this->db->insert('rhk_cascade', [
                            'rhk_bawahan_id' => $bid, 
                            'rhk_atasan_id'  => $current_dkd_id,
                            'bobot'          => 0,
                            'created_at'     => date('Y-m-d H:i:s')
                        ]);
                    }
                }
            }
        }
    }

    /**
     * Fungsi Helper untuk mengisi tabel rhk_cascade
     */
    private function process_rhk_cascade($rhk_bawahan_id, $rhk_atasan_id) {
        // Cek apakah data cascade sudah ada untuk menghindari duplikat
        $this->db->where([
            'rhk_bawahan_id' => $rhk_bawahan_id,
            'rhk_atasan_id'  => $rhk_atasan_id
        ]);
        $exists = $this->db->get('rhk_cascade')->row();

        if (!$exists) {
            $this->db->insert('rhk_cascade', [
                'rhk_bawahan_id' => $rhk_bawahan_id, // ID dari dialog_kinerja_data milik middle
                'rhk_atasan_id'  => $rhk_atasan_id,  // ID referensi RHK milik top leader
                'bobot'          => 0,               // Default bobot
                'created_at'     => date('Y-m-d H:i:s')
            ]);
        }
    }

    public function get_rhk_from_atasan($pegawai_id) {
        $sql = "
            SELECT p.nama AS atasan_nama, p.nip AS atasan_nip, dkd.field_value AS rhk_data
            FROM dialog_kinerja_data dkd
            JOIN dialog_kinerja dk ON dkd.dialog_id = dk.id
            JOIN pegawai p ON dk.pegawai_id = p.id_peg
            WHERE dk.template = 1
            AND JSON_CONTAINS(dkd.field_value, '\"{$pegawai_id}\"', '$.intervensi_rhk')
            AND dkd.field_key = 'intervensi_rhk'
        ";
        return $this->db->query($sql)->result();
    }

    public function get_akhlak_from_atasan($pegawai_id) {
        $sql = "
            SELECT p.nama AS atasan_nama, p.nip AS atasan_nip, dkd.field_value AS akhlak_data
            FROM dialog_kinerja_data dkd
            JOIN dialog_kinerja dk ON dkd.dialog_id = dk.id
            JOIN pegawai p ON dk.pegawai_id = p.id_peg
            WHERE dk.template = 1
            AND JSON_CONTAINS(dkd.field_value, '\"{$pegawai_id}\"', '$.intervensi_akhlak')
            AND dkd.field_key = 'intervensi_akhlak'
        ";
        return $this->db->query($sql)->result();
    }
    
    
    // template 2
	public function get_matriks_pembagian_peran($pegawai_id) {
		// Ambil semua data template 2 milik pegawai ini
		$this->db->select('field_key, field_value');
		$this->db->from('dialog_kinerja_data dkd');
		$this->db->join('dialog_kinerja dk', 'dk.id = dkd.dialog_id');
		$this->db->where('dk.pegawai_id', $pegawai_id);
		$this->db->where('dk.template', 2);
		$query = $this->db->get();

		$raw_data = [];
		foreach ($query->result() as $row) {
			$raw_data[$row->field_key] = $row->field_value;
		}

		// Cari nomor baris maksimal yang ada
		$max_no = 0;
		$indicators = ['Idis', 'I.kin.', 'I.2.1', 'dst'];
		foreach ($raw_data as $key => $value) {
			foreach ($indicators as $ind) {
				// Escape titik di regex
				$escaped_ind = preg_quote($ind, '/');
				if (preg_match('/^' . $escaped_ind . '_(\d+)$/', $key, $matches)) {
					$no = (int)$matches[1];
					if ($no > $max_no) $max_no = $no;
				}
			}
			// Juga cek field identitas
			if (preg_match('/^nama_(\d+)$/', $key, $matches)) {
				$no = (int)$matches[1];
				if ($no > $max_no) $max_no = $no;
			}
		}

		// Jika belum ada data sama sekali, tampilkan minimal 1 baris kosong
		if ($max_no == 0) {
			return [
				[
					'no' => 1,
					'nama' => '',
					'nip' => '',
					'jabatan' => '',
					'indicators' => [
						'Idis' => '',
						'I.kin.' => '',
						'I.2.1' => '',
						'dst' => ''
					]
				]
			];
		}

		// Bangun data berdasarkan nomor urut
		$result = [];
		for ($i = 1; $i <= $max_no; $i++) {
			$result[] = [
				'no' => $i,
				'nama' => $raw_data["nama_{$i}"] ?? '',
				'nip' => $raw_data["nip_{$i}"] ?? '',
				'jabatan' => $raw_data["jabatan_{$i}"] ?? '',
				'indicators' => [
					'Idis' => $raw_data["Idis_{$i}"] ?? '',
					'I.kin.' => $raw_data["I.kin._{$i}"] ?? '',
					'I.2.1' => $raw_data["I.2.1_{$i}"] ?? '',
					'dst' => $raw_data["dst_{$i}"] ?? ''
				]
			];
		}

		return $result;
	}

	public function get_intervened_subordinates($pegawai_id) {
		// Ambil semua dialog_kinerja milik atasan ini (template 1 atau 2)
		$this->db->select('dkd.id as dkd_id');
		$this->db->from('dialog_kinerja_data dkd');
		$this->db->join('dialog_kinerja dk', 'dk.id = dkd.dialog_id');
		$this->db->where('dk.pegawai_id', $pegawai_id);
		// Tidak perlu filter template, karena rhk_cascade bisa merujuk ke mana saja
		$atasan_dkd_ids = $this->db->get()->result_array();

		if (empty($atasan_dkd_ids)) {
			return [];
		}

		$dkd_ids = array_column($atasan_dkd_ids, 'dkd_id');

		// Cari bawahan di rhk_cascade
		$this->db->select('rc.rhk_bawahan_id as id_peg');
		$this->db->from('rhk_cascade rc');
		$this->db->where_in('rc.rhk_atasan_id', $dkd_ids);
		$bawahan_ids = $this->db->get()->result_array();

		if (empty($bawahan_ids)) {
			return [];
		}

		$pegawai_ids = array_unique(array_column($bawahan_ids, 'id_peg'));

		// Ambil data pegawai
		return $this->db->select('id_peg, nama, nip, jabatan')
						->from('pegawai')
						->where_in('id_peg', $pegawai_ids)
						->get()->result_array();
	}
	
}
