<?PHP
namespace Classe;

use mysqlDB;
use views\UsersHtml;

class Users
{
    public int $idUser;
    public $username;
    public $password;
    public $lastname;
    public $firstname;
    public $email;
    public $comment;
    public $lastTime;
    public $lastUrl;
    public $lastHost;
    public $valide_au;
    public $numLicence;
    public $idDep;
    public $N;
    public $nomDep;

    private mysqlDB $conn;
    private $id_user;
    private $id_departement;
    private $nom_departement;
    private $last_time;
    private $last_url;
    private $last_host;
    private $num_licence;
    private $locked;

    //Funciton de construction 
    //cette fonction valide le nombre de paramettre passé en argument et redirige vers le bon constructeur
    //Si aucun parametre c'est un appel de la requete SQL donc initialise les variables. 
    //En PHP 8 plus besoin de mettre les variables dans le constructeur il crée automatiquement des variable privé 
    public function __construct()
    {
        $args = func_get_args();
        $numArgs = func_num_args();

        if ($numArgs > 0) {
            if (method_exists($this, $f = '__construct' . $numArgs)) {
                call_user_func_array([$this, $f], $args);
            }
        } else {
            $this->idUser = $this->id_user;
            $this->N = $this->N;
            $this->username = $this->username;
            $this->idDep = $this->id_departement;
            $this->nomDep = $this->nom_departement;
            $this->lastname = $this->lastname;
            $this->firstname = $this->firstname;
            $this->lastTime = $this->last_time;
            $this->lastUrl = $this->last_url;
            $this->lastHost = $this->last_host;
            $this->numLicence = $this->num_licence;
            $this->email = $this->email;
            $this->comment = $this->comment;
            $this->valide_au = $this->valide_au;
            $this->locked = $this->locked;
        }
    }
    public function __construct7($username, $password, $lastname, $firstname, $email, $comment, $last_time, $last_url, $last_host, $valide_au, $num_licence, $locked)
    {

        $this->username = $username;
        $this->password = $password;
        $this->lastname = $lastname;
        $this->firstname = $firstname;
        $this->email = $email;
        $this->comment = $comment;
        $this->lastTime = $last_time;
        $this->lastUrl = $last_url;
        $this->lastHost = $last_host;
        $this->valide_au = $valide_au;
        $this->numLicence = $num_licence;
        $this->locked = $locked;
    }
    public function __construct1($conn)
    {
        $this->conn = $conn;
        $this->username = "";
        $this->password = "";
        $this->lastname = "";
        $this->firstname = "";
        $this->email = "";
        $this->comment = "";
        $this->lastTime = "";
        $this->lastUrl = "";
        $this->lastHost = "";
        $this->valide_au = "";
        $this->numLicence = "";
        $this->locked = null;
        $this->idUser = 0;
    }
    public function __construct2($conn, $idUser)
    {
        $this->idUser = $idUser;
        $this->conn = $conn;
        $sqlUser = "SELECT * FROM users WHERE id=" . $idUser;
        $conn->exec($sqlUser);
        $resultUser = $conn->data;
        foreach ($resultUser as $rowUser) {
            $this->username = $rowUser['username'];
            $this->password = $rowUser['password'];
            $this->lastname = $rowUser['nom'] ?? '';           // nom instead of lastname
            $this->firstname = $rowUser['prenom'] ?? '';       // prenom instead of firstname
            $this->email = $rowUser['email'];
            $this->comment = $rowUser['description'] ?? '';    // description instead of comment
            $this->lastTime = $rowUser['derniere_connexion'] ?? ''; // derniere_connexion instead of last_time
            $this->lastUrl = '';                               // Not in new schema
            $this->lastHost = '';                              // Not in new schema
            $this->valide_au = '';                             // Not in new schema
            $this->numLicence = '';                            // Not in new schema
            $this->locked = !$rowUser['actif'];               // actif instead of locked (inverted logic)
            $this->idUser = $rowUser['id'];                    // id instead of id_user
        }
    }
    public function afficherListeUtilisateur()
    {

        $conn = $this->conn;
        extract($_REQUEST, EXTR_PREFIX_ALL | EXTR_REFS, 'v');
        $_POST[] = "";
        $_GET[] = "";
        $get[] = "";
        $get["page"] = "user";

        // Query with role information from the new schema
        $sql = "SELECT u.id, u.username, u.nom, u.prenom, u.email, u.telephone, 
                       u.derniere_connexion, u.actif, u.description, u.date_creation,
                       r.nom_role, r.description as role_description
                FROM users u
                LEFT JOIN roles r ON u.role_id = r.id
                ORDER BY u.username ";

        $conn->exec($sql);
        $result = $conn->data;
        
        // Include the Roles class to get role information
        $roleClass = new Roles($conn);

        UsersHtml::afficherListeUtilisateur($result, null, $roleClass, $sql);
    }


    public function isAdmin(Users $user)
    {
        $sql = "SELECT COUNT(*) AS N FROM users_roles WHERE id_user=$user->idUser AND id_role=1";
        $this->conn->exec($sql);
        $result = $this->conn->data[0];

        if ($result[0] > 0)
            return 1;
        else
            return 0;
    }

    function isPilote(Users $user)
    {
        $sql = "SELECT COUNT(*) AS N FROM users_roles WHERE id_user=$user->idUser AND (id_role=1 OR id_role=2)";
        $this->conn->exec($sql);
        $result = $this->conn->data[0];

        if ($result[0] > 0)
            return 1;
        else
            return 0;
    }

    function isGestion(Users $user)
    {
        $sql = "SELECT COUNT(*) AS N FROM users_roles WHERE id_user=$user->idUser AND (id_role=1 OR id_role=2 OR id_role=4)";
        $this->conn->exec($sql);
        $result = $this->conn->data[0];

        if ($result[0] > 0)
            return 1;
        else
            return 0;
    }

    public function valideContrat()
    {
        // Since the new schema doesn't have valide_au, return empty string to indicate no contract validation needed
        return '';
    }

    public function setUserDep(string $username): int
    {
        $sql = "SELECT * FROM users WHERE LOWER(username)='" . addslashes($username) . "' AND actif = 1";
        $this->conn->exec($sql);
        $nrows = $this->conn->rows;
        if ($nrows > 0) {
            $rowUser = $this->conn->data[0];
            $this->username = $rowUser['username'];
            $this->password = $rowUser['password'];
            $this->lastname = $rowUser['nom'] ?? '';
            $this->firstname = $rowUser['prenom'] ?? '';
            $this->email = $rowUser['email'];
            $this->comment = $rowUser['description'] ?? '';
            $this->lastTime = $rowUser['derniere_connexion'] ?? '';
            $this->lastUrl = '';
            $this->lastHost = '';
            $this->valide_au = '';
            $this->numLicence = '';
            $this->locked = !$rowUser['actif'];
            $this->idUser = $rowUser['id'];
            $this->idDep = 1; // Default department since new schema doesn't have departments
        }
        return $this->conn->rows;
    }

    function valideLogin($username, $password): array
    {
        $password2 = md5($password);
        $sql2 = 'SELECT * FROM users WHERE LOWER(username)="' . strtolower($username) . '" AND password="' . $password2 . '" AND valide_au IS NULL';
        $this->conn->exec($sql2);

        return $result = $this->conn->data;
    }

    function checkUserIfExist($username): array
    {
        $sql2 = 'SELECT * FROM users WHERE LOWER(username)="' . strtolower($username) . '" ;';
        $this->conn->exec($sql2);

        return $result = $this->conn->data;
    }

    function setUserAccesPage($lastPage, $idUser,  $lastTime, $host)
    {
        // Update derniere_connexion in the new schema (removed last_url and last_host as they don't exist)
        $sql = 'UPDATE users SET derniere_connexion="' . $lastTime . '" WHERE id='.$idUser.';';
        $this->conn->exec($sql);
    }

    /**
     * Récupère les rôles d'un utilisateur avec le nouveau schéma
     * @param int $idUser ID de l'utilisateur
     * @return array Informations sur les rôles de l'utilisateur
     */
    function getUserRoles($idUser)
    {
        $sql = "SELECT u.id, u.username, u.role_id, 
                       r.nom_role as role_name, r.niveau_acces as role_level, r.description as role_description
                FROM users u
                LEFT JOIN roles r ON u.role_id = r.id
                WHERE u.id = $idUser AND u.actif = 1";
        
        $this->conn->exec($sql);
        $result = $this->conn->data;
        
        if (!empty($result)) {
            return [
                [
                    'id_user' => $result[0]['id'],
                    'username' => $result[0]['username'],
                    'role_id' => $result[0]['role_id'],
                    'role_name' => $result[0]['role_name'] ?? 'Visiteur',
                    'role_level' => $result[0]['role_level'] ?? 10,
                    'role_description' => $result[0]['role_description'] ?? 'Utilisateur visiteur'
                ]
            ];
        }
        
        // Rôle par défaut si aucun résultat
        return [
            [
                'id_user' => $idUser,
                'username' => '',
                'role_id' => 1,
                'role_name' => 'Visiteur',
                'role_level' => 10,
                'role_description' => 'Utilisateur visiteur'
            ]
        ];
    }
}
