<?php
/**
 * user model

 */

class Member_Model {

    private $db;
    private $table;

    public function __construct() {
        $this->db = Database::getInstance();
        $this->table = DB_PREFIX . 'member';
    }

    public function getMembers($page = 1) {
        if ($page) {
            $perpage_num = Option::get('admin_article_perpage_num');
            $startId = ($page - 1) * $perpage_num;
            $limit = "LIMIT $startId, " . $perpage_num;
        }
        $res = $this->db->query("SELECT * FROM $this->table order by id asc $limit");
        $members = [];
        while ($row = $this->db->fetch_array($res)) {
            $members[] = $row;
        }
        return $members;
    }

    public function getMembersAll() {

        $res = $this->db->query("SELECT * FROM $this->table order by id asc");
        $members = [];
        while ($row = $this->db->fetch_array($res)) {
            $members[] = $row;
        }
        return $members;
    }



    public function updateUser($userData, $uid) {
        $utctimestamp = time();
        $Item = ["update_time=$utctimestamp"];
        foreach ($userData as $key => $data) {
            $Item[] = "$key='$data'";
        }
        $upStr = implode(',', $Item);
        $this->db->query("update $this->table set $upStr where uid=$uid");
    }



    public function add($name) {
        $sql = "insert into $this->table (name) values('{$name}')";
        $this->db->query($sql);
    }
    public function edit($id, $name) {
        $this->db->query("update $this->table set name='{$name}' where id=$id");
    }

    public function del($id) {
        $this->db->query("delete from $this->table where id=$id");

    }



    public function isUserExist($user_name, $uid = '') {
        if (empty($user_name)) {
            return false;
        }
        $subSql = $uid ? 'and uid!=' . $uid : '';
        $data = $this->db->once_fetch_array("SELECT COUNT(*) AS total FROM $this->table WHERE username='$user_name' $subSql");
        return $data['total'] > 0;
    }


    public function getMemberCount() {
        $sql = "SELECT COUNT(*) AS total FROM {$this->table}";
        $res = $this->db->once_fetch_array($sql);
        return $res['total'];
    }



}
