<?php

class Brivium_Credits_CacheRebuilder_CreditImport extends XenForo_CacheRebuilder_Abstract
{
	/**
	 * Gets rebuild message.
	 */
	public function getRebuildMessage()
	{
		return new XenForo_Phrase('BRC_import_credits');
	}

	/**
	 * Shows the exit link.
	 */
	public function showExitLink()
	{
		return true;
	}

	/**
	 * Rebuilds the data.
	 *
	 * @see XenForo_CacheRebuilder_Abstract::rebuild()
	 */
	public function rebuild($position = 0, array &$options = array(), &$detailedMessage = '')
	{
		$options['batch'] = isset($options['batch']) ? $options['batch'] : 75;
		$options['batch'] = max(1, $options['batch']);
		
		/* @var $userModel XenForo_Model_User */
		$userModel = XenForo_Model::create('XenForo_Model_User');

		$userIds = $userModel->getUserIdsInRange($position, $options['batch']);
		if (sizeof($userIds) == 0)
		{
			return true;
		}
		
		$inputHandler = new XenForo_Input($options);
		$input = $inputHandler->filter(array(
			'money_type' => XenForo_Input::STRING,
			'remove_trophy_points' => XenForo_Input::UINT,
			'currency_id' => XenForo_Input::UINT,
			'type' => XenForo_Input::STRING
		));
		$field = '';
		if($input['money_type']=='dbbank'){
			$bdBankAddon = XenForo_Model::create('XenForo_Model_AddOn')->getAddOnVersion('bdbank');
			if (!$bdBankAddon) {
				return true;
				//return $this->responseError('[bd] Banking Addon required');
			}
			$field = XenForo_Application::get("options")->bdbank_field;
		}else if($input['money_type']=='trophy_points'){
			$field = 'trophy_points';
		}else{
			return true;
		}
		
		$removeTrophyPoints = $input['remove_trophy_points'];
		$currencyId = $input['currency_id'];
		if($currencyId){
			$currency = XenForo_Application::get('brcCurrencies')->$currencyId;
		}else{
			return true;
			//return $this->responseError(new XenForo_Phrase('BRC_requested_currency_not_found'));
		}
		
		
		XenForo_Db::beginTransaction();

		foreach ($userIds AS $userId)
		{
			$position = $userId;
			/* @var $userDw XenForo_DataWriter_User */
			$userDw = XenForo_DataWriter::create('XenForo_DataWriter_User', XenForo_DataWriter::ERROR_SILENT);
			if ($userDw->setExistingData($userId))
			{
				if (is_null($userDw->get($currency['column'])) || is_null($userDw->get($field))){vdd($field);
					return true;
				}else{
					if($removeTrophyPoints && $input['money_type']=='trophy_points'){
						$userDw->set('trophy_points', 0);
					}
					if($input['type']=='merge'){
						$userDw->set($currency['column'], $userDw->get($currency['column']) + $userDw->get($field));
					}else{
						$userDw->set($currency['column'], $userDw->get($field));
					}
					if($userDw->hasChanges()){
						$userDw->save();
					}
				}
			}
		}

		XenForo_Db::commit();

		$detailedMessage = XenForo_Locale::numberFormat($position);

		return $position;
	}
}