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

class Dialog_kinerja extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
        $this->load->model('Pegawai_model');
        $this->load->model('DialogKinerja_model');
        $this->load->model('Dashboard_model');
    }

    public function index() {
		$data['role'] = $this->session->userdata('role');
		$data['skpd'] = $this->session->userdata('unor_id');

		if ($data['role'] === 'superadmin') {
            $data['pegawai'] = $this->Pegawai_model->get_all();
        } elseif ($data['role'] === 'admin_opd') {
            $unor_id = $this->session->userdata('unor_id');
            if (empty($unor_id)) {
                $this->session->set_flashdata('error', 'Data OPD tidak ditemukan.');
                redirect('auth/logout');
            }
           $unor_ids = $this->Pegawai_model->get_all_child_unor_ids($unor_id);
            // Ambil pegawai berdasarkan daftar unor_id
            $data['pegawai'] = $this->Pegawai_model->get_by_unor_ids($unor_ids);
        } else {
            $data['pegawai'] = $this->Pegawai_model->get_all();
        }

		// --- TAMBAHKAN LOGIKA INI ---
		// 1. Ambil semua data indikator dari tabel database
		$all_data = $this->db->get('dialog_kinerja_data')->result();
		$data['all_indikator_data'] = $all_data;

		// 2. Ambil daftar RHK unik (untuk looping luar)
		// grouping berdasarkan rhk_id agar satu RHK hanya muncul satu kali sebagai header
		$this->db->select('rhk_id, rhk_atasan_id'); // sesuaikan kolom yang ingin ditampilkan
		$this->db->group_by('rhk_id');
		$data['daftar_rhk_atasan'] = $this->db->get('dialog_kinerja_data')->result();
		
		// Pastikan variabel lain yang dibutuhkan view ada
		$data['level'] = $this->session->userdata('level'); // contoh
		$data['daftar_bawahan'] = $data['pegawai']; // contoh jika bawahan diambil dari daftar pegawai
		// ----------------------------

		$this->load->view('templates/header');
		$this->load->view('templates/sidebar');
		$this->load->view('dialog_kinerja/index', $data);
		$this->load->view('templates/footer');
	}

    public function pilih($pegawai_id) {
        redirect("dialog_kinerja/template/{$pegawai_id}/1");
    }

    public function template($pegawai_id, $template = 1) {
        if ($template < 1 || $template > 5) show_404();

        $data['pegawai'] = $this->DialogKinerja_model->get_pegawai_with_unor($pegawai_id);
        if (!$data['pegawai']) show_404();

        // Dapatkan level kepemimpinan
        $data['level'] = $this->Dashboard_model->get_pimpinan_level($pegawai_id);
        
        // Dapatkan daftar bawahan (jika leader)
        $data['daftar_bawahan'] = [];
        if ($data['level']) {
            $data['daftar_bawahan'] = $this->Dashboard_model->get_bawahan_for_select($pegawai_id);
        }

        $data['pegawai_id'] = $pegawai_id;
        $data['template'] = $template;
        $data['form_data'] = $this->DialogKinerja_model->get_template_data($pegawai_id, $template);

        // Ambil RHK & ekspektasi dari atasan
        $data['rhk_dari_atasan'] = [];
        $data['akhlak_dari_atasan'] = [];
        if ($template == 1) {
            $data['rhk_dari_atasan'] = $this->DialogKinerja_model->get_rhk_from_atasan($pegawai_id);
            $data['akhlak_dari_atasan'] = $this->DialogKinerja_model->get_akhlak_from_atasan($pegawai_id);
        }
        
        
        // template 2
    	if ($template == 2) {
            $level = $data['level'];
            $pegawai_id = $data['pegawai_id'];
        
            // 1. Ambil Data Diri Sendiri (Pimpinan) sebagai baris pertama
            $daftar_tampil = [
                [
                    'id_peg'  => $pegawai_id,
                    'nama'    => $data['pegawai']->nama,
                    'nip'     => $data['pegawai']->nip,
                    'jabatan' => $data['pegawai']->jabatan,
                    'level_posisi' => 'pimpinan'
                ]
            ];
        
            // 2. Ambil Daftar Bawahan (Filter: bawahan_id tidak boleh sama dengan pimpinan_id)
            $this->db->select('p.id_peg, p.nama, p.nip, p.jabatan, pb.level as level_posisi');
            $this->db->from('pimpinan_bawahan pb');
            $this->db->join('pegawai p', 'p.id_peg = pb.bawahan_id');
            $this->db->where('pb.pimpinan_id', $pegawai_id);
            $this->db->where('pb.bawahan_id !=', $pegawai_id); // <-- CEGAH DUPLIKASI DISINI
            $bawahan = $this->db->get()->result_array();
        
            foreach ($bawahan as $b) {
                $daftar_tampil[] = $b;
            }
        
            // 3. Siapkan data matriks untuk View
            $matriks_data = [];
            $no = 1;
        
            foreach ($daftar_tampil as $peg) {
                $id_curr_peg = $peg['id_peg'];
                
                // Ambil data nilai yang sudah tersimpan di database (Idis, I.kin, dll)
                $data_simpanan = $this->DialogKinerja_model->get_template_data($id_curr_peg, 2);
        
                $matriks_data[] = [
                    'no'           => $no++,
                    'id_peg'       => $id_curr_peg,
                    'nama'         => $peg['nama'],
                    'nip'          => $peg['nip'],
                    'jabatan'      => $peg['jabatan'],
                    'level_posisi' => $peg['level_posisi'] ?? 'staf',
                    'indicators'   => [
                        'Idis'   => $data_simpanan["Idis"] ?? '',
                        'I.kin.' => $data_simpanan["I.kin."] ?? '',
                        'I.2.1'  => $data_simpanan["I.2.1"] ?? '',
                        'dst'    => $data_simpanan["dst"] ?? ''
                    ]
                ];
            }
        
            $data['matriks_data'] = $matriks_data;
        }

        $this->load->view('templates/header');
        $this->load->view('templates/sidebar');
        $this->load->view("dialog_kinerja/template_{$template}", $data);
        $this->load->view('templates/footer');
    }

    public function save($pegawai_id, $template) {
        if ($template < 1 || $template > 5) show_404();

    $post_data = $this->input->post();
    
    // Validasi minimal
    if (!isset($post_data['form_level'])) {
        // Bisa redirect error atau set default
        $post_data['form_level'] = ''; 
    }

    $this->DialogKinerja_model->save_template($pegawai_id, $template, $post_data);

        if ($template < 5) {
            redirect("dialog_kinerja/template/{$pegawai_id}/" . ($template + 1));
        } else {
            $this->session->set_flashdata('success', 'Dialog kinerja berhasil disimpan.');
            redirect('dialog_kinerja');
        }
    }

    public function data_list() {
    	$data['all_data'] = $this->db->get('dialog_kinerja_data')->result();
    
    	$this->load->view('templates/header');
    	$this->load->view('templates/sidebar');
    	$this->load->view('dialog_kinerja/data_list', $data);
    	$this->load->view('templates/footer');
    }

	
}
