<?php

require_once '../models/db.php';
require_once '../models/user.php';

class Userlist
{
    /** @var array<User> */
    protected $users;
    /** @var PDO  */
    private $conn;

    /**
     * Userlist constructor.
     * @param string $groupname
     */
    public function __construct($groupname)
    {
        $db = DB::getInstance();
        $this->conn = $db->getConnection();

        $this->users = [];

        // Select all products from DB

        $stmt = $this->conn->prepare('SELECT felhasznalok.shibboleth_id, felhasznalok.nev, felhasznalok.csoport_id FROM felhasznalok INNER JOIN csoportok ON felhasznalok.csoport_id = csoportok.csoport_id WHERE csoportok.nev = :name');
        $stmt->bindParam(':name', $groupname);
        $stmt->execute();

        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $this->users[] = new User($row['shibboleth_id'], $row['nev'], $row['csoport_id']);
        }
    }

    /**
     * GETTERS
     */

    public function getUsers() {
        return $this->users;
    }



    public static function getAllUserlist($user_id){

        $db = DB::getInstance();
        $conn = $db->getConnection();

        if (User::isAdmin($user_id)) {
            $all_group = [];
            $stmt = $conn->prepare('SELECT nev FROM csoportok');
            $stmt->execute();
            $g_names = $stmt->fetchAll(PDO::FETCH_COLUMN);

            foreach ($g_names as $name){
                $stmt = $conn->prepare('SELECT csoportok.nev AS csop_nev, felhasznalok.nev, felhasznalok.shibboleth_id FROM csoportok INNER JOIN felhasznalok ON csoportok.csoport_id = felhasznalok.csoport_id WHERE csoportok.nev = :gname');
                $stmt->bindParam(':gname', $name);
                $stmt->execute();
                $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
                array_push($all_group, $users);
            }
            return $all_group;
        }
    }

    public static function getAllNames($user_id){
        $db = DB::getInstance();
        $conn = $db->getConnection();

        if (User::isAdmin($user_id)) {
            $all_group = [];
            $stmt = $conn->prepare('SELECT nev FROM csoportok');
            $stmt->execute();
            $g_names = $stmt->fetchAll(PDO::FETCH_COLUMN);
            return $g_names;
        }
    }
}