<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}

class pjAdminCustomers extends pjAdmin
{
	public function pjActionCheckEmail()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['token_3']) || empty($_GET['token_3']))
			{
				echo 'false';
				exit;
			}
			$pjCustomerTokenModel = pjCustomerTokenModel::factory()->where('t1.token_id', 3)->where('t1.content', $_GET['token_3']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjCustomerTokenModel->where('t1.customer_id !=', $_GET['id']);
			}
			echo $pjCustomerTokenModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$token_arr = pjTokenModel::factory()->findAll()->getData();
			
			if (isset($_POST['customer_create']))
			{
				$pjCustomerModel = pjCustomerModel::factory();
				
				$id = $pjCustomerModel->reset()->setAttributes($_POST)->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$pjCustomerTokenModel = pjCustomerTokenModel::factory();
					$pjCustomerTokenModel->begin();
					foreach($token_arr as $token)
					{
						$pjCustomerTokenModel
							->reset()
							->set('customer_id', $id)
							->set('token_id', $token['id'])
							->set('content', $_POST['token_' . $token['id']])
							->insert();
						
					}
					$pjCustomerTokenModel->commit();
					
					$err = 'ACU03';
				} else {
					$err = 'ACU04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminCustomers&action=pjActionIndex&err=$err");
			} else {
				
				$this->set('token_arr', $token_arr);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminCustomers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteCustomer()
	{
		$this->setAjax(true);
		
		if ($this->isXHR())
		{
			$response = array();
			if ($this->isAdmin())
			{
				if (pjCustomerModel::factory()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					$pjDocumentModel = pjDocumentModel::factory();
					
					pjCustomerTokenModel::factory()->where('customer_id', $_GET['id'])->eraseAll();
					$doc_id_arr = $pjDocumentModel->where('customer_id', $_GET['id'])->findAll()->getDataPair(null, 'id');
					if(!empty($doc_id_arr))
					{
						$pjDocumentModel->reset()->whereIn('id', $doc_id_arr)->eraseAll();
						pjHistoryModel::factory()->whereIn('document_id', $doc_id_arr)->eraseAll();
					}
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
			}
			pjAppController::jsonResponse($response);
		}
		exit;
	}
	
	public function pjActionDeleteCustomerBulk()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if ($this->isAdmin())
			{
				if (isset($_POST['record']) && count($_POST['record']) > 0)
				{
					$pjDocumentModel = pjDocumentModel::factory();
					
					pjCustomerModel::factory()->whereIn('id', $_POST['record'])->eraseAll();
					pjCustomerTokenModel::factory()->whereIn('customer_id', $_POST['record'])->eraseAll();
					$doc_id_arr = $pjDocumentModel->whereIn('customer_id', $_POST['record'])->findAll()->getDataPair(null, 'id');
					if(!empty($doc_id_arr))
					{
						$pjDocumentModel->reset()->whereIn('id', $doc_id_arr)->eraseAll();
						pjHistoryModel::factory()->whereIn('document_id', $doc_id_arr)->eraseAll();
					}
				}
			}
		}
		exit;
	}
	
	public function pjActionGetCustomer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjCustomerModel = pjCustomerModel::factory();
			$pjCustomerTokenModel = pjCustomerTokenModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjCustomerModel->where("t1.id IN (SELECT TCT.customer_id FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE (TCT.token_id=1 AND TCT.content LIKE '%$q%') OR (TCT.token_id=2 AND TCT.content LIKE '%$q%') OR (TCT.token_id=3 AND TCT.content LIKE '%$q%')) ");
			}
			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjCustomerModel->where('t1.status', $_GET['status']);
			}
			$column = 'id';
			$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 = $pjCustomerModel->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 = $pjCustomerModel
				->select("t1.*,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=1) AS first_name,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=2) AS last_name,
						  (SELECT TCT.content FROM `".$pjCustomerTokenModel->getTable()."` AS TCT WHERE TCT.customer_id=t1.id AND TCT.token_id=3) AS email,
						  (SELECT COUNT(customer_id) FROM `".pjDocumentModel::factory()->getTable()."` AS TD WHERE TD.customer_id=t1.id) AS documents")
				->orderBy("$column $direction")
				->limit($rowCount, $offset)
				->findAll()
				->getData();

			pjAppController::jsonResponse(compact('data', 'total', 'pages', 'page', 'rowCount', 'column', 'direction'));
		}
		exit;
	}
	
	public function pjActionIndex()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$this->appendJs('jquery.datagrid.js', PJ_FRAMEWORK_LIBS_PATH . 'pj/js/');
			$this->appendJs('pjAdminCustomers.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveCustomer()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			pjCustomerModel::factory()->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$token_arr = pjTokenModel::factory()->findAll()->getData();
				
			$pjCustomerModel = pjCustomerModel::factory();
			if (isset($_POST['customer_update']))
			{
				$pjCustomerModel->where('id', $_POST['id'])->limit(1)->modifyAll($_POST);
				
				$pjCustomerTokenModel = pjCustomerTokenModel::factory();
				$pjCustomerTokenModel->where('customer_id', $_POST['id'])->eraseAll();
				$pjCustomerTokenModel->reset()->begin();
				foreach($token_arr as $token)
				{
					$pjCustomerTokenModel
						->reset()
						->set('customer_id', $_POST['id'])
						->set('token_id', $token['id'])
						->set('content', $_POST['token_' . $token['id']])
						->insert();
				
				}
				$pjCustomerTokenModel->commit();
				
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminCustomers&action=pjActionIndex&err=ACU01");
				
			} else {
				$arr = $pjCustomerModel
					->select("t1.*, (SELECT COUNT(*) FROM `".pjDocumentModel::factory()->getTable()."` AS TD WHERE TD.customer_id=t1.id) AS documents")
					->find($_GET['id'])
					->getData();
					
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminCustomers&action=pjActionIndex&err=ACU08");
				}
				
				$content_arr = pjCustomerTokenModel::factory()->where('customer_id', $_GET['id'])->findAll()->getDataPair('token_id', 'content');
				
				$this->set('arr', $arr);
				$this->set('token_arr', $token_arr);
				$this->set('content_arr', $content_arr);
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminCustomers.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
}
?>