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

class Pegawai extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if (!in_array($this->session->userdata('role'), ['superadmin', 'admin_opd'])) {
            show_error('Akses ditolak', 403);
        }
        $this->load->model('Pegawai_model');
        $this->load->helper(['url', 'form']);
        $this->load->library('pagination');
    }

    public function index() {
        $search = $this->input->get('search');
        $unor_filter_name = $this->input->get('unor_id');
        $per_page = $this->input->get('per_page') ?: 25;
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;

        // Validasi per_page
        $allowed_per_page = [25, 50, 100, 500];
        if (!in_array($per_page, $allowed_per_page)) {
            $per_page = 25;
        }

        $data['unor_list'] = $this->Pegawai_model->get_unor_list();
        $data['per_page'] = $per_page;
        $data['allowed_per_page'] = $allowed_per_page;

        if ($this->session->userdata('role') === 'superadmin') {
            if (!empty($unor_filter_name)) {
                $unor_id = $this->Pegawai_model->get_unor_id_by_name($unor_filter_name);
                if ($unor_id) {
                    $unor_ids = $this->Pegawai_model->get_all_child_unor_ids($unor_id);
                    $total_rows = $this->Pegawai_model->count_by_unor_ids($unor_ids, $search);
                    $data['pegawai'] = $this->Pegawai_model->get_by_unor_ids_paginated($unor_ids, $search, $per_page, $page);
                } else {
                    $total_rows = 0;
                    $data['pegawai'] = [];
                }
            } else {
                $total_rows = $this->Pegawai_model->count_all($search);
                $data['pegawai'] = $this->Pegawai_model->get_all_paginated($search, $per_page, $page);
            }
        } 
        elseif ($this->session->userdata('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);
            $total_rows = $this->Pegawai_model->count_by_unor_ids($unor_ids, $search);
            $data['pegawai'] = $this->Pegawai_model->get_by_unor_ids_paginated($unor_ids, $search, $per_page, $page);
        }

        $data['total_data'] = $total_rows;
        $data['total_all'] = $this->Pegawai_model->count_all();

        // Konfigurasi pagination
        $config['base_url'] = base_url('pegawai/index');
        $config['total_rows'] = $total_rows;
        $config['per_page'] = $per_page;
        $config['use_page_numbers'] = TRUE;
        $config['reuse_query_string'] = TRUE;
        $config['full_tag_open'] = '<ul class="pagination">';
        $config['full_tag_close'] = '</ul>';
        $config['first_link'] = 'Awal';
        $config['last_link'] = 'Akhir';
        $config['first_tag_open'] = '<li class="page-item">';
        $config['first_tag_close'] = '</li>';
        $config['prev_link'] = '&laquo';
        $config['prev_tag_open'] = '<li class="page-item">';
        $config['prev_tag_close'] = '</li>';
        $config['next_link'] = '&raquo';
        $config['next_tag_open'] = '<li class="page-item">';
        $config['next_tag_close'] = '</li>';
        $config['last_tag_open'] = '<li class="page-item">';
        $config['last_tag_close'] = '</li>';
        $config['cur_tag_open'] = '<li class="page-item active"><a class="page-link" href="#">';
        $config['cur_tag_close'] = '</a></li>';
        $config['num_tag_open'] = '<li class="page-item">';
        $config['num_tag_close'] = '</li>';
        $config['attributes'] = array('class' => 'page-link');

        $this->pagination->initialize($config);

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

    // === EDIT PROFIL ===
    public function edit($id_peg) {
        $pegawai = $this->Pegawai_model->get_by_id_peg($id_peg);
        if (!$pegawai) {
            show_404();
        }

        // Hanya Superadmin yang bisa edit semua, Admin OPD hanya bisa edit di bawah OPD-nya
        if ($this->session->userdata('role') === 'admin_opd') {
            $unor_id = $this->session->userdata('unor_id');
            $unor_ids = $this->Pegawai_model->get_all_child_unor_ids($unor_id);
            if (!in_array($pegawai->unor_id, $unor_ids)) {
                show_error('Akses ditolak', 403);
            }
        }

        $this->form_validation->set_rules('nama', 'Nama', 'required');
        $this->form_validation->set_rules('nip', 'NIP', 'required|callback_nip_check[' . $id_peg . ']');
        $this->form_validation->set_rules('jabatan', 'Jabatan', 'required');

        if ($this->form_validation->run() == FALSE) {
            $data['pegawai'] = $pegawai;
            $data['unor_list'] = $this->Pegawai_model->get_unor_list();
            $this->load->view('templates/header');
            $this->load->view('templates/sidebar');
            $this->load->view('pegawai/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $data = [
                'nama' => $this->input->post('nama'),
                'nip' => $this->input->post('nip'),
                'jabatan' => $this->input->post('jabatan'),
                'golru' => $this->input->post('golru'),
                'unor_id' => $this->input->post('unor_id')
            ];

            $this->Pegawai_model->update($id_peg, $data);
            $this->session->set_flashdata('success', 'Profil pegawai berhasil diupdate.');
            redirect('pegawai');
        }
    }

    public function nip_check($nip, $id_peg) {
        $existing = $this->Pegawai_model->get_by_nip($nip);
        if ($existing && $existing->id_peg != $id_peg) {
            $this->form_validation->set_message('nip_check', 'NIP sudah digunakan oleh pegawai lain.');
            return FALSE;
        }
        return TRUE;
    }
}