<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */
namespace BlackSheepResearch\Component\UserPoints\Site\Models;

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

use Joomla\CMS\Factory;
use Joomla\CMS\MVC\Model\FormModel;
use BlackSheepResearch\Component\UserPoints\Site\UserPoints;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

abstract class UserModel extends FormModel {
    
    protected $app = null;
    
    public function __construct () {
        parent::__construct();
        $this->app = Factory::getApplication();
    }
    
    protected function redirect ($url, $message='', $type = 'info') {
        $this->app->enqueueMessage($message, $type);
        $this->app->redirect($url);
    }
    
    protected function triggerEvent ($eventName, $args) {
        return UserPoints::triggerEvent($eventName, $args);
    }
    
    public function getForm($data = array(), $loadData = true) {
        return false;
    }
    
    public function _checkCurrentMaxPerDay($rule_id, $referrerid, $ip) {
        $db = SQL::getInstance();
        $where[] = "rule_id = {$db->quote($rule_id)}";
        $where[] = "enabled = 1";
        $curdate = SQL::dateSQL();
        $where[] = "`insert_date` LIKE '$curdate%'";
        $where[] = "referreid = {$db->quote($referrerid)}";
        if ('GUEST' == $referrerid) {
            $where[] = "keyreference = {$db->quote($ip)}";
        }
        $allwhere = implode(' AND ', $where);
        $db->setQuery("SELECT COUNT(*) FROM #__alpha_userpoints_details WHERE $allwhere");
        return $db->loadResult();
    }

    public function _checkLastInviteForDelay($rule_id, $referrerid, $ip, $delay) {
        $db = SQL::getInstance();
        $now = SQL::datetimeSQL();
        $sql = "SELECT TIMESTAMPDIFF(SECOND, insert_date, '$now') AS timediff FROM #__alpha_userpoints_details";
        $where[] = "rule_id = '$rule_id'";
        $where[] = "enabled = 1";
        $where[] = "referreid = {$db->quote($referrerid)}";
        if ('GUEST' == $referrerid) {
            $where[] = "keyreference = {$db->quote($ip)}";
        }
        $allwhere = implode(' AND ', $where);
        $sql .= " WHERE $allwhere ORDER BY `insert_date` DESC LIMIT 1";
        $db->setQuery($sql);
        $result = $db->loadResult();
        return is_null($result) ? 1 : (((int) $result < $delay) ? 0 : 1);
    }
        
}
