<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminProducts extends pjAdmin
{
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['product_create']))
			{
				if($_POST['suggest_type'] == 'offer')
				{
					for($i = 1; $i <=3; $i++)
					{
						$_POST['price_range_'.$i.'_action'] = ':NULL';
						$_POST['price_range_'.$i.'_promo'] = ':NULL';
						$_POST['price_range_'.$i.'_email'] = ':NULL';
						switch ($_POST['price_suggest_'.$i.'_action']) {
							case 'promo':
								$_POST['price_suggest_'.$i.'_email'] = ':NULL';
								$_POST['price_suggest_'.$i.'_message'] = ':NULL';
								break;
							case 'email':
								$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
								$_POST['price_suggest_'.$i.'_message'] = ':NULL';
								break;
							case 'thank':
								$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
								$_POST['price_suggest_'.$i.'_email'] = ':NULL';
								break;
						}
					}
				}
				if($_POST['suggest_type'] == 'suggest')
				{
					for($i = 1; $i <=3; $i++)
					{
						$_POST['price_suggest_'.$i.'_action'] = ':NULL';
						$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
						$_POST['price_suggest_'.$i.'_email'] = ':NULL';
						switch ($_POST['price_suggest_'.$i.'_action']) {
							case 'promo':
								$_POST['price_range_'.$i.'_email'] = ':NULL';
								$_POST['price_range_'.$i.'_message'] = ':NULL';
								break;
							case 'email':
								$_POST['price_range_'.$i.'_promo'] = ':NULL';
								$_POST['price_range_'.$i.'_message'] = ':NULL';
								break;
							case 'thank':
								$_POST['price_range_'.$i.'_promo'] = ':NULL';
								$_POST['price_range_'.$i.'_email'] = ':NULL';
								break;
						}
					}
				}
				
				$id = pjProductModel::factory($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'AP03';
				} else {
					$err = 'AP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminProducts&action=pjActionIndex&err=$err");
			} else {
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminProducts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}

	public function pjActionDeleteProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjProductModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteProductBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjProductModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionGetProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductModel = pjProductModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjProductModel->where('t1.name LIKE', "%$q%");
			}

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

			$total = $pjProductModel->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 = $pjProductModel
				->select("t1.*, 
						  (SELECT COUNT(`TO`.id) FROM `".pjOfferModel::factory()->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id) AS cnt_offers,
						  (SELECT AVG(`TO`.price) FROM `".pjOfferModel::factory()->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id) AS avg")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			foreach($data as $k => $v)
			{
				$v['price'] = $v['price'] != null ? pjUtil::formatCurrencySign($v['price'], $this->option_arr['o_currency']) : '';
				$v['avg'] = $v['avg'] != null ? pjUtil::formatCurrencySign(number_format($v['avg'], 2), $this->option_arr['o_currency']) : '';
				$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('pjAdminProducts.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveProduct()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjProductModel = pjProductModel::factory();
			$pjProductModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();

		if ($this->isAdmin() || $this->isEditor())
		{
			if (isset($_POST['product_update']))
			{
				if($_POST['suggest_type'] == 'offer')
				{
					for($i = 1; $i <=3; $i++)
					{
						$_POST['price_range_'.$i.'_action'] = ':NULL';
						$_POST['price_range_'.$i.'_promo'] = ':NULL';
						$_POST['price_range_'.$i.'_email'] = ':NULL';
						switch ($_POST['price_suggest_'.$i.'_action']) {
							case 'promo':
								$_POST['price_suggest_'.$i.'_email'] = ':NULL';
								$_POST['price_suggest_'.$i.'_message'] = ':NULL';
								break;
							case 'email':
								$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
								$_POST['price_suggest_'.$i.'_message'] = ':NULL';
								break;
							case 'thank':
								$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
								$_POST['price_suggest_'.$i.'_email'] = ':NULL';
								break;
						}
					}
				}
				if($_POST['suggest_type'] == 'suggest')
				{
					for($i = 1; $i <=3; $i++)
					{
						$_POST['price_suggest_'.$i.'_action'] = ':NULL';
						$_POST['price_suggest_'.$i.'_promo'] = ':NULL';
						$_POST['price_suggest_'.$i.'_email'] = ':NULL';
						switch ($_POST['price_suggest_'.$i.'_action']) {
							case 'promo':
								$_POST['price_range_'.$i.'_email'] = ':NULL';
								$_POST['price_range_'.$i.'_message'] = ':NULL';
								break;
							case 'email':
								$_POST['price_range_'.$i.'_promo'] = ':NULL';
								$_POST['price_range_'.$i.'_message'] = ':NULL';
								break;
							case 'thank':
								$_POST['price_range_'.$i.'_promo'] = ':NULL';
								$_POST['price_range_'.$i.'_email'] = ':NULL';
								break;
						}
					}
				}
				pjProductModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminProducts&action=pjActionIndex&err=AP01");
				
			} else {
				$pjOfferModel = pjOfferModel::factory();
				$arr = pjProductModel::factory()
					->select("t1.*,
							  (SELECT COUNT(TO.id) FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id AND `TO`.type='email') AS cnt_emails,	
							  (SELECT COUNT(TO.id) FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id AND `TO`.type='thank') AS cnt_thanks,
							  (SELECT COUNT(TO.id) FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id AND `TO`.type='promo') AS cnt_codes,
							  (SELECT AVG(TO.price) FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE `TO`.product_id=t1.id) AS avg_price")
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminProducts&action=pjActionIndex&err=AP08");
				}
				
				$this->set('arr', $arr);
				$this->set('cnt_offers', $pjOfferModel->reset()->where('product_id', $_GET['id'])->findCount()->getData());
				$this->set('cnt_ips', $pjOfferModel->reset()->where('product_id', $_GET['id'])->groupBy("t1.ip")->findCount()->getData());
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminProducts.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionRemoverOffers()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			
			if(isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjOfferModel = pjOfferModel::factory();
				$id_arr = $pjOfferModel
					->select("t1.ip, (SELECT TO.id FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE TO.ip=t1.ip ORDER BY TO.created DESC LIMIT 1) AS last_id")
					->where('product_id', $_GET['id'])
					->groupBy("ip")
					->findAll()
					->getDataPair(null, 'last_id');
				
				if(!empty($id_arr))
				{
					$pjOfferModel->reset()->where('product_id', $_GET['id'])->whereNotIn('id', $id_arr)->eraseAll();
					$response['code'] = 200;
				}else{
					$response['code'] = 100;
				}
				
			}else{
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
}
?>