<?php
namespace Gateway;
use PDO;

Class UserGateway extends Gateway{

    public function getNumberOfUsers() : array
    {
        $query = "SELECT Count(*) FROM Users";

        $this -> co -> executeQuery($query);

        return $this -> co -> getResults();
    }

    public function firstIdUser():int{
        $query = "Select id_user from Users;";
        $this -> co -> executeQuery($query);
        $res = $this -> co -> getResults();
        foreach($res as $r){
            $tab[] = $r["id_user"];
        }
        $id=1;
        while(in_array($id,$tab)){$id=$id+1;}
        return $id;
    }

    public function randomImg():int{
        $query = "SELECT id_img FROM image ORDER BY Random() LIMIT 1";
        $this->co->executeQuery($query);
        $res = $this->co->getResults();
        return $res[0][0];
    }

    public function insertUser(string $pseudo, string $email, string $password, bool $isAdmin, int $imgPrfl) : bool {
        
        $id=$this->firstIdUser();
        $idImg=$this->randomImg();
        
        $query = "
            INSERT INTO Users(id_user,username,email,password,creation,img)
            VALUES (:id, :pseudo, :email, :password, CURRENT_DATE, :imgPrfl);
        ";
        return $this -> co -> executeQuery($query, [
            ":id" => [$id, PDO::PARAM_INT],
            ":pseudo" => [$pseudo, PDO::PARAM_STR],
            ":email" => [$email, PDO::PARAM_STR],
            ":password" => [$password, PDO::PARAM_STR],
            ":imgPrfl" => [$idImg, PDO::PARAM_STR]
        ]);
    }

    public function delete(string $id) : bool{

        // supretion user
        $query='DELETE FROM Users WHERE id_user = :id;';
        return $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR)));
    }

    public function inFavorite(string $username, int $idq):bool{
        $query = 'SELECT count(*) FROM Favorite f JOIN Users u ON f.users = u.id_user WHERE u.username = :user AND f.quote = :id';
        $this->co->executeQuery($query, array(':user'=>array($username, PDO::PARAM_STR),':id'=>array($idq, PDO::PARAM_INT)));
        $result = $this->co->getResults();
        return ($result[0]['count'] >= 1);
    }

    public function addFavorite(string $username, int $id){
        $query = 'INSERT INTO Favorite VALUES ((SELECT id_user FROM Users WHERE username = :username), :id)';
        $this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR), ':id' => array($id,PDO::PARAM_INT)));
        $query = 'UPDATE Quote SET likes = (likes + 1) WHERE id_quote = :id';
        $this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT)));
    }

    public function supFavorite(string $username, int $id){
        $query = 'SELECT id_user FROM Users WHERE username = :username';
        $this->co->executeQuery($query, array(':username' => array($username,PDO::PARAM_STR)));
        $result = $this->co->getResults()[0]['id_user'];

        $query = 'DELETE FROM Favorite WHERE users = :user AND quote = :id;';
        $this->co->executeQuery($query, array(':user' => array($result,PDO::PARAM_INT), ':id' => array($id,PDO::PARAM_INT)));
        $query = 'UPDATE Quote SET likes = (likes - 1) WHERE id_quote = :id';
        $this->co->executeQuery($query, array(':id' => array($id,PDO::PARAM_INT)));
    }


    public function deleteAllCommentaryUser(string $user){
        $query = 'DELETE FROM Commentary WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);';
        $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
    }
    
    
    public function deleteAllFavoriteUser(string $user){
        $query = 'DELETE FROM Favorite WHERE users IN ( SELECT id_user FROM Users WHERE username = :user);';
        $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
    }

    public function deleteUser(string $user){
        $query = 'DELETE FROM Users WHERE username=:user;';
        $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
    }

    // ===================== GET FUNCTION =====================

    public function getFavorite(string $id):array{

        //obtention favoris d'un user
        $query='SELECT * FROM Quote WHERE id_quote IN (SELECT id_quote FROM Favorite f JOIN users u ON u.id_user = f.user_f WHERE u.id_user = :id);';
        $this->co->executeQuery($query,array(':id' => array($id,PDO::PARAM_STR)));
        $result=$this->co->getResults();
        return $result;
    }

    public function getIdUser(string $username):array{
        $query = 'SELECT id_user FROM Users WHERE username=:username';
        $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR)));
        $result = $this->co->getResults();
        return $result;
    }

    // ===================== FIND FUNCTION =====================

    //obtenir les information d'un user
    public function findDataUser(int $id):array{
        $query = 'SELECT u.id_user , u.username , u.email , u.password , i.imgPath , u.creation FROM Users WHERE id_user=:idUser';
        $this->co->executeQuery($query, array(':idUser'=>array($id, PDO::PARAM_STR)));
        $result = $this->co->getResults();
        return $result;
    }

    // obtenir les informations d'un user selon son pseudo
    public function findUsername(string $username):array{
        $query = 'SELECT * FROM Users u Join Image i on i.id_img=u.img WHERE username= :username';
        $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR)));
        return $this->co->getResults();
    }

    public function findEmail(string $email):array{
        $query = 'SELECT * FROM Users WHERE email = :email';
        $this->co->executeQuery($query, array(':email'=>array($email, PDO::PARAM_STR)));
        return $this->co->getResults();
    }


    // ===================== CHECK FUNCTION =====================

    public function IsExisteUsername(string $username): bool {
        $query = 'SELECT COUNT(*) as count FROM Users WHERE username = :username';
        $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
        $results = $this->co->getResults();
        
        return $results[0]['count'] > 0; // retourne true si "count" > 0)
    }

    public function IsExisteEmail(string $email): bool {
        $query = 'SELECT COUNT(*) as count FROM Users WHERE email = :email';
        $this->co->executeQuery($query, array(':email' => array($email, PDO::PARAM_STR)));
        $results = $this->co->getResults();
        
        return $results[0]['count'] > 0; // retourne true si "count" > 0)
    }

    public function getPasswordHash(string $username): ?string {
        $query = 'SELECT password FROM Users WHERE username = :username';
        $this->co->executeQuery($query, array(':username' => array($username, PDO::PARAM_STR)));
        $results = $this->co->getResults();
    
        // Si un utilisateur est trouvé, retourner le hash du mot de passe, sinon null
        return $results ? $results[0]['password'] : null;
    }
    

    // ===================== UPDATE FUNCTION =====================

    //Update Username
    public function updateUsername(string $username, string $newUsername):array{
        //Update le nom du user passé en paramètre
        $queryUpdate = 'UPDATE Users SET username=:newUsername WHERE username=:username';
        $this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newUsername'=> array($newUsername, PDO::PARAM_STR)));

        //Renvoie le nouveau nom du user
        $queryReponse = 'SELECT username FROM Users WHERE username=:idUser';

        $this->co->executeQuery($queryReponse, array(':idUser'=>array($newUsername, PDO::PARAM_STR)));
        return $this->co->getResults();
    }

    //Update Email
    public function updateEmail(string $username, string $newEmail):array{
        //Update le email du user passé en paramètre
        $queryUpdate = 'UPDATE Users SET email=:newEmail WHERE username=:username';
        $this->co->executeQuery($queryUpdate, array(':username'=>array($username, PDO::PARAM_STR), ':newEmail'=> array($newEmail, PDO::PARAM_STR)));

        //Renvoie le nouveau email du user
        $queryReponse = 'SELECT email FROM Users WHERE username=:username';

        $this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR)));
        return $this->co->getResults();
    }


    public function updateImg(string $username,string $newImage):array{
        if($newImage==null){
            $id_image = $this->randomImg();
        }
        else if(is_int((int)$newImage)){
            $id_image=(int)$newImage;
        }
        else{
            $id_image = $this->randomImg();
        }


        //Update l'image du user passé en paramètre
        $query = 'UPDATE Users SET img=:id_image WHERE username=:username';
        $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':id_image'=> array($id_image, PDO::PARAM_INT)));

        //Renvoie la nouvelle image du user
        $queryReponse = 'SELECT img FROM Users WHERE username=:username';
        $this->co->executeQuery($queryReponse, array(':username'=>array($username, PDO::PARAM_STR)));
        return $this->co->getResults();
    }


    public function updatePasswd(string $username, string $newPassWd):void{
        //Update le passwd du user passé en paramètre
        $query = 'UPDATE Users SET password=:newPassWd WHERE username=:username';
        $this->co->executeQuery($query, array(':username'=>array($username, PDO::PARAM_STR), ':newPassWd'=> array($newPassWd, PDO::PARAM_STR)));
    }

    public function emailWithUser(string $user):array{
        $query = 'SELECT email FROM Users WHERE username = :user';
        $this->co->executeQuery($query, array(':user'=>array($user, PDO::PARAM_STR)));
        return $this->co->getResults();
    }
}
?>
