<?php
class ToolsController extends BackController {
	public function actionSitemap() {
		$args = array('yiic', 'sitemap');
		$commandPath = Yii::app() -> getBasePath() . DIRECTORY_SEPARATOR . 'commands';

		// Create new console command runner
		$runner = new CConsoleCommandRunner();

		// Adding commands
		$runner -> addCommands($commandPath);

		// If something goes wrong return error
		if($error = $runner -> run ($args)) {
			Yii::app()->user->setFlash("danger", Yii::t("error_code", "Sitemap error code $error"));
		} else {
			Yii::app()->user->setFlash("success", Yii::t("tools", Yii::t("tools", "Sitemap has been generated")));
		}
		$this->redirectBack();
	}

	public function actionClearCache() {
		Yii::app()->cache->flush();
		Yii::app()->user->setFlash("success", Yii::t("tools", "Cache has been cleared"));
		$this->redirectBack();
	}

	public function actionCheckOnSale() {
		$args=array('yiic', 'checkonsale');
		$commandPath=Yii::app() -> getBasePath() . DIRECTORY_SEPARATOR . 'commands';
		$runner=new CConsoleCommandRunner();
		$runner->addCommands($commandPath);
		if($error=$runner->run($args)) {
			Yii::app()->user->setFlash('danger', Yii::t("notification", "An internal error occurred. Please try again later"));
		} else {
			Yii::app()->user->setFlash("success", Yii::t("tools", "All websites that are on sale have been checked"));
		}
		$this->redirectBack();
	}

	public function actionGarbageCollector() {
		$args=array('yiic', 'garbagecollector');
		$commandPath=Yii::app() -> getBasePath() . DIRECTORY_SEPARATOR . 'commands';
		$runner=new CConsoleCommandRunner();
		$runner->addCommands($commandPath);
		if($error=$runner->run($args)) {
			Yii::app()->user->setFlash('danger', Yii::t("notification", "An internal error occurred. Please try again later"));
		} else {
			Yii::app()->user->setFlash("success", Yii::t("tools", "Expired data has been cleared"));
		}
		$this->redirectBack();
	}

	private function redirectBack() {
		$referrer=Yii::app()->request->urlReferrer;
		$url=$referrer ? $referrer : $this->createUrl("admin/site/index");
		$this->redirect($url);
	}
}