<?php

/**
 * Created by PhpStorm.
 * User: joe
 * Date: 16-9-8
 * Time: 下午4:03
 */
class Users_model extends CI_Model {

    public function __construct() {
        $this->load->database();
    }

    public function get($id=null, $select = null, $where = null, $order = null, $sort = 'ASC') {
        if ($select) $this->db->select($select);
        if ($id) {
            return $this->db->where('id', $id)->get('users')->row_array();
        }
        if ($where) $this->db->where($where);
        if ($order) $this->db->order_by($order, $sort);
        return $this->db->get('users')->result_array();
    }

    public function valid($username, $password = null) {
        if (!$password) {
            return json_encode(['error' => '密码未填写。'], JSON_UNESCAPED_UNICODE);
        }

        $user = $this->db->where('name', $username)->limit(1)->get('users')->row_array();

        if (!$user) {
            return json_encode(['error' => '用户不存在。'], JSON_UNESCAPED_UNICODE);
        } else if ($user['password'] != md5($password)) {
            return json_encode(['error' => '密码不正确。'], JSON_UNESCAPED_UNICODE);
        } else {
            return $user;
        }
    }
}