<?php

class GatewayPlayer
{
    private $con;

    public function __construct($con)
    {
        $this->con = $con;
    }

    public function addPlayer($player)
    {
        $query = "insert into players(id,nickname,hashedPassword) values (:id,:nickname,:hashedPassword);";
        $this->con->executeQuery(
            $query,
            array(
                ':id' => array($player->getId(), PDO::PARAM_INT),
                ':nickname' => array($player->getNickname(), PDO::PARAM_STR),
                ':hashedPassword' => array($player->getHashedPassword(), PDO::PARAM_STR)
            )
        );
    }

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

    public function getPlayerByID(int $id)
    {
        $query = "SELECT * FROM players WHERE id = :id;";
        $this->con->executeQuery($query, array(':id' => array($id, PDO::PARAM_INT)));
        $results = $this->con->getResults();
        if ($results == NULL) {
            return false;
        }
        return new Player($results[0]['id'], $results[0]['nickname'], $results[0]['hashedPassword']);
    }

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

    public function updatePlayer($player)
    {
        $query = "UPDATE players SET nickname = :nickname, hashedPassword = :hashedPassword WHERE id = :id;";
        $this->con->executeQuery(
            $query,
            array(
                ':id' => array($player->getId(), PDO::PARAM_INT),
                ':nickname' => array($player->getNickname(), PDO::PARAM_STR),
                ':hashedPassword' => array($player->getHashedPassword(), PDO::PARAM_STR)
            )
        );
    }

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

    public function verifyPlayer($player)
    {
        $query = "SELECT players.id FROM players WHERE nickname = :nickname AND password = :password";
        $this->con->executeQuery(
            $query,
            array(
                ':nickname' => array($player->getUsername(), PDO::PARAM_STR),
                ':password' => array($player->getHashedPassword(), PDO::PARAM_STR)
            )
        );
        $results = $this->con->getResults();
                
        return $results[0];
    }
}
