<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminSubscriptions extends pjAdmin
{
	private function __checkEmail($email, $id=NULL)
	{
		$pjSubscriptionModel = pjSubscriptionModel::factory();
		if (isset($id) && (int) $id > 0)
		{
			$pjSubscriptionModel->where('t1.id !=', $id);
		}
		return 0 == $pjSubscriptionModel->where('t1.email', $email)->findCount()->getData();
	}
	
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['email']) || empty($_GET['email']) || !pjValidation::pjActionEmail($_GET['email']))
			{
				die("false");
			}
			
			echo $this->__checkEmail($_GET['email'], @$_GET['id']) ? "true" : "false";
			exit;
		}
		die("false");
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['subscription_create']))
			{
				if (!$this->__checkEmail($_POST['email']))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSubscriptions&action=pjActionIndex&err=ASP05");
				}
				
				$data = array();
				$data['is_subscribed'] = 'T';
				$data['date_subscr'] = ':CURDATE()';
				$id = pjSubscriptionModel::factory(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ASP03';
					if (isset($_POST['i18n']))
					{
						pjMultiLangModel::factory()->saveMultiLang($_POST['i18n'], $id, 'pjSubscription');
					}
				} else {
					$err = 'ASP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSubscriptions&action=pjActionIndex&err=$err");
			} else {
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminSubscriptions.js');
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteSubscription()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['id']) || (int) $_GET['id'] <= 0)
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjSubscriptionModel = pjSubscriptionModel::factory();
			$arr = $pjSubscriptionModel->find($_GET['id'])->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Subscription not found.'));
			}
			if ($pjSubscriptionModel->erase()->getAffectedRows() == 1)
			{
				pjMultiLangModel::factory()->where('model', 'pjSubscription')->where('foreign_id', $_GET['id'])->eraseAll();
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Subscription have been deleted.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 102, 'text' => 'Subscription have not been deleted.'));
		}
		exit;
	}
	
	public function pjActionDeleteSubscriptionBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_POST['record']) || empty($_POST['record']))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjSubscriptionModel = pjSubscriptionModel::factory();
			$arr = $pjSubscriptionModel->whereIn('id', $_POST['record'])->findAll()->getData();
			if (empty($arr))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 101, 'text' => 'Subscription(s) not found.'));
			}
			$pjSubscriptionModel->eraseAll();
			pjMultiLangModel::factory()->where('model', 'pjSubscription')->whereIn('foreign_id', $_POST['record'])->eraseAll();
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Selected subscriptions have been deleted.'));
		}
		exit;
	}
	
	public function pjActionExport()
	{
		$this->checkLogin();
		
		if (isset($_POST['do_export']))
		{
			$arr = pjSubscriptionModel::factory()
				->select('t1.id, t1.email, t1.date_subscr')
				->orderBy('t1.date_subscr DESC')->findAll()->getData();
			foreach($arr as $k => $v)
			{
				$v['date_subscr'] = date($this->option_arr['o_date_format'], strtotime($v['date_subscr']));
				$arr[$k] = $v;
			}
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Subscriptions-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionExportSubscription()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']) && !empty($_POST['record']))
		{
			$arr = pjSubscriptionModel::factory()
				->select('t1.id, t1.email, t1.date_subscr')
				->whereIn('id', $_POST['record'])->findAll()->getData();
			foreach($arr as $k => $v)
			{
				$v['date_subscr'] = date($this->option_arr['o_date_format'], strtotime($v['date_subscr']));
				$arr[$k] = $v;
			}
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Subscriptions-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionToggleSubscription()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (isset($_POST['record']) && !empty($_POST['record']) && isset($_GET['is_subscribed']) && in_array($_GET['is_subscribed'], array('T', 'F')))
			{
				pjSubscriptionModel::factory()->whereIn('id', $_POST['record'])->modifyAll(array('is_subscribed' => $_GET['is_subscribed']));
				pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Selected subscriptions have been modified.'));
			}
			pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
		}
		exit;
	}
	
	public function pjActionGetSubscription()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			$pjSubscriptionModel = pjSubscriptionModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = $pjSubscriptionModel->escapeString($_GET['q']);
				$q = str_replace(array('%', '_'), array('\%', '\_'), trim($q));
				$pjSubscriptionModel
					->where('t1.email LIKE', "%$q%");
			}
			
			if (isset($_GET['is_subscribed']) && !empty($_GET['is_subscribed']) && in_array($_GET['is_subscribed'], array('T', 'F')))
			{
				$pjSubscriptionModel->where('t1.is_subscribed', $_GET['is_subscribed']);
			}

			$column = 't1.date_subscr';
			$direction = 'DESC';
			if (isset($_GET['direction']) && isset($_GET['column']) && in_array(strtoupper($_GET['direction']), array('ASC', 'DESC')))
			{
				$column = $_GET['column'];
				$direction = strtoupper($_GET['direction']);
			}

			$total = $pjSubscriptionModel->findCount()->getData();
			$rowCount = isset($_GET['rowCount']) && (int) $_GET['rowCount'] > 0 ? (int) $_GET['rowCount'] : 10;
			$pages = ceil($total / $rowCount);
			$page = isset($_GET['page']) && (int) $_GET['page'] > 0 ? intval($_GET['page']) : 1;
			$offset = ((int) $page - 1) * $rowCount;
			if ($page > $pages)
			{
				$page = $pages;
			}

			$data = $pjSubscriptionModel
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				$v['date_subscr'] = date($this->option_arr['o_date_format'], strtotime($v['date_subscr']));
				$data[$k] = $v;
			}			
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminSubscriptions.js');
			$this->appendJs('index.php?controller=pjAdmin&action=pjActionMessages', PJ_INSTALL_URL, true);
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveSubscription()
	{
		$this->setAjax(true);
	
		if ($this->isXHR() && $this->isLoged())
		{
			if (!isset($_GET['id']) || (int) $_GET['id'] <= 0 || !isset($_POST['column']) || empty($_POST['column']) || !isset($_POST['value']))
			{
				pjAppController::jsonResponse(array('status' => 'ERR', 'code' => 100, 'text' => 'Missing, empty or invalid parameters.'));
			}
			$pjSubscriptionModel = pjSubscriptionModel::factory();
			if (!in_array($_POST['column'], $pjSubscriptionModel->getI18n()))
			{
				$pjSubscriptionModel->set('id', $_GET['id'])->modify(array($_POST['column'] => $_POST['value']));
			} else {
				pjMultiLangModel::factory()->updateMultiLang(array($this->getLocaleId() => array($_POST['column'] => $_POST['value'])), $_GET['id'], 'pjSubscription');
			}
			pjAppController::jsonResponse(array('status' => 'OK', 'code' => 200, 'text' => 'Subscription have been modified.'));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['subscription_update']))
			{
				if (!$this->__checkEmail($_POST['email'], $_POST['id']))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminSubscriptions&action=pjActionIndex&err=ASP05");
				}
				
				pjSubscriptionModel::factory()->set('id', $_POST['id'])->modify($_POST);
				if (isset($_POST['i18n']))
				{
					pjMultiLangModel::factory()->updateMultiLang($_POST['i18n'], $_POST['id'], 'pjSubscription');
				}
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminSubscriptions&action=pjActionIndex&err=ASP01");
				
			}
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$arr = pjSubscriptionModel::factory()->find($_GET['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminSubscriptions&action=pjActionIndex&err=ASP08");
				}
				$this->set('arr', $arr);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminSubscriptions.js');
			} else {
				pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminSubscriptions&action=pjActionIndex&err=ASP08");
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>