<?php
require_once ('Database.php');
require_once ('UserData.php');

class UserDataSet {
    protected $_dbHandle, $_dbInstance;

    public function __construct() {
        $this->_dbInstance = Database::getInstance();
        $this->_dbHandle = $this->_dbInstance->getDbConnection();
    }
    public function checkAccessLevel($username) {
        $sqlQuery = "SELECT ecoUser.userType FROM ecoUser
                        LEFT JOIN ecoUsertypes ON ecoUser.userType = ecoUsertypes.userType
                        WHERE ecoUser.username = ?";
        $statement = $this->_dbHandle->prepare($sqlQuery);
        $statement->bindValue(1, $username);
        $statement->execute();
        return $statement->fetch(PDO::FETCH_ASSOC)['userType'];
    }
    public function fetchAll(): array
    {
        $sqlQuery = 'SELECT * FROM ecoUser;';

        $statement = $this->_dbHandle->prepare($sqlQuery); // prepare a PDO statement
        $statement->execute(); // execute the PDO statement

        $dataSet = [];
        // loop through and read the results of the query and cast
        // them into a matching object
        while ($row = $statement->fetch()) {
            $dataSet[] = new UserData($row);
        }
        return $dataSet;
    }

    /**
     * @param $username
     * @param $password
     * @return array
     */
    public function checkUserCredentials($username, $password): array
    {
        $sqlQuery = 'SELECT * FROM ecoUser WHERE username = ? AND password = ?;';
        $statement = $this->_dbHandle->prepare($sqlQuery);
        $statement->bindParam(1, $username);
        $statement->bindParam(2, $password);
        $statement->execute();
        $dataSet = [];
        while ($row = $statement->fetch()) {
            $dataSet[] = new UserData($row);
        }
        return $dataSet;
    }
    public function fetchUser($username): array
    {
        $sqlQuery = 'SELECT * FROM ecoUser WHERE username = ?';
        $statement = $this->_dbHandle->prepare($sqlQuery);
        $statement->execute([$username]);
        $dataSet = [];
        while ($row = $statement->fetch()) {
            $dataSet[] = new UserData($row);
        }
        return $dataSet;
    }

}