<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjAdminCampaigns extends pjAdmin
{
	public function pjActionCheckTitle()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (!isset($_GET['title']) || empty($_GET['title']))
			{
				echo 'false';
				exit;
			}
			$pjCampaignModel = pjCampaignModel::factory()->where('t1.title', $_GET['title']);
			if (isset($_GET['id']) && (int) $_GET['id'] > 0)
			{
				$pjCampaignModel->where('t1.id !=', $_GET['id']);
			}
			echo $pjCampaignModel->findCount()->getData() == 0 ? 'true' : 'false';
		}
		exit;
	}
	
	public function pjActionCreate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminCampaigns&action=pjActionIndex&err=ACP05");
			}
			if (isset($_POST['campaign_create']))
			{
				$pjCampaignModel = pjCampaignModel::factory();
				
				$data = array();
				
				$data['deadline'] = pjUtil::formatDate($_POST['deadline'], $this->option_arr['o_date_format']);
				unset($_POST['deadline']);
				
				$id = $pjCampaignModel->setAttributes(array_merge($_POST, $data))->insert()->getInsertId();
				if ($id !== false && (int) $id > 0)
				{
					$err = 'ACP03';
					
					if (isset($_FILES['image']))
					{
						if($_FILES['image']['error'] == 0)
						{
							if(getimagesize($_FILES['image']["tmp_name"]) != false)
							{
								$Image = new pjImage();
								if ($Image->getErrorCode() !== 200)
								{
									$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
									if ($Image->load($_FILES['image']))
									{
										$resp = $Image->isConvertPossible();
										if ($resp['status'] === true)
										{
											$hash = md5(uniqid(rand(), true));
											$image_path = PJ_UPLOAD_PATH . $id . '_' . $hash . '.' . $Image->getExtension();
												
											$Image->loadImage($_FILES['image']["tmp_name"]);
											$Image->setFillColor($this->imageFillColor)->resize(300, 170);
											$Image->saveImage($image_path);
					
											$pjCampaignModel->reset()->where('id', $id)->limit(1)->modifyAll(array('image'=>$image_path));
												
										}
									}
								}
							}else{
								$err = 'ACP09';
							}
						}else if($_FILES['image']['error'] != 4){
							$err = 'ACP09';
						}
					}
				} else {
					$err = 'ACP04';
				}
				pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminCampaigns&action=pjActionIndex&err=$err");
			} else {
				
				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminCampaigns.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteCampaign()
	{
		$this->setAjax(true);
		if ($this->isAdmin())
		{
			if ($this->isXHR())
			{
				$pjCampaignModel = pjCampaignModel::factory();
				$response = array();
				$arr = $pjCampaignModel->find($_GET['id'])->getData();
				if ($pjCampaignModel->reset()->setAttributes(array('id' => $_GET['id']))->erase()->getAffectedRows() == 1)
				{
					pjDonationModel::factory()->where('campaign_id', $_GET['id'])->eraseAll();
					if (file_exists(PJ_INSTALL_PATH . $arr['image'])) {
						@unlink(PJ_INSTALL_PATH . $arr['image']);
					}
					$response['code'] = 200;
				} else {
					$response['code'] = 100;
				}
				
				pjAppController::jsonResponse($response);
			}
		}
		exit;
	}
	
	public function pjActionDeleteCampaignBulk()
	{
		$this->setAjax(true);
		if ($this->isAdmin())
		{
			if ($this->isXHR())
			{
				if (isset($_POST['record']) && count($_POST['record']) > 0)
				{
					$pjCampaignModel = pjCampaignModel::factory();
					$arr = $pjCampaignModel->whereIn('id', $_POST['record'])->findAll()->getData();
					foreach($arr as $v)
					{
						if (file_exists(PJ_INSTALL_PATH . $v['image'])) {
							@unlink(PJ_INSTALL_PATH . $v['image']);
						}
					}
					$pjCampaignModel->reset()->whereIn('id', $_POST['record'])->eraseAll();
					pjDonationModel::factory()->whereIn('campaign_id', $_POST['record'])->eraseAll();
				}
			}
		}
		exit;
	}
	
	public function pjActionExportCampaign()
	{
		$this->checkLogin();
		
		if (isset($_POST['record']) && is_array($_POST['record']))
		{
			$arr = pjCampaignModel::factory()->whereIn('id', $_POST['record'])->findAll()->getData();
			$csv = new pjCSV();
			$csv
				->setHeader(true)
				->setName("Campaigns-".time().".csv")
				->process($arr)
				->download();
		}
		exit;
	}
	
	public function pjActionGetCampaign()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjCampaignModel = pjCampaignModel::factory();
			
			if (isset($_GET['q']) && !empty($_GET['q']))
			{
				$q = pjObject::escapeString($_GET['q']);
				$pjCampaignModel->where('t1.title LIKE', "%$q%");
				$pjCampaignModel->orWhere('t1.description LIKE', "%$q%");
			}

			if (isset($_GET['status']) && !empty($_GET['status']) && in_array($_GET['status'], array('T', 'F')))
			{
				$pjCampaignModel->where('t1.status', $_GET['status']);
			}
				
			$column = 'title';
			$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 = $pjCampaignModel->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 = array();
			
			$data = $pjCampaignModel
				->select("t1.*, (SELECT SUM(`TD`.`amount`) FROM `".pjDonationModel::factory()->getTable()."` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS total_donated,
								(SELECT COUNT(`TD`.`id`) FROM `".pjDonationModel::factory()->getTable()."` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS cnt_donations")
				->orderBy("$column $direction")->limit($rowCount, $offset)->findAll()->getData();
			foreach($data as $k => $v)
			{
				$v['deadline'] = date($this->option_arr['o_date_format'], strtotime($v['deadline']));
				$total_donated = 0.00;
				if(!empty($v['total_donated']))
				{
					$total_donated = $v['total_donated'];
				}
				$v['donated'] = pjUtil::formatCurrencySign($total_donated , $this->option_arr['o_currency']) . ' ' . __('lblOf', true) . ' ' . pjUtil::formatCurrencySign($v['amount'], $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('pjAdminCampaigns.js');
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionSaveCampaign()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$pjCampaignModel = pjCampaignModel::factory();
			$pjCampaignModel->where('id', $_GET['id'])->limit(1)->modifyAll(array($_POST['column'] => $_POST['value']));
		}
		exit;
	}
	
	public function pjActionStatusCampaign()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			if (isset($_POST['record']) && count($_POST['record']) > 0)
			{
				pjCampaignModel::factory()->whereIn('id', $_POST['record'])->where('id <>', 1)->modifyAll(array(
					'status' => ":IF(`status`='F','T','F')"
				));
			}
		}
		exit;
	}
	
	public function pjActionUpdate()
	{
		$this->checkLogin();
		
		if ($this->isAdmin() || $this->isEditor())
		{
			$post_max_size = pjUtil::getPostMaxSize();
			if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && (int) $_SERVER['CONTENT_LENGTH'] > $post_max_size)
			{
				pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminCampaigns&action=pjActionIndex&err=ACP06");
			}	
			if (isset($_POST['campaign_update']))
			{
				$pjCampaignModel = pjCampaignModel::factory();
				
				$err = 'ACP01';
				
				$arr = $pjCampaignModel->find($_POST['id'])->getData();
				if (empty($arr))
				{
					pjUtil::redirect($_SERVER['PHP_SELF'] . "?controller=pjAdminCampaigns&action=pjActionIndex&err=ACP08");
				}
				
				$data = array();
				$data['deadline'] = pjUtil::formatDate($_POST['deadline'], $this->option_arr['o_date_format']);
				unset($_POST['deadline']);
				
				if (isset($_FILES['image']))
				{
					if($_FILES['image']['error'] == 0)
					{
						if(getimagesize($_FILES['image']["tmp_name"]) != false)
						{
							if(!empty($arr['image']))
							{
								@unlink(PJ_INSTALL_PATH . $arr['image']);
							}
							$Image = new pjImage();
							if ($Image->getErrorCode() !== 200)
							{
								$Image->setAllowedTypes(array('image/png', 'image/gif', 'image/jpg', 'image/jpeg', 'image/pjpeg'));
								if ($Image->load($_FILES['image']))
								{
									$resp = $Image->isConvertPossible();
									if ($resp['status'] === true)
									{
										$hash = md5(uniqid(rand(), true));
										$image_path = PJ_UPLOAD_PATH . $_POST['id'] . '_' . $hash . '.' . $Image->getExtension();
				
										$Image->loadImage($_FILES['image']["tmp_name"]);
										$Image->setFillColor($this->imageFillColor)->resize(300, 170);
										$Image->saveImage($image_path);
										$data['image'] = $image_path;
									}
								}
							}
						}else{
							$err = 'ACP10';
						}
					}else if($_FILES['image']['error'] != 4){
						$err = 'ACP10';
					}
				}
				
				$pjCampaignModel->reset()->where('id', $_POST['id'])->limit(1)->modifyAll(array_merge($_POST, $data));
				
				if($err == 'ACP01')
				{
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminCampaigns&action=pjActionIndex&err=ACP01");
				}else{
					pjUtil::redirect(PJ_INSTALL_URL . "index.php?controller=pjAdminCampaigns&action=pjActionUpdate&id=".$_POST['id']."&err=ACP10");
				}
				
			} else {
				$tblName = pjDonationModel::factory()->getTable();
				$arr = pjCampaignModel::factory()
					->select("t1.*, (SELECT SUM(`TD`.`amount`) FROM `$tblName` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS total_amount,
									(SELECT COUNT(`TD`.`id`) FROM `$tblName` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS total_donations")
					->find($_GET['id'])
					->getData();
				if (count($arr) === 0)
				{
					pjUtil::redirect(PJ_INSTALL_URL. "index.php?controller=pjAdminCampaigns&action=pjActionIndex&err=ACP08");
				}
				$this->set('arr', $arr);

				$this->appendJs('jquery.validate.min.js', PJ_THIRD_PARTY_PATH . 'validate/');
				$this->appendJs('pjAdminCampaigns.js');
			}
		} else {
			$this->set('status', 2);
		}
	}
	
	public function pjActionDeleteImage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
				
			$pjCampaignModel = pjCampaignModel::factory();
			$arr = $pjCampaignModel->find($_GET['id'])->getData();
				
			if(!empty($arr))
			{
				if(!empty($arr['image']))
				{
					@unlink(PJ_INSTALL_PATH . $arr['image']);
				}
	
				$data = array();
				$data['image'] = ':NULL';
				$pjCampaignModel->reset()->where(array('id' => $_GET['id']))->limit(1)->modifyAll($data);
	
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
				
			pjAppController::jsonResponse($response);
		}
	}
	
	public function pjActionGetMessage()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$arr = pjCampaignModel::factory()
				->select("t1.*, (SELECT SUM(`TD`.`amount`) FROM `".pjDonationModel::factory()->getTable()."` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS total_donated,
								(SELECT COUNT(`TD`.`id`) FROM `".pjDonationModel::factory()->getTable()."` AS TD WHERE TD.campaign_id=t1.id AND TD.status='P') AS cnt_donations")
				->find($_GET['id'])->getData();
			$this->set('arr', $arr);
		}
	}
	
	public function pjActionStopCampaign()
	{
		$this->setAjax(true);
	
		if ($this->isXHR())
		{
			$response = array();
	
			$pjCampaignModel = pjCampaignModel::factory();
			$arr = $pjCampaignModel->find($_POST['id'])->getData();
	
			if(!empty($arr))
			{
				$data = array();
				$data['status'] = 'F';
				$pjCampaignModel->reset()->where(array('id' => $_POST['id']))->limit(1)->modifyAll($data);
				$response['code'] = 200;
			}else{
				$response['code'] = 100;
			}
	
			pjAppController::jsonResponse($response);
		}
	}
}
?>