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

class User_model extends CI_Model {

    const TABLE = 'users';

    public function get_all() {
        return $this->db->order_by('role','ASC')->order_by('name','ASC')->get(self::TABLE)->result();
    }

    public function get($id) {
        return $this->db->get_where(self::TABLE, ['id' => (int)$id])->row();
    }

    public function get_by_username($username) {
        return $this->db->get_where(self::TABLE, ['username' => $username, 'is_active' => 1])->row();
    }

    public function insert($data) {
        $insert = [
            'name'      => $data['name'],
            'username'  => $data['username'],
            'password'  => password_hash($data['password'], PASSWORD_BCRYPT),
            'role'      => $data['role'] ?? 'user',
            'is_active' => 1,
        ];
        $this->db->insert(self::TABLE, $insert);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        $update = [
            'name'      => $data['name'],
            'username'  => $data['username'],
            'role'      => $data['role'] ?? 'user',
            'is_active' => isset($data['is_active']) ? (int)$data['is_active'] : 1,
        ];
        // Hanya update password jika diisi
        if (!empty($data['password'])) {
            $update['password'] = password_hash($data['password'], PASSWORD_BCRYPT);
        }
        $this->db->where('id', (int)$id)->update(self::TABLE, $update);
        return $this->db->affected_rows();
    }

    public function update_last_login($id) {
        $this->db->where('id',(int)$id)->update(self::TABLE,['last_login'=>date('Y-m-d H:i:s')]);
    }

    public function delete($id) {
        // Jangan hapus diri sendiri atau admin terakhir
        $this->db->where('id',(int)$id)->delete(self::TABLE);
        return $this->db->affected_rows();
    }

    public function count_admins() {
        return $this->db->where('role','admin')->where('is_active',1)->count_all_results(self::TABLE);
    }

    public function username_exists($username, $exclude_id = NULL) {
        $this->db->where('username', $username);
        if ($exclude_id) $this->db->where('id !=', (int)$exclude_id);
        return $this->db->count_all_results(self::TABLE) > 0;
    }
}
