<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminOffers extends pjAdmin
{
	public $offerType = 'pjSugPrice_OfferType';
	
	public function pjActionDeleteOffer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
			if (pjOfferModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
			{
				$response['code'] = 200;
			} else {
				$response['code'] = 100;
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteOfferBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjOfferModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
			}
		}
		exit;
	}
	
	public function pjActionExportOffers()
	{
		$this->checkLogin();
	
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$type_action = __('type_action', true);
			
			$arr = pjOfferModel::factory()
				->select("t1.id, t2.name AS product, t1.price, t1.type, t1.email, t1.promo_code as promo_message, t1.ip")
				->join('pjProduct', 't1.product_id=t2.id', 'left outer')
				->whereIn('t1.id', $_POST['record'])
				->findAll()
				->getData();
			foreach($arr as $k => $v)
			{
				$v['type'] = $type_action[$v['type']];
				$arr[$k] = $v;
			}
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Offers-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetOffer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjOfferModel = pjOfferModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjOfferModel->where("t1.email LIKE '%$q%' OR t2.name LIKE '%$q%'");
			}
			if(isset($_GET['status']) && !empty($_GET['status']))
			{
				$pjOfferModel->where('t1.type', $_GET['status']);
				$_SESSION[$this->offerType] = $_GET['status']; 
			}else{
				unset($_SESSION[$this->offerType]);
			}
			if(isset($_GET['product_id']) && (int) $_GET['product_id'] > 0)
			{
				$pjOfferModel->where('t1.product_id', $_GET['product_id']);
			}
			if(isset($_GET['ip']) && !empty($_GET['ip']))
			{
				$pjOfferModel->where('t1.ip', $_GET['ip']);
			}
			$column = 'created';
			$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 = $pjOfferModel->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 = $pjOfferModel
				->select("t1.*, t2.name")
				->join('pjProduct', 't1.product_id=t2.id', 'left')
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();
			$type_action = __('type_action', true);
			foreach($data as $k => $v)
			{
				$v['price'] = $v['price'] != null ? pjUtil::formatCurrencySign($v['price'], $this->option_arr['o_currency']) : '';
				$v['created'] = date($this->option_arr['o_date_format'], strtotime($v['created'])) . ', ' . date($this->option_arr['o_time_format'], strtotime($v['created']));
				$v['type'] = $type_action[$v['type']];
				$data[$k] = $v;
			}
				
			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$product_arr = pjProductModel::factory()
				->where('t1.status', 'T')
				->orderBy("t1.name ASC")
				->findAll()
				->getData();
			
			$this->set('product_arr', $product_arr);
						
			$this->appendJs('chosen.jquery.min.js', PJ_THIRD_PARTY_PATH . 'harvest/');
			$this->appendCss('chosen.css', PJ_THIRD_PARTY_PATH . 'harvest/');
			
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminOffers.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveOffer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjOfferModel = pjOfferModel::factory();
			if (!in_array($_POST['column'], $pjOfferModel->i18n))
			{
				$pjOfferModel->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['offer_update']))
			{
				$data = array();
				if(!isset($_POST['email']))
				{
					$data['email'] = ':NULL';
				}
				$product = pjProductModel::factory()->find($_POST['product_id'])->getData();
				switch ($product['suggest_type']) {
					case 'offer':
						$data['type'] = $product['price_suggest_'.$_POST['price_option'].'_action'];
					break;
					
					case 'suggest':
						$data['type'] = $product['price_range_'.$_POST['price_option'].'_action'];
					break;
				}
				pjOfferModel::factory()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminOffers&action=pjActionIndex&err=AOF01");
				
			} else {
				$pjOfferModel = pjOfferModel::factory();
				$arr = $pjOfferModel
					->select("t1.*, (SELECT COUNT(`TO`.id) FROM `".$pjOfferModel->getTable()."` AS `TO` WHERE `TO`.ip = t1.ip) AS cnt_offers")
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminOffers&action=pjActionIndex&err=AOF08");
				}
				
				$this->set('arr', $arr);
				$this->set('product_arr', pjProductModel::factory()->where('t1.status', 'T')->orderBy('name ASC')->findAll()->getData());
				$this->set('product', pjProductModel::factory()->find($arr['product_id'])->getData());
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminOffers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionGetPrices()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$this->set('product', pjProductModel::factory()->find($_POST['product_id'])->getData());
		}		
	}
	
	public function pjActionGetMessages()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$this->set('product', pjProductModel::factory()->find($_POST['product_id'])->getData());
		}
	}
}
?>