<?php
/**
* @package XenCentral Ad Server
* @author Skydevelop EU
* @copyright Drnoyan & Nalyan LDA, Portugal, EU
* @license http://www.dnf.pt/eula.html
* @link http://www.skydevelop.com
* @revision 97
* @version 2.0.0 beta 3 rev. 3
*/


class XenCentral_AdServer_Model_XenForo_User extends XFCP_XenCentral_AdServer_Model_XenForo_User
{
    const FETCH_USER_CREDITS = 'fetchUserCredits';
    const FETCH_ONLY_ACTIVE = 'fetchOnlyActive';

    public function prepareUserFetchOptions(array $fetchOptions)
    {
        $joinOptions = parent::prepareUserFetchOptions($fetchOptions);

        if (!empty($fetchOptions[self::FETCH_USER_CREDITS])) {
            if (!empty($fetchOptions[self::FETCH_ONLY_ACTIVE])) {
                $join = 'INNER';
            } else {
                $join = 'LEFT';
            }

            $joinOptions['joinTables'] .= '
                ' . $join . ' JOIN xcas_user_data AS xcas_user_data ON xcas_user_data.user_id=user.user_id
            ';
            $joinOptions['selectFields'] .= ', xcas_user_data.ad_credit, xcas_user_data.excluded_campaign_domains';
        }

        return $joinOptions;
    }


    public function getAdServerUserInfo($user_id)
    {
        $users = $this->getAdServerUsers(array($user_id));
        return reset($users);
    }

    public function getAdServerUsers($userIdArray)
    {
        $users = $this->getUsers(array(
            'user_id' => $userIdArray
        ), array(
            self::FETCH_USER_CREDITS => 1,
            self::FETCH_ONLY_ACTIVE => 1,
        ));

        foreach ($users AS &$user) {
            $user = $this->_prepareAdServerUserInfo($user);
        }

        return $users;
    }

    protected function _prepareAdServerUserInfo($user)
    {
        if (!$user) {
            return false;
        }

        if (empty($user['ad_credit'])) {
            $user['ad_credit'] = 0.00;
        }

        if (!empty($user['excluded_campaign_domains'])) {
            $user['excluded_campaign_domains'] = unserialize($user['excluded_campaign_domains']);
        } else {
            $user['excluded_campaign_domains'] = array();
        }

        return $user;
    }

    protected function _getAllCampaignOwners()
    {
        static $allCampaignOwners;

        if (is_null($allCampaignOwners)) {
            $allUsers = $this->getAdServerUsers(0);

            foreach ($allUsers AS $user) {
                $allCampaignOwners[$user['user_id']] = array(
                    'user_id'=>$user['user_id'],
                    'username'=>$user['username'],
                    'ad_credit' => $user['ad_credit'],
                    'excluded_campaign_domains'=>$user['excluded_campaign_domains']
                );
            }
        }

        return $allCampaignOwners;
    }

    public function getActiveCampaignOwner($userIdList, $minCredit = null)
    {
        $users = $this->_getAllCampaignOwners();

        $userIdArray = explode(',', $userIdList);
        shuffle($userIdArray);
        foreach ($userIdArray AS $userId) {
            if (isset($users[$userId])) {
                $user = $users[$userId];
                if (
                    (is_null($minCredit) AND $user['ad_credit'] > 0) // by default any positive credit will work
                    OR !is_null($minCredit) AND $minCredit == 0 // 0 set in options, no charge at all
                    OR ($minCredit > 0 AND $user['ad_credit'] >= $minCredit) // some number specified

                ) {
                    return $user;
                }
            }
        }

        return false;
    }

    public function updateAdServerUserInfo($user)
    {
        if (is_array($user['excluded_campaign_domains'])) {
            $user['excluded_campaign_domains'] = serialize($user['excluded_campaign_domains']);
        }

        $this->_getDb()->query("
            INSERT INTO xcas_user_data (user_id, ad_credit, excluded_campaign_domains)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE
            ad_credit=VALUES(ad_credit),
            excluded_campaign_domains=VALUES(excluded_campaign_domains)
        ", array(
            'user_id' => $user['user_id'],
            'ad_credit' => $user['ad_credit'],
            'excluded_campaign_domains' => $user['excluded_campaign_domains']
        ));
    }

    public function addUserCredit($user_id, $credit)
    {
        $user = $this->getAdServerUserInfo($user_id);
        $user['ad_credit'] += $credit;

        $this->updateAdServerUserInfo($user);
    }

    public function removeUserCredit($user_id, $credit)
    {
        $user = $this->getAdServerUserInfo($user_id);
        $user['ad_credit'] -= $credit;
        if ($user['ad_credit'] < 0) {
            $user['ad_credit'] = 0;
        }

        $this->updateAdServerUserInfo($user);
    }


}