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

class Account extends MY_Controller {

    public function __construct() {
        parent::__construct();
        $this->require_admin(); // Hanya admin
        $this->load->model('User_model');
        $this->load->helper(['url','form']);
    }

    // Daftar semua user
    public function index() {
        $data['users'] = $this->User_model->get_all();
        $data['title'] = 'Manajemen Akun';
        $this->load->view('layouts/main', $data + ['content' => 'account/index']);
    }

    // Form tambah user
    public function create() {
        $data['title'] = 'Tambah Akun';
        $data['user']  = NULL;
        $this->load->view('layouts/main', $data + ['content' => 'account/form']);
    }

    // Simpan user baru
    public function store() {
        $username = trim($this->input->post('username'));

        if ($this->User_model->username_exists($username)) {
            $this->session->set_flashdata('error', 'Username sudah digunakan.');
            redirect('account/create');
            return;
        }

        if (empty($this->input->post('password'))) {
            $this->session->set_flashdata('error', 'Password tidak boleh kosong.');
            redirect('account/create');
            return;
        }

        $this->User_model->insert([
            'name'     => $this->input->post('name'),
            'username' => $username,
            'password' => $this->input->post('password'),
            'role'     => $this->input->post('role') ?: 'user',
        ]);

        $this->session->set_flashdata('success', 'Akun berhasil ditambahkan.');
        redirect('account');
    }

    // Form edit user
    public function edit($id) {
        $user = $this->User_model->get($id);
        if (!$user) show_404();
        $data['title'] = 'Edit Akun';
        $data['user']  = $user;
        $this->load->view('layouts/main', $data + ['content' => 'account/form']);
    }

    // Simpan perubahan
    public function update($id) {
        $username = trim($this->input->post('username'));

        if ($this->User_model->username_exists($username, $id)) {
            $this->session->set_flashdata('error', 'Username sudah digunakan.');
            redirect('account/edit/'.$id);
            return;
        }

        // Cegah hapus admin terakhir jika role diubah
        $user = $this->User_model->get($id);
        $new_role = $this->input->post('role') ?: 'user';
        if ($user->role === 'admin' && $new_role !== 'admin' && $this->User_model->count_admins() <= 1) {
            $this->session->set_flashdata('error', 'Tidak bisa mengubah role. Harus ada minimal 1 admin aktif.');
            redirect('account/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') ?? 1,
        ]);

        $this->session->set_flashdata('success', 'Akun berhasil diperbarui.');
        redirect('account');
    }

    // Hapus user
    public function delete($id) {
        // Cegah hapus diri sendiri
        if ((int)$id === (int)$this->auth_user->id) {
            $this->session->set_flashdata('error', 'Tidak bisa menghapus akun Anda sendiri.');
            redirect('account');
            return;
        }

        // Cegah hapus admin terakhir
        $user = $this->User_model->get($id);
        if ($user && $user->role === 'admin' && $this->User_model->count_admins() <= 1) {
            $this->session->set_flashdata('error', 'Tidak bisa menghapus admin terakhir.');
            redirect('account');
            return;
        }

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

    // Profil diri sendiri (semua role bisa akses ini)
    public function profile() {
        $this->require_login();
        $data['title']    = 'Profil Saya';
        $data['usr']      = $this->auth_user;
        $this->load->view('layouts/main', $data + ['content' => 'account/profile']);
    }

    // Simpan profil diri sendiri
    public function update_profile() {
        $this->require_login();
        $id       = $this->auth_user->id;
        $username = trim($this->input->post('username'));

        if ($this->User_model->username_exists($username, $id)) {
            $this->session->set_flashdata('error', 'Username sudah digunakan.');
            redirect('account/profile');
            return;
        }

        $this->User_model->update($id, [
            'name'     => $this->input->post('name'),
            'username' => $username,
            'password' => $this->input->post('password'),
            'role'     => $this->auth_user->role, // role tidak bisa ubah sendiri
        ]);

        // Update session name
        $this->session->set_userdata('user_name', $this->input->post('name'));
        $this->session->set_userdata('username',  $username);

        $this->session->set_flashdata('success', 'Profil berhasil diperbarui.');
        redirect('account/profile');
    }
}
