<?php
if (!defined("ROOT_PATH"))
{
	header("HTTP/1.1 403 Forbidden");
	exit;
}
class pjCodeModel extends pjAppModel
{
	protected $primaryKey = 'id';
	
	protected $table = 'codes';
	
	protected $schema = array(
		array('name' => 'id', 'type' => 'int', 'default' => ':NULL'),
		array('name' => 'event_id', 'type' => 'int', 'default' => ':NULL'),
		array('name' => 'code', 'type' => 'varchar', 'default' => ':NULL'),
		array('name' => 'type', 'type' => 'enum', 'default' => 'percent'),
		array('name' => 'discount', 'type' => 'decimal', 'default' => ':NULL'),
		array('name' => 'count', 'type' => 'int', 'default' => ':NULL'),
		array('name' => 'valid_from', 'type' => 'datetime', 'default' => ':NULL'),
		array('name' => 'valid_to', 'type' => 'datetime', 'default' => ':NULL')
	);
	
	public static function factory($attr=array())
	{
		return new pjCodeModel($attr);
	}
	
	public function checkCode($event_id, $code, $option_arr)
	{
		$code_arr = $this
			->where('t1.event_id', $event_id)
			->where('t1.code', $code)
			->where("(CURDATE() BETWEEN t1.valid_from AND t1.valid_to)")
			->limit(1)
			->findAll()
			->getData();
		if(count($code_arr) > 0)
		{
			$code_arr = $code_arr[0];
			$ticket_id_arr = array();
			$ticket_arr = pjCodeTicketModel::factory()
				->select('t1.*, t2.*')
				->join("pjTicket", 't1.ticket_id=t2.id', 'left')
				->where('t1.code_id', $code_arr['id'])
				->findAll()
				->getData();
			
			foreach($ticket_arr as $k => $v)
			{
				if($v['type'] == 'paid')
				{
					$price = $v['price'];
					if((float) $code_arr['discount'] > 0)
					{
						if($code_arr['type'] == 'percent')
						{
							$price = $v['price'] - ($v['price'] * (float) $code_arr['discount'] / 100);
						}else{
							$price = $v['price'] - $code_arr['discount'];
						}
					}
					if($price < 0)
					{
						$price = 0;
					}
					$ticket_id_arr[] = $v['id'] . '~:~' . $price . '~:~' . pjUtil::formatCurrencySign(number_format($price, 2), $option_arr['o_currency']);
				}
			}
			$code_arr['ticket_id_arr'] = implode("~|~", $ticket_id_arr);
			$code_arr['status'] = 'OK';
		}else{
			$code_arr['status'] = 'ERR';
		}
		
		return $code_arr;
	}
}
?>