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

/**
 * Application user CRUD (login table: user).
 */
class User_m extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    public function get_all()
    {
        if ($this->db->table_exists('app_roles') && $this->db->field_exists('role_id', 'user')) {
            $this->db->select('u.*, r.name AS role_name, r.is_superadmin');
            $this->db->from('user u');
            $this->db->join('app_roles r', 'r.id = u.role_id', 'left');
        } else {
            $this->db->select('u.*, NULL AS role_name, 0 AS is_superadmin', false);
            $this->db->from('user u');
        }
        $this->db->order_by('u.id', 'DESC');
        return $this->db->get()->result();
    }

    public function get($id)
    {
        return $this->db->where('id', (int) $id)->get('user')->row();
    }

    public function get_by_username($username, $exclude_id = null)
    {
        $this->db->where('username', $username);
        if ($exclude_id !== null) {
            $this->db->where('id !=', (int) $exclude_id);
        }
        return $this->db->get('user')->row();
    }

    public function create($data)
    {
        $this->db->insert('user', $data);
        return $this->db->insert_id();
    }

    public function update($id, $data)
    {
        return $this->db->where('id', (int) $id)->update('user', $data);
    }

    public function delete($id)
    {
        return $this->db->where('id', (int) $id)->delete('user');
    }

    public function ensure_columns()
    {
        if (!$this->db->field_exists('role_id', 'user')) {
            @$this->db->query('ALTER TABLE `user` ADD COLUMN `role_id` INT(11) UNSIGNED NULL DEFAULT NULL');
        }
        if (!$this->db->field_exists('status', 'user')) {
            @$this->db->query('ALTER TABLE `user` ADD COLUMN `status` TINYINT(1) NOT NULL DEFAULT 1');
        }
        if (!$this->db->field_exists('email', 'user')) {
            @$this->db->query('ALTER TABLE `user` ADD COLUMN `email` VARCHAR(150) NULL DEFAULT NULL');
        }
    }
}
