<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

namespace BlackSheepResearch\Component\UserPoints\Site\Problems;

defined('_JEXEC') or die;

use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Image\Image;
use Joomla\CMS\Uri\Uri;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

// Look at https://github.com/picqer/php-barcode-generator 

if ((file_exists(JPATH_SITE . '/libraries/CBLib/CBLib/Core/CBLib.php')) && (file_exists(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php'))) {
    include_once(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php');
}

class Avatar extends ProblemBase {

    protected $avatar = '';

    public function __construct($useAvatarFrom, $userinfo, $height = '', $width = '', $class = '') {
        $db = SQL::getInstance();

        $setheight = ($height != '') ? 'height="' . $height . '"' : '';
        $setwidth = ($width != '') ? 'width="' . $width . '"' : 'width="' . $height . '"';

        if ($width == '') {
            $width = $height;
        }

        $defaultAvatarAUP = Uri::root() . 'components/com_userpoints/assets/images/avatars/generic_gravatar_grey.png';

        switch ($useAvatarFrom) {
            case 'gravatar':
                $gravatar_url = 'https://www.gravatar.com/avatar/';
                $gravatar_url .= hash('sha256', strtolower(trim($userinfo->email)));
                // $gravatar_url .= '?d=' . urlencode($defaultAvatarAUP);
                // If default is used, need &amp; instead of ? in next part
                if ($height) {
                    $gravatar_url .= "?s=$height";
                } else {
                    $gravatar_url .= '?s=80';
                }
                $this->avatar = '<img src="' . $gravatar_url . '" alt=""/>';
                break;
            case 'kunena':
                defined("_AUP_KUNENA_PATH") || define('_AUP_KUNENA_PATH', JPATH_ROOT . '/media/kunena');
                defined("_AUP_KUNENA_LIVE_PATH") || define('_AUP_KUNENA_LIVE_PATH', Uri::base(true) . '/media/kunena');
                $this->avatar = _AUP_KUNENA_LIVE_PATH . '/avatars/nophoto.jpg';
                $db->setQuery("SELECT a.*, b.* FROM #__kunena_users as a
				LEFT JOIN #__users as b on b.id=a.userid
				where a.userid=" . $db->quote($userinfo->userid));
                $userProfilKunena = $db->loadObject();
                if ($userProfilKunena && file_exists(_AUP_KUNENA_PATH . '/avatars/' . $userProfilKunena->avatar)) {
                    $this->avatar = _AUP_KUNENA_LIVE_PATH . '/avatars/' . $userProfilKunena->avatar;
                }
                break;
            case 'cb':
                if ((file_exists(JPATH_SITE . '/libraries/CBLib/CBLib/Core/CBLib.php')) && (file_exists(JPATH_ADMINISTRATOR . '/components/com_comprofiler/plugin.foundation.php'))) {
                    $cbUser = \CBuser::getInstance($userinfo->userid, false);
                    if (is_object($cbUser)) {
                        $this->avatar = $cbUser->getField('avatar', null, 'php', 'none', 'list', 0, true)['avatar'] ?? '';
                    }
                }
                break;
            case 'cbe':
                global $mosConfig_lang;
                $q = "SELECT avatar, avatarapproved FROM #__cbe WHERE user_id =" . $db->quote($userinfo->id) . " ";
                $db->setQuery($q);
                $result = $db->loadObject();
                $this->avatar = $result->avatar;
                if (file_exists(JPATH_ROOT . "/components/com_cbe/images/" . $mosConfig_lang)) {
                    $uimagepath = Uri::base(true) . "/components/com_cbe/images/" . $mosConfig_lang . "/";
                } else
                    $uimagepath = Uri::base(true) . "/components/com_cbe/images/english/";
                if ($result->avatarapproved == 0) {
                    $this->avatar = $uimagepath . "pendphoto.jpg";
                } elseif ($result->avatar == '' || $result->avatar == null) {
                    $this->avatar = $uimagepath . "nophoto.jpg";
                } else {
                    $this->avatar = Uri::base(true) . "/images/cbe/" . $this->avatar;
                }
                break;

            case 'jomsocial':
                $q = "SELECT avatar FROM #__community_users WHERE userid =" . $db->quote($userinfo->id) . " ";
                $db->setQuery($q);
                $result = $db->loadResult();
                if (!empty($result)) {
                    $this->avatar = Uri::base(false) . $result;
                } else {
                    $this->avatar = Uri::base(true) . "/components/com_community/assets/default_thumb.jpg";
                }
                break;
            case 'easysocial':
                require_once JPATH_ADMINISTRATOR . '/components/com_easysocial/includes/easysocial.php';
                $esf = ES::user($userinfo->id);
                $this->avatar = $esf->getAvatar('square');
                break;
            case 'easyblog':
                require_once JPATH_ADMINISTRATOR . '/components/com_easyblog/includes/easyblog.php';
                //$config = EB::config();
                $eb = EB::user($userinfo->id);
                $this->avatar = $eb->getAvatar('square');
                break;
            case 'easyprofile':
                $q = "SELECT avatar FROM #__jsn_users WHERE `id`=" . $db->quote($userinfo->id);
                $db->setQuery($q);
                $result = $db->loadResult();
                if (!empty($result)) {
                    $this->avatar = $result;
                } else {
                    $this->avatar = $defaultAvatarAUP;
                }
                break;
            case 'clexus':
                $q = "SELECT picture FROM #__mypms_profiles WHERE `name`=" . $db->quote($userinfo->username);
                $db->setQuery($q);
                $result = $db->loadResult();
                if (!empty($result)) {
                    $this->avatar = $result;
                } else {
                    $this->avatar = $defaultAvatarAUP;
                }
                break;
            case 'K2':
                $q = "SELECT image FROM #__k2_users WHERE userID=" . $db->quote($userinfo->id) . " ";
                $db->setQuery($q);
                $result = $db->loadResult();
                if (!empty($result)) {
                    $this->avatar = Uri::base(true) . "/media/k2/users/" . $result;
                } else {
                    $this->avatar = $defaultAvatarAUP;
                }
                break;
            case 'userpoints':

                if (!defined("_AUP_AVATAR_LIVE_PATH")) {
                    define('_AUP_AVATAR_LIVE_PATH', Uri::base(true) . '/components/com_userpoints/assets/images/avatars/');
                }

                //$usr_avatar = ( $userinfo->avatar!='' ) ? JPATH_COMPONENT . '/assets/images/avatars/' . $userinfo->avatar : JPATH_COMPONENT . '/assets/images/avatars/generic_gravatar_grey.gif' ;
                $usr_avatar = ($userinfo->avatar != '') ? JPATH_ROOT . '/components/com_userpoints/assets/images/avatars/' . $userinfo->avatar : JPATH_ROOT . '/components/com_userpoints/assets/images/avatars' . '/generic_gravatar_grey.gif';
                if (file_exists($usr_avatar)) {
                    $image = new Image($usr_avatar);
                    $this->avatar = $image->createThumbs(array($width . 'x' . $height), Image::CROP_RESIZE, JPATH_ROOT . '/components/com_userpoints' . '/assets/images/avatars/thumbs');
                    $this->avatar = myImage::getLivePathImage($this->avatar);
                } else {
                    $this->avatar = $defaultAvatarAUP;
                }

                break;

            case 'jomWALL':
                // for version 2.5
                $config = ComponentHelper::getParams('com_awdwall');
                $template = $config->get('temp', 'blue');
                $this->avatarintergration = $config->get('avatarintergration', '0');

                $q = "SELECT facebook_id FROM #__jconnector_ids WHERE user_id = " . $db->quote($userId);
                $db->setQuery($q);
                $facebook_id = $db->loadResult();
                if ($facebook_id) {
                    $this->avatar = 'https://graph.facebook.com/' . $facebook_id . '/picture?type=large';
                } else {

                    $q = 'SELECT avatar FROM #__awd_wall_users WHERE user_id = ' . (int) $userId;
                    $db->setQuery($q);
                    $img = $db->loadResult();

                    if ($img == NULL) {
                        $this->avatar = Uri::root() . "components/com_awdwall/images/" . $template . "/" . $template . "51.png";
                    } else {
                        $this->avatar = Uri::root() . "images/wallavatar/" . $userId . "/thumb/tn51" . $img;
                    }
                }

                if ($this->avatarintergration == 1) { // k2
                    if (file_exists(JPATH_SITE . '/components/com_k2/k2.php')) {
                        require_once (JPATH_SITE . '/components/com_k2/helpers/utilities.php');

                        $this->avatar = K2HelperUtilities::getAvatar($userId);
                    }
                } else if ($this->avatarintergration == 2) { // easyblog
                    if (file_exists(JPATH_SITE . '/components/com_easyblog/easyblog.php')) {
                        require_once (JPATH_SITE . '/components/com_easyblog/helpers/helper.php');

                        $blogger = EasyBlogHelper::getTable('Profile', 'Table');
                        $blogger->load($userId);
                        $this->avatar = $blogger->getAvatar();
                    }
                } else if ($this->avatarintergration == 3) { // altauserpoint
                    $_user_info = UserPoints::getUserInfo($referrerid = '', $userId);
                    $com_params = ComponentHelper::getParams('com_userpoints');
                    $useAvatarFrom = $com_params->get('useAvatarFrom', '');
                    $height = 50;
                    $width = 50;
                    $this->avatar = getAvatar($useAvatarFrom, $_user_info, $height, $width);
                    $doc = new DOMDocument();
                    $doc->loadHTML($this->avatar);
                    $imageTags = $doc->getElementsByTagName('img');

                    foreach ($imageTags as $tag) {
                        $this->avatar = $tag->getAttribute('src');
                    }
                }
                break;
            default:
                $this->avatar = '';
        }

        if ($this->avatar) {
            if ($useAvatarFrom != 'gravatar' && $useAvatarFrom != 'jomsocial') {
                $this->avatar = '<img src="' . $this->avatar . '" border="0" alt="" ' . $setheight . $setwidth . ' ' . $class . ' />';
            } elseif ($useAvatarFrom == 'jomsocial') {
                $this->avatar = '<img src="' . $this->avatar . '" border="0" alt="" ' . $setheight . $setwidth . ' />';
            }
        } else {
            $this->avatar = '<img src="' . $defaultAvatarAUP . '" border="0" alt="" ' . $setheight . $setwidth . ' />';
        }
    }

    public function getAvatar() {
        return $this->avatar;
    }
}
