<?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\Controllers;

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

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Component\ComponentHelper;
use BlackSheepResearch\Component\UserPoints\Site\UserController;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Utils\Session;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Coupon;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

/**
 * @package UserPoints
 */
class AccountControl extends UserController {

    /**
     * Custom Constructor
     */
    public function __construct() {
        parent::__construct();
    }

public function display($cachable = false, $urlparams = false) {
    $com_params = ComponentHelper::getParams('com_userpoints');
    $model = $this->getModel('userpoint');
    $view = $this->getView('account', 'html');
    // current user
    $user = UserPoints::getUser();
    // profil request
    $userid = Factory::getApplication()->input->get('userid', '', 'string');
    if (!$user->id && !$com_params->get('allowGuestUserViewProfil', 1)) {
        $msg = Text::_('AUP_ALERT_NOT_AUTH');
        $this->redirect('/index.php', $msg);
    }
    // check referre ID
    if (!$userid) {
        $referrerid = $model->_checkUser();
    } else {
        $referrerid = $userid;
    }
    // Rule Profile View
    if ($referrerid != Session::get('referrerid')) {
        $keyreference = UserPoints::buildKeyreference('sysplgup_profile_view', $user->id);
        $username = ( $user->username ) ? $user->username : Text::_('AUP_GUEST');
        $datareference = Text::_('AUP_PROFILE_VIEW_REFERENCE') . ' ' . $username;
        UserPoints::userpoints('sysplgup_profile_view', $referrerid, 0, $keyreference, $datareference);
    }
    // End rule Profile View

    // Get the parameters of the active menu item
    $params = $model->_getParamsAUP();
    $num_item_activities = $params->get('num_item_activities', 10);

    // Get user info
    $_user_info = UserPoints::getUserInfo($referrerid);
    if (empty($_user_info)) {
        return;
    }

    // Get referral info
    $referralname = "";
    if ($_user_info->referraluser) {
        $referralinfo = UserPoints::getUserInfo($_user_info->referraluser);
        $referralname = $referralinfo->username;
    }

    // Get level/rank and medals
    $userrankinfo = UserPoints::getUserRank($referrerid);
    $medalslistuser = UserPoints::getUserMedals($referrerid);

    // Load avatar
    $useAvatarFrom = $com_params->get('useAvatarFrom');
    $height = 100;
    if ($useAvatarFrom == 'userpoints') {
        $lang = Factory::getLanguage();
        $lang->load('com_media', JPATH_ADMINISTRATOR);
    }
    $avatar = getAvatar($useAvatarFrom, $_user_info, $height, $height, 'class=""');

    // Assign all data to viewdata
    $this->viewdata = [
        'params' => $params,
        'cparams' => $com_params,
        'referreid' => $referrerid,
        'currenttotalpoints' => $_user_info->points,
        'lastupdate' => $_user_info->last_update,
        'referraluser' => $_user_info->referraluser,
        'referralname' => $referralname,
        'rowsreferrees' => $model->_get_referrees($referrerid),
        'userid' => $user->id,
        'userrankinfo' => $userrankinfo,
        'medalslistuser' => $medalslistuser,
        'rowslastpoints' => $model->_get_last_points($referrerid, $num_item_activities)[0],
        'pointsearned' => $model->_pointsearned(),
        'totalpoints' => $model->_totalpoints(),
        'mypointsearned' => $model->_mypointsearned($referrerid),
        'mypointsspent' => $model->_mypointsspent($referrerid),
        'mypointsearnedthismonth' => $model->_mypointsearnedthismonth($referrerid),
        'mypointsspentthismonth' => $model->_mypointsspentthismonth($referrerid),
        'mypointsearnedthisday' => $model->_mypointsearnedthisday($referrerid),
        'mypointsspentthisday' => $model->_mypointsspentthisday($referrerid),
        'myname' => $_user_info->name,
        'myusername' => $_user_info->username,
        'avatar' => $avatar,
        'user_info' => $_user_info,
        'useAvatarFrom' => $useAvatarFrom,
        'mycouponscode' => $model->_getMyCouponCode($referrerid),
        'userinfo' => $_user_info
    ];

    // Display
    $view->_display();
}
    public function saveprofile() {

        // Check for request forgeries
        $this->checkToken('request', true);
        $referreid = Factory::getApplication()->input->get('referreid', '', 'username'); // referreid is not an INTeger, string filter is required
        $model = $this->getModel('userpoint');
        $model->_save_profile();
        Factory::getApplication()->input->set('userid', $referreid);

        return $this->display();
    }

    public function downloadactivity() {

        $userid = Factory::getApplication()->input->get('userid', '', 'int');

        $referrerid = UserPoints::getAnyUserReferreID($userid);

        // if (!$referrerid OR $referrerid != Session::get('referrerid')) return;

        $model = $this->getModel('userpoint');
        $lastpoints = $model->_get_last_points($referrerid, 'nolimit');

        $fileName = "completeactivity_" . uniqid(rand(), true) . ".csv";
        $filepath = JPATH_SITE . '/tmp/' . $fileName;

        $handler = fopen($filepath, "a");
        $header = Text::_('AUP_DATE') . ";" . Text::_('AUP_ACTION') . ";" . Text::_('AUP_POINTS') . ";" . Text::_('AUP_EXPIRE') . ";" . Text::_('AUP_DETAIL') . ";" . Text::_('AUP_APPROVED');
        fwrite($handler, $header . "\n");

        $total = count($lastpoints);
        for ($i = 0; $i < $total; $i++) {

            $date_insert = $this->presentDate('date', $lastpoints[$i]->insert_date, Text::_('DATE_FORMAT_LC2'));

            if ($lastpoints[$i]->expire_date == SQL::nulldatetimeSQL()) {
                $date_expire = '';
            } else {
                $date_expire = $this->presentDate('date', $lastpoints[$i]->expire_date, Text::_('DATE_FORMAT_LC'));
            }

            $approved = ( $lastpoints[$i]->approved ) ? Text::_('AUP_APPROVED') : Text::_('AUP_PENDINGAPPROVAL');

            fwrite($handler, $date_insert . ";" . Text::_($lastpoints[$i]->rule_name) . ";" . $lastpoints[$i]->points . ";" . $date_expire . ";" . $lastpoints[$i]->datareference . ";" . $approved . "\n");
        }

        header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
        header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: text/x-comma-separated-values");
        header("Content-Disposition: attachment; filename=$fileName");

        readfile($filepath);

        exit;
    }

    public function coupon () {
        $app = Factory::getApplication();
        $redirecturl = 'index.php?option=com_userpoints&view=account&Itemid=' . $app->input->getInt('Itemid');
        $referrerid = UserPoints::getReferreid();
        if (!$referrerid) {
            $this->redirect($redirecturl, Text::_('AUP_YOUMUSTBELOGGED'));
        }
        $couponcode = $app->input->get('couponcode');
        $coupon = Coupon::withCouponcode($couponcode);
        if (!$coupon->id) {
            $this->redirect($redirecturl, Text::_('AUP_COUPON_IS_NOT_VALID'));
        }
        if ($coupon->hasExpired()) {
            $this->redirect($redirecturl, Text::_('AUP_COUPON_HAS_EXPIRED'));
        }
        if ($coupon->hasBeenUsed()) {
            $this->redirect($redirecturl, Text::_('AUP_THIS_COUPON_WAS_ALREADY_USED'));
        }
        $coupon->redeem($referrerid);
    }

    private function presentDate ($type, $date, $format) : string {
        if ('date' == $type) {
            return date($format, strtotime($date));
        }
    }
}
