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

class Departemen extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        cek_login();
        $this->load->model('Menu_model', 'menu');
        $this->menu->aksesUser($this->session->userdata('login_session')['role']);

        $this->load->model('Admin_model', 'admin');
        $this->load->library('form_validation');
    }

    public function index()
    {
        $data['title'] = "Departemen";
        $data['departemen'] = $this->admin->get('departemen');
        $this->template->load('templates/dashboard', 'departemen/data', $data);
    }

    private function _validasi()
    {
        $this->form_validation->set_rules('nama_depart', 'Nama departemen', 'required|trim');
    }

    public function add()
    {
        $this->_validasi();

        if ($this->form_validation->run() == false) {
            $data['title'] = "Departemen";
            $this->template->load('templates/dashboard', 'departemen/add', $data);
        } else {
            $input = $this->input->post(null, true);
            $insert = $this->admin->insert('departemen', $input);
            if ($insert) {
                set_pesan('data berhasil disimpan');
                redirect('departemen');
            } else {
                set_pesan('data gagal disimpan', false);
                redirect('departemen/add');
            }
        }
    }

    public function edit($getId)
    {
        $id = encode_php_tags($getId);
        $this->_validasi();

        if ($this->form_validation->run() == false) {
            $data['title'] = "Departemen";
            $data['departemen'] = $this->admin->get('departemen', ['id_depart' => $id]);
            $this->template->load('templates/dashboard', 'departemen/edit', $data);
        } else {
            $input = $this->input->post(null, true);
            $update = $this->admin->update('departemen', 'id_depart', $id, $input);
            if ($update) {
                set_pesan('data berhasil disimpan');
                redirect('departemen');
            } else {
                set_pesan('data gagal disimpan', false);
                redirect('departemen/add');
            }
        }
    }

    public function delete($getId)
    {
        $id = encode_php_tags($getId);

        $dtDepart =$this->admin->get('user', ['id_depart' => $id]);

        if(is_null($dtDepart)) {
            if ($this->admin->delete('departemen', 'id_depart', $id)) {
                set_pesan('data berhasil dihapus.');
            } else {
                set_pesan('data gagal dihapus.', false);
            }
        } else {
            set_pesan('departemen sudah digunakan!', false);
        }
        redirect('departemen');
    }
}
