<?php

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

// no direct access
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use Joomla\CMS\Router\Route;
use Joomla\CMS\Image\Image;
use Joomla\CMS\Uri\Uri;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\WebAssetManager;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Avatar;

function getAvatar($useAvatarFrom, $userinfo, $height = '', $width = '', $class = '') {
    $avatar = new Avatar($useAvatarFrom, $userinfo, $height);
    return $avatar->getAvatar();
    
    
    $db = SQL::getInstance();

    $avatar = '';

    $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';
            }
            $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');
            $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)) {
                $avatar = _AUP_KUNENA_LIVE_PATH . '/avatars/' . $userProfilKunena->avatar;
            }
            break;
        case 'cb':
            $avatar = $defaultAvatarAUP;
            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' );
                $cbUser = CBuser::getInstance($userinfo->userid, false);
                if (is_object($cbUser)) {
                    $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();
            $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) {
                $avatar = $uimagepath . "pendphoto.jpg";
            } elseif ($result->avatar == '' || $result->avatar == null) {
                $avatar = $uimagepath . "nophoto.jpg";
            } else
                $avatar = Uri::base(true) . "/images/cbe/" . $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)) {
                $avatar = Uri::base(false) . $result;
            } else {
                $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);
            $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);
            $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)) {
                $avatar = $result;
            } else {
                $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)) {
                $avatar = $result;
            } else {
                $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)) {
                $avatar = Uri::base(true) . "/media/k2/users/" . $result;
            } else {
                $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);
                $avatar = $image->createThumbs(array($width . 'x' . $height), Image::CROP_RESIZE, JPATH_ROOT . '/components/com_userpoints' . '/assets/images/avatars/thumbs');
                $avatar = myImage::getLivePathImage($avatar);
            } else {
                $avatar = $defaultAvatarAUP;
            }

            break;

        case 'jomWALL':
            // for version 2.5
            $config = ComponentHelper::getParams('com_awdwall');
            $template = $config->get('temp', 'blue');
            $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) {
                $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) {
                    $avatar = Uri::root() . "components/com_awdwall/images/" . $template . "/" . $template . "51.png";
                } else {
                    $avatar = Uri::root() . "images/wallavatar/" . $userId . "/thumb/tn51" . $img;
                }
            }

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

                    $avatar = K2HelperUtilities::getAvatar($userId);
                }
            } else if ($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);
                    $avatar = $blogger->getAvatar();
                }
            } else if ($avatarintergration == 3) { // altauserpoint
                $_user_info = UserPoints::getUserInfo($referrerid = '', $userId);
                $com_params = ComponentHelper::getParams('com_userpoints');
                $useAvatarFrom = $com_params->get('useAvatarFrom', '');
                $height = 50;
                $width = 50;
                $avatar = getAvatar($useAvatarFrom, $_user_info, $height, $width);
                $doc = new DOMDocument();
                $doc->loadHTML($avatar);
                $imageTags = $doc->getElementsByTagName('img');

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

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

    return $avatar;
}

function getProfileLink($profilechoice, $userinfo, $xhtml = true) {

    switch ($profilechoice) {
        case 'ku' :
            $profilLink = Route::_('index.php?option=com_kunena&func=fbprofile&userid=' . $userinfo->userid, $xhtml);
            $menu = 'com_kunena';
            break;
        case 'cb' :
            $profilLink = Route::_('index.php?option=com_comprofiler&task=userProfile&user=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_comprofiler&view=userprofile';
            break;
        case 'cbe' :
            $profilLink = Route::_('index.php?option=com_cbe&task=userProfile&user=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_cbe&task=userProfile';
            break;
        case 'js' :
            $profilLink = Route::_('index.php?option=com_community&view=profile&userid=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_community&view=profile';
            break;
        case 'es' :
            $profilLink = Route::_('index.php?option=com_easysocial&view=profile&id=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_easysocial&view=profile';
            break;
        case 'eb' :
            $profilLink = Route::_('index.php?option=com_easyblog&view=blogger&layout=listings&id=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_easyblog&view=blogger';
            break;
        case 'ep' :
            $profilLink = Route::_('index.php?option=com_jsn&view=profile&id=' . $userinfo->userid, $xhtml);
            $menu = 'index.php?option=com_jsn&view=profile';
            break;
        case 'j!' :
            $profilLink = Route::_('index.php?option=com_users&view=profile', $xhtml);
            $menu = 'index.php?option=com_users&view=profile';
            break;

        case 'jw' :
            if (is_file(JPATH_ROOT . '/components/com_awdwall/helpers/user.php')) {
                include_once JPATH_ROOT . '/components/com_awdwall/helpers/user.php';
                $itemId = AwdwallHelperUser::getComItemId();
                $profilLink = Route::_('index.php?option=com_awdwall&view=awdwall&layout=mywall&wuid=' . $userinfo->userid . '&Itemid=' . $itemId, false);
            } else
                $profilLink = '';
            $menu = '';
            break;

        default :
            // AUP Link Profile
            $profilLink = Route::_('index.php?option=com_userpoints&view=account&userid=' . $userinfo->referreid, $xhtml);
            $menu = 'index.php?option=com_userpoints&view=account';
            break;
    }
    if ($menu != '') {
        $db = SQL::getInstance();
        $lang = Factory::getLanguage();
        $q = "SELECT id FROM #__menu WHERE `link`= {$db->quote($menu)}
        AND `type`='component' AND `published`='1'  AND access='1' AND ( language = {$db->quote($lang->getTag())} OR language='*')";
        $db->setQuery($q);
        $profilLink .= '&Itemid=' . $db->loadResult();
    }

    return $profilLink;
}

function _getIconCategoryRule($category) {
    $icon = ( $category != '' ) ? '<img src="' . Uri::root() . 'components/com_userpoints/assets/images/categories/' . $category . '.gif" alt="" align="absmiddle" />' : '';
    return $icon;
}

function _updateProfileViews($referreid) {
    $db = SQL::getInstance();
    $q = "UPDATE #__alpha_userpoints SET profileviews = profileviews + 1 WHERE `referreid`= {$db->quote($referreid)}";
    $db->setQuery($q);
    $db->execute();
}

function getFormattedPoints($points) {
    return UserPoints::getFormattedPoints($points);
}

class myImage extends Image {

    function __construct() {
        
    }

    public static function getPathImage($avatar) {
        return $avatar[0]->path;
    }

    public static function getLivePathImage($avatar) {
        $path = $avatar[0]->path;
        $livePathAvatar = str_replace('\\', '/', $path);
        $pos = strpos($livePathAvatar, 'components');
        $livePathAvatar = substr_replace($livePathAvatar, Uri::base(), 0, $pos);

        return $livePathAvatar;
    }
}
