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

class User extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model('User_model');
        $this->require_admin();
    }

    public function index() {
        $data['users'] = $this->User_model->get_all();
        $data['title'] = 'Manajemen Akun';
        $this->render('user/index', $data);
    }

    public function create() {
        $data['title']   = 'Tambah Akun';
        $data['usr']     = NULL;
        $data['is_edit'] = FALSE;
        $this->render('user/form', $data);
    }

    public function store() {
        $username = trim($this->input->post('username'));
        $password = $this->input->post('password');

        if (empty($password)) {
            $this->session->set_flashdata('error', 'Password tidak boleh kosong.');
            redirect('user/create');
            return;
        }
        if ($this->User_model->username_exists($username)) {
            $this->session->set_flashdata('error', 'Username sudah digunakan.');
            redirect('user/create');
            return;
        }

        $this->User_model->insert([
            'name'     => $this->input->post('name'),
            'username' => $username,
            'password' => $password,
            'role'     => $this->input->post('role') ?: 'user',
        ]);
        $this->session->set_flashdata('success', 'Akun berhasil ditambahkan.');
        redirect('user');
    }

    public function edit($id) {
        $usr = $this->User_model->get($id);
        if (!$usr) show_404();
        $data['title']   = 'Edit Akun';
        $data['usr']     = $usr;
        $data['is_edit'] = TRUE;
        $this->render('user/form', $data);
    }

    public function update($id) {
        $usr = $this->User_model->get($id);
        if (!$usr) show_404();

        $username = trim($this->input->post('username'));

        // Cek username duplikat (selain diri sendiri)
        if ($this->User_model->username_exists($username, $id)) {
            $this->session->set_flashdata('error', 'Username sudah digunakan akun lain.');
            redirect('user/edit/' . $id);
            return;
        }

        // Jangan turunkan role jika satu-satunya admin
        $new_role = $this->input->post('role') ?: 'user';
        if ($usr->role === 'admin' && $new_role !== 'admin') {
            if ($this->User_model->count_admins() <= 1) {
                $this->session->set_flashdata('error', 'Tidak bisa mengubah role — harus ada minimal 1 admin aktif.');
                redirect('user/edit/' . $id);
                return;
            }
        }

        $this->User_model->update($id, [
            'name'      => $this->input->post('name'),
            'username'  => $username,
            'password'  => $this->input->post('password'), // kosong = tidak ubah
            'role'      => $new_role,
            'is_active' => $this->input->post('is_active') !== NULL ? (int)$this->input->post('is_active') : 1,
        ]);
        $this->session->set_flashdata('success', 'Akun berhasil diperbarui.');
        redirect('user');
    }

    public function delete($id) {
        // Tidak boleh hapus diri sendiri
        if ((int)$id === (int)$this->auth_user->id) {
            $this->session->set_flashdata('error', 'Tidak bisa menghapus akun sendiri.');
            redirect('user');
            return;
        }
        $usr = $this->User_model->get($id);
        if (!$usr) show_404();

        // Tidak boleh hapus satu-satunya admin
        if ($usr->role === 'admin' && $this->User_model->count_admins() <= 1) {
            $this->session->set_flashdata('error', 'Tidak bisa menghapus satu-satunya admin.');
            redirect('user');
            return;
        }

        $this->User_model->delete($id);
        $this->session->set_flashdata('success', 'Akun berhasil dihapus.');
        redirect('user');
    }

    public function reset_password($id) {
        $usr = $this->User_model->get($id);
        if (!$usr) show_404();

        $this->User_model->update($id, [
            'name'      => $usr->name,
            'username'  => $usr->username,
            'password'  => 'password',   // User_model akan hash ini
            'role'      => $usr->role,
            'is_active' => $usr->is_active,
        ]);
        $this->session->set_flashdata('success', 'Password akun "' . $usr->name . '" direset ke "password".');
        redirect('user');
    }
}
