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

class Admin_group extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if ($this->session->userdata('role') !== 'superadmin') {
            show_error('Akses ditolak', 403);
        }
        // ✅ MUAT LIBRARY
        $this->load->library(['form_validation']);
        $this->load->model('Admin_group_model');
        $this->load->helper(['url', 'form']);
    }

    public function index() {
        $data['admins'] = $this->Admin_group_model->get_all();
        $this->load->view('templates/header');
        $this->load->view('templates/sidebar');
        $this->load->view('admin_group/index', $data);
        $this->load->view('templates/footer');
    }

    public function create() {
        $data['unor_list'] = $this->Admin_group_model->get_unor_list();
        $this->load->view('templates/header');
        $this->load->view('templates/sidebar');
        $this->load->view('admin_group/create', $data);
        $this->load->view('templates/footer');
    }

    public function save() {
        $this->form_validation->set_rules('username', 'Username', 'required|is_unique[admin_groups.username]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');
        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
        $this->form_validation->set_rules('role', 'Role', 'required');
        $this->form_validation->set_rules('unor_id', 'OPD/UNOR', 'required');

        if ($this->form_validation->run()) {
            $data = [
                'username' => $this->input->post('username'),
                'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT),
                'nama_lengkap' => $this->input->post('nama_lengkap'),
                'role' => $this->input->post('role'),
                'unor_id' => $this->input->post('unor_id')
            ];

            $this->Admin_group_model->insert($data);
            $this->session->set_flashdata('success', 'Admin berhasil ditambahkan.');
            redirect('admin_group');
        } else {
            $this->create();
        }
    }

    public function edit($id) {
        $admin = $this->Admin_group_model->get_by_id($id);
        if (!$admin || $admin->role === 'superadmin') {
            show_error('Data tidak ditemukan.', 404);
        }

        $this->form_validation->set_rules('username', 'Username', 'trim|required|callback_username_check[' . $id . ']');
        $this->form_validation->set_rules('password', 'Password', 'min_length[6]');
        $this->form_validation->set_rules('nama_lengkap', 'Nama Lengkap', 'required');
        $this->form_validation->set_rules('unor_id', 'OPD', 'required');

        if ($this->form_validation->run() == FALSE) {
            $data['admin'] = $admin;
            $data['unor_list'] = $this->Admin_group_model->get_unor_list();
            $this->load->view('templates/header');
            $this->load->view('templates/sidebar');
            $this->load->view('admin_group/edit', $data);
            $this->load->view('templates/footer');
        } else {
            $data = [
                'username' => $this->input->post('username'),
                'nama_lengkap' => $this->input->post('nama_lengkap'),
                'unor_id' => $this->input->post('unor_id')
            ];

            if (!empty($this->input->post('password'))) {
                $data['password'] = password_hash($this->input->post('password'), PASSWORD_DEFAULT);
            }

            $this->Admin_group_model->update($id, $data);
            $this->session->set_flashdata('success', 'Admin OPD berhasil diupdate.');
            redirect('admin_group');
        }
    }

    public function delete($id) {
        $admin = $this->Admin_group_model->get_by_id($id);
        if ($admin && $admin->role === 'superadmin') {
            $this->session->set_flashdata('error', 'Tidak bisa menghapus Superadmin.');
            redirect('admin_group');
        }

        if ($this->Admin_group_model->delete($id)) {
            $this->session->set_flashdata('success', 'Admin OPD berhasil dihapus.');
        } else {
            $this->session->set_flashdata('error', 'Gagal menghapus admin.');
        }
        redirect('admin_group');
    }

    public function username_check($username, $id) {
        if ($this->Admin_group_model->username_exists($username, $id)) {
            $this->form_validation->set_message('username_check', 'Username sudah digunakan.');
            return FALSE;
        }
        return TRUE;
    }

    // Di dalam class Admin_group
    public function unor_autocomplete() {
        $term = $this->input->get('term');
        if (!$term) {
            echo json_encode([]);
            return;
        }

        $this->db->select('unor_id as id, nama as value');
        $this->db->from('unor');
        $this->db->like('nama', $term, 'both');
        $this->db->order_by('nama', 'ASC');
        $this->db->limit(10);
        $query = $this->db->get();

        $data = [];
        foreach ($query->result() as $row) {
            $data[] = [
                'id' => $row->id,
                'value' => $row->value,
                'label' => $row->value // Tampil di dropdown
            ];
        }

        echo json_encode($data);
    }

}