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

class Users extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('DynamicModel', 'dm');
        $this->load->library('form_validation');

        if (!$this->session->userdata('logged_in')) {
            redirect('auth');
        }
    }

    public function index()
    {

        if($this->session->userdata('role') != 'Admin'){
            show_error('Akses ditolak', 403);
        }

        $data = ["active_menu" => "users"];

        $this->load->view('partials/header', $data);
        $this->load->view('users/layout');
        $this->load->view('partials/footer');
    }

    // =========================
    // DATATABLE USERS + ROLES
    // =========================
    public function get_data()
    {
        $this->db->select('
            users.id,
            users.username,
            users.nama,
            roles.nama_role
        ');
        $this->db->from('users');
        $this->db->join('roles', 'roles.id = users.role_id', 'left');

        $column_order  = ['users.id', 'users.username', 'users.nama', 'roles.nama_role'];
        $column_search = ['users.username', 'users.nama', 'roles.nama_role'];
        $order = ['users.id' => 'DESC'];

        $search_value = $this->input->post('search')['value'] ?? '';

        if (!empty($search_value)) {
            $this->db->group_start();
            foreach ($column_search as $i => $col) {
                if ($i === 0) {
                    $this->db->like($col, $search_value);
                } else {
                    $this->db->or_like($col, $search_value);
                }
            }
            $this->db->group_end();
        }

        if ($this->input->post('order')) {
            $col_index = $this->input->post('order')[0]['column'];
            $dir = $this->input->post('order')[0]['dir'];

            if (isset($column_order[$col_index])) {
                $this->db->order_by($column_order[$col_index], $dir);
            }
        } else {
            $this->db->order_by(key($order), $order[key($order)]);
        }

        if ($this->input->post('length') != -1) {
            $this->db->limit(
                $this->input->post('length'),
                $this->input->post('start')
            );
        }

        $query = $this->db->get();
        $data = $query->result();

        $output = [
            "draw" => intval($this->input->post('draw')),
            "recordsTotal" => $this->db->count_all('users'),
            "recordsFiltered" => $this->_count_filtered($search_value),
            "data" => []
        ];

        foreach ($data as $row) {

            $action = '
                <button class="btn btn-sm btn-warning btn-edit" data-id="'.$row->id.'">Edit</button>
                <button class="btn btn-sm btn-danger btn-delete" data-id="'.$row->id.'">Hapus</button>
            ';

            $output['data'][] = [
                $row->id,
                $row->username,
                $row->nama,
                $row->nama_role,
                $action
            ];
        }

        echo json_encode($output);
    }

    private function _count_filtered($search_value)
    {
        $this->db->from('users');
        $this->db->join('roles', 'roles.id = users.role_id', 'left');

        if (!empty($search_value)) {
            $this->db->group_start();
            $this->db->like('users.username', $search_value);
            $this->db->or_like('users.nama', $search_value);
            $this->db->or_like('roles.nama_role', $search_value);
            $this->db->group_end();
        }

        return $this->db->count_all_results();
    }

    // =========================
    // STORE USER
    // =========================
    public function store()
    {
        $this->form_validation->set_rules('username', 'Username', 'required|is_unique[users.username]');
        $this->form_validation->set_rules('nama', 'Nama', 'required');
        $this->form_validation->set_rules('role_id', 'Role', 'required');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[6]');

        if ($this->form_validation->run() == FALSE) {
            echo json_encode([
                'status' => false,
                'message' => validation_errors()
            ]);
            return;
        }

        $data = [
            'username' => $this->input->post('username'),
            'nama'     => $this->input->post('nama'),
            'role_id'  => $this->input->post('role_id'),
            'password' => password_hash($this->input->post('password'), PASSWORD_DEFAULT)
        ];

        $this->dm->setTable('users')->insert($data);

        log_activity(
            'users',
            'create',
            'Menambahkan user: ' . $data['username'],
            'success'
        );

        echo json_encode([
            'status' => true,
            'message' => 'User berhasil ditambahkan'
        ]);
    }

    // =========================
    // EDIT USER
    // =========================
    public function edit($id)
    {
        $user = $this->db->get_where('users', ['id' => $id])->row();

        if ($user) {
            echo json_encode([
                'status' => true,
                'data' => $user
            ]);
        } else {
            echo json_encode([
                'status' => false,
                'message' => 'User tidak ditemukan'
            ]);
        }
    }

    // =========================
    // UPDATE USER
    // =========================
    public function update()
    {
        $id = $this->input->post('id');

        $this->form_validation->set_rules('username', 'Username', 'required');
        $this->form_validation->set_rules('nama', 'Nama', 'required');
        $this->form_validation->set_rules('role_id', 'Role', 'required');

        if (!empty($this->input->post('password'))) {
            $this->form_validation->set_rules('password', 'Password', 'min_length[6]');
        }

        if ($this->form_validation->run() == FALSE) {
            echo json_encode([
                'status' => false,
                'message' => validation_errors()
            ]);
            return;
        }

        $data = [
            'username' => $this->input->post('username'),
            'nama'     => $this->input->post('nama'),
            'role_id'  => $this->input->post('role_id')
        ];

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

        $this->dm->setTable('users')->update($id, $data);

        log_activity(
            'users',
            'update',
            'Update user ID: ' . $id . ' username: ' . $this->input->post('username'),
            'success'
        );

        echo json_encode([
            'status' => true,
            'message' => 'User berhasil diupdate'
        ]);
    }

    // =========================
    // DELETE USER
    // =========================
    public function delete($id)
    {
        $this->dm->setTable('users')->delete($id);
        
        log_activity(
            'users',
            'delete',
            'Hapus user ID: ' . $id,
            'success'
        );

        echo json_encode([
            'status' => true,
            'message' => 'User berhasil dihapus'
        ]);
    }

    // =========================
    // GET ROLES
    // =========================
    public function get_role()
    {
        $roles = $this->db->get('roles')->result();

        echo json_encode($roles);
    }
}