<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @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\Factory;
use Joomla\CMS\Plugin\CMSPlugin;
use BlackSheepResearch\Component\UserPoints\Site\Utils\Session;
use BlackSheepResearch\Component\UserPoints\Site\Utils\Cookie;

/**
 * UserPoints System Plugin
 *
 * @package		Joomla
 * @subpackage	UserPoints
 * @since 		1.5
 */

class plgSystemUserPoints extends CMSPlugin {

    public function onAfterRender() {
        $app = Factory::getApplication();
        // this function stores the referee if the invited user does not register immediately
        // No need in admin panel
        if ($app->isClient('administrator')) {
            return;
        }
        //Get ?referrer= from URL
        $referrer = $app->input->get('referrer', '', 'username');
        if ($referrer) {
            Session::set('referrerid', $referrer);
        }
        $this->setRaffleCookies($referrer);

        // Get cookie and session data
        // $ref_cookie = '';   // Cookie::get('referrerid');
        $ref_session = Session::get('referrerid');
        return;
        
        // If there is no cookie, session, AND ?referrer=, then guest is self referred.  Skip code
        if ($referrer OR $ref_session) {
            // If there is a ?referrer=, it is the most recent referrer.  Set it into session & cookie
            if ($referrer AND !$ref_cookie AND !$ref_session) {
                // Cookie::set("referrerid", $referrer, $expire);
                // Set session
                Session::set('referrerid', $referrer);
                return;
            } else {
                // If a session is set AND does not match the cookie, Set the session into the cookie.  Session is most recent referrer.
                if ($ref_session AND ($ref_session != $ref_cookie)) {
                    // Cookie::set("referrerid", $ref_session, $expire);
                    return;
                }

                // If No session is set AND a cookie is set, it is an old referral.  Set cookie into a current session
                if (!$ref_session AND $ref_cookie) {
                    // Set session
                    Session::set('referrerid', $ref_cookie);
                    return;
                }
            }
        }
    }

    private function setRaffleCookies (string $referrer) {
        //Get ?draw= from URL
        $draw = Factory::getApplication()->input->getInt('draw', 0);
        $expire = time() + 60 * 60 * 24 * 30; //expires in 30 days
        if ($draw) {
            Cookie::set("draw", $draw, $expire);
            Cookie::set("referredraw", $referrer, $expire);
        }
    }
}
