<?php
namespace model;

use model\database;


class users {
    
    public static function get_user(string $username) {
        return (new database())->table('users')->where(['username' => $username])->select();
    }
    
    public static function get_user_by_id(int $uid) {
        return (new database())->table('users')->where(['uid' => $uid])->select();
    }
    
    public static function del_user_by_id(int $uid) {
        return (new database())->table('users')->where(['uid' => $uid])->delete();
    }
    
    public static function add_user($username, $password, $sex, $birthday, $id_card, $borrow_num = 15, $type = 0) {
        return (new database())->table('users')->insert([
            'username' => $username,
            'password' => hash('sha256', $GLOBALS['config']['salt'].$password),
            'birthday' => $birthday,
            'sex' => (int)$sex,
            'id_card' => $id_card,
            'borrow_num' => (int)$borrow_num,
            'type' => (int)$type
        ]);
    }
    
    public static function update_user(int $uid, $password, $sex, $birthday, $id_card, $borrow_num, $type) {
        $update = [
            'sex' => (int)$sex,
            'birthday' => $birthday,
            'id_card' => $id_card,
            'borrow_num' => $borrow_num,
            'type' => $type,
        ];
        if (!empty($password)) $update['password'] = hash('sha256', $GLOBALS['config']['salt'].$password);
        return (new database())->table('users')->where(['uid' => $uid])->update($update);
    }
    
    public static function list_users(int $page = 1) {
        $users = (new database())->table('users')->page(20, $page);
        return isset($users[0]['uid']) ? $users : [$users];
    }
    
    public static function count_users() {
        return (new database())->table('users')->count();
    }
    
}
