<?php

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

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');

use Joomla\CMS\Plugin\CMSPlugin;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\User\UserHelper;
use Joomla\Utilities\IpHelper;
use Joomla\CMS\Component\ComponentHelper;
use BlackSheepResearch\Component\UserPoints\Site\Utils\Session;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsDetails;
use BlackSheepResearch\Component\UserPoints\Site\Problems\PointsUser;
use BlackSheepResearch\Component\UserPoints\Site\Problems\Rule;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;
use BlackSheepResearch\Component\UserPoints\Site\Problems\RaffleData;
use BlackSheepResearch\Component\UserPoints\Site\Problems\RaffleInscription;

class plgUserUp_newregistered extends CMSPlugin {

    protected $app = null;

    public function onUserAfterSave($user, $isnew, $success, $msg) {

        if ($success AND $isnew) {
            $this->app = Factory::getApplication();
            Factory::getLanguage()->load('com_userpoints', JPATH_SITE);

            $referrerid = $this->app->getUserState('com_userpoints.referral', '', 'username');
            $newreferreid = $this->makeNewReffererid($referrerid, $user);
            $this->addNewUser($user, $referrerid, $newreferreid);

            $rule = Rule::withRuleName('sysplgup_newregistered');
            if ($rule->published && $rule->points) {
                $details = $this->addNewUserPoints($newreferreid, $rule);
                $this->newUserNotifications($rule, $user, $newreferreid, $details);
            }

            if ($referrerid) {
                $data = htmlspecialchars($user['name'], ENT_QUOTES, 'UTF-8') . " (" . $user['username'] . ") ";
                $data = sprintf(Text::_('AUP_X_HASJOINEDTHEWEBSITE'), $data);
                $this->sysplgup_invitewithsuccess($referrerid, $data);
            }

            return true;
        }
    }

    private function makeNewReffererid(string $referrerid, $user): string {
        // get params definitions
        $params = ComponentHelper::getParams('com_userpoints');
        $prefixSelfRegister = $params->get('prefix_selfregister', '');
        $prefixReferralRegister = $params->get('prefix_referralregister', '');

        $prefixNewReferreid = ( $referrerid != '' ) ? strtoupper($prefixReferralRegister) : strtoupper($prefixSelfRegister);
        if ($params->get('referralIDtype') == 'r') {
            $newreferreid = strtoupper(uniqid($prefixNewReferreid, true));
        } elseif ($params->get('referralIDtype') == 'u') {
            $newreferreid = str_replace([' ', ',', "'"], '-', $prefixNewReferreid . strtoupper($user['username']));
        }
        return $newreferreid;
    }

    private function addNewUser($user, $referrerid, $newreferreid) {
        $row = new PointsUser();
        // insert this new user into userpoints table
        $row->id = NULL;
        $row->userid = $user['id'];
        $row->referreid = $newreferreid;
        $row->last_update = SQL::datetimeSQL();
        $row->referraluser = $referrerid;
        $row->leveldate = SQL::nulldateSQL();
        $row->published = 1;
        $row->shareinfos = 1;

        /* if (isset($user['profile']) && (count($user['profile'])))
          {
          foreach ($user['profile'] as $k => $v)
          {
          $value = str_replace('"', '', $v);
          $row = $this->checkProfileField($k, $row, $value);
          }
          } */

        $row->save();
    }

    private function addNewUserPoints($newreferreid, $rule) {
        // save new points into userpoints table details
        $detail = new PointsDetails();
        $detail->referreid = $newreferreid;
        $detail->setPointsWithMax($newreferreid, $rule->points);
        $detail->insert_date = SQL::datetimeSQL();
        $detail->expire_date = $rule->rule_expire;
        $detail->status = $rule->autoapproved;
        $detail->rule_id = $rule->plugin_function;
        $detail->approved = $rule->autoapproved;
        $detail->datareference = Text::_('AUP_WELCOME');
        $detail->enabled = 1;
        $detail->save();
        return $detail;
    }

    private function newUserNotifications($rule, $user, $newreferreid, $details) {
        // frontend message
        if ($rule->displaymsg) {
            $tokens = ['{username}', '{name}', '{email}'];
            $substitutes = [$user['username'], $user['name'], $user['email']];
            $msg = str_replace($tokens, $substitutes, $rule->msg);
            if ($msg != '') {
                $this->app->enqueueMessage(str_replace('{points}', UserPoints::getFPoints($rule->points), Text::_($msg)), 'message');
            } else {
                $this->app->enqueueMessage(sprintf(Text::_('AUP_CONGRATULATIONS_PLURAL'), $rule->points), 'message');
            }
        }
        // send notification
        if ($rule->notification) {
            UserPoints::sendnotification($newreferreid, $details, $rule, 1);
        }
    }

    public function onUserAfterDelete($user, $success, $msg) {
        $pointsuser = PointsUser::withUserID($user['id']);
        $pointsuser->deleteWithRelated();
        $pointsuser->removeReferral();
    }

    public function sysplgup_invitewithsuccess($referrerid, $data) {
        $ip = IpHelper::getIp();
        $keyreference = UserPoints::buildKeyreference('sysplgup_invitewithsuccess', $ip);
        UserPoints::userpoints('sysplgup_invitewithsuccess', $referrerid, 0.0, $keyreference, $data);
    }

    public function onUserLogin($user, $options = array()) {
        $this->app = Factory::getApplication();
        $userid = intval(UserHelper::getUserId($user['username']));
        $fulluser = UserPoints::getUser($userid);

        // start the user session for Userpoints
        UserPoints::getReferreid($userid);

        if (0 == $fulluser->block AND $this->app->isClient('site')) {
            // load language component
            $lang = Factory::getLanguage();
            $lang->load('com_userpoints', JPATH_SITE);

            // check raffle subscription to showing a reminder message
            // check first if rule for raffle is enabled
            if (UserPoints::checkRuleEnabled('sysplgup_raffle', 1)
                AND 'stillRegistered' == $this->checkIfCurrentRaffleSubscription($userid)
                AND '' != Text::_('AUP_YOU_ARE_STILL_NOT_REGISTERED_FOR_RAFFLE')) {
                $messageRaffle = sprintf(Text::_('AUP_YOU_ARE_STILL_NOT_REGISTERED_FOR_RAFFLE'), $user['username']);
                $this->app->enqueueMessage($messageRaffle);
            }
        }
        //return true;
    }

    public function onUserLogout($user, $options = array()) {
        //Make sure we're a valid user first
        if ($user['id']) {
            Session::set('referrerid');
        }
        return true;
    }

    private function checkIfCurrentRaffleSubscription($userid) {
        $nextraffle = RaffleData::getNextID();
        if ($nextraffle) {
            // check if already subscription
            return RaffleInscription::countByUserRaffle($userid, $nextraffle) ? 'alreadyRegistered' : 'stillRegistered';
        }
        return 'noRaffleAvailable';
    }
}
