<?php
    /* 
    CREATE TABLE users
    (
        username varchar(50) PRIMARY KEY,
        password varchar(255),
        is_admin boolean default FALSE
    );
    */
    class user
    {
        public $username;
        public $admin;
        
        public function user($username, $admin)
        {
            $this->username = $username;
            $this->admin = $admin;
        }
    }

    class databank
    {
        private $connected = false;
        private $con;

        public function connect()
        {
            if(!$this->connected)
            {
                require_once('db_data.php');
                $this->con = new mysqli("localhost", "snuvi", $db_pass, "snuvi");
                if($this->con->connect_error) 
                {
                    echo "no databank connection";
                } 
                else 
                {
                    $this->connected = true;
                }                
            }
        }

        public function disconnect()
        {
            if($this->connected)
            {
                $this->con->close();
                $this->connected = false;
            }
        }
        
        public function isConnected()
        {
            return $this->connected;
        }
        
        public function getUser($username, $password)
        {
            $sql = $this->con->prepare("SELECT * FROM users WHERE username=?");
            if($sql == false)
            {
                echo $this->con->error;
                return null;
            }
            $sql->bind_param('s', $username);
            $sql->execute();
            $result = $sql->get_result();
            $sql->close();
            if($result->num_rows >= 1)
            {
                $r = $result->fetch_object();
                if(password_verify($password, $r->password))
                {
                    $user = new user($r->username, $r->is_admin);
                    return $user;
                }
                return null;
            }
            return null;
        }
        
        public function addUser($username, $password)
        {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            $sql = $this->con->prepare("INSERT INTO users VALUES (?, ?, false);");
            $sql->bind_param('ss', $username, $hash);
            $sql->execute();
            if($sql->errno === 0) 
            {
                $sql->close();
                return true;
            } 
            if(substr($this->con->error, 0, 15) === "Duplicate entry")
            {
                echo "username already exists";
            }
            else
            {
                echo $this->con->error;
                echo "database error";
            }
            $sql->close();
            return false;
        }
    }
?>