<?php

class GatewayAdministrator
{
    private $con;

    public function __construct()
    {
        global $dns, $user, $pass;
        $this->con = new Connection($dns, $user, $pass);
    }

    public function addAdministrator($administrator)
    {
        $query = "insert into administrators(username,password) values (:username,:password);";
        $this->con->executeQuery(
            $query,
            array(
                ':username' => array($administrator['username'], PDO::PARAM_STR),
                ':password' => array(md5($administrator['password']), PDO::PARAM_STR)
            )
        );
    }

    public function getAdministratorByUsername(string $username)
    {
        $query = "SELECT * FROM administrators WHERE username = :username;";
        $this->con->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
        $results = $this->con->getResults();
        if ($results == NULL) {
            return false;
        }
        return new Administrator($results[0]['id'], $results[0]['username'], $results[0]['hashedPassword']);
    }

    public function getAdministratorByID(int $id)
    {
        $query = "SELECT * FROM administrators WHERE id = :id;";
        $this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
        $results = $this->con->getResults();

        return $results[0];
    }

    public function getAdministrators()
    {
        $query = "SELECT * FROM administrators";
        $this->con->executeQuery($query);
        $results = $this->con->getResults();
                
        return $results;
    }

    public function updateAdministrator($id,$administrator)
    {
        $query = "UPDATE administrators SET username = :username, password = :password WHERE id = :id;";
        $this->con->executeQuery(
            $query,
            array(
                ':id' => array($id, PDO::PARAM_INT),
                ':username' => array($administrator['username'], PDO::PARAM_STR),
                ':password' => array(md5($administrator['password']), PDO::PARAM_STR)
            )
        );
    }

    public function deleteAdministratorByID($id)
    {
        $query = "DELETE FROM administrators WHERE id = :id;";
        $this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
    }

    public function verifyAdministrator($administrator)
    {
        $query = "SELECT administrators.id FROM administrators WHERE username = :username AND password = :password";
        $this->con->executeQuery(
            $query,
            array(
                ':username' => array($administrator['username'], PDO::PARAM_STR),
                ':password' => array(md5($administrator['password']), PDO::PARAM_STR)
            )
        );
        $results = $this->con->getResults();
                
        return $results[0];
    }
}
