<?php

/**
 *--------------------------------------
 * 广告
 *--------------------------------------
 * @project		: uwa
 * @author		: cblee
 * @created		: 2012-10-18
 * @copyright	: (c)2012 AsThis
 *--------------------------------------
 */

class AdModl extends Modl
{
	public function get_adList($adSpaceId = '', $timeLimit = false)
	{
		$where = array();
		if(!empty($adSpaceId))
		{
			$where['__AD__.ad_space_id'] = array('EQ', $adSpaceId);
		}
		$_AL = $this->order('a_display_order ASC')
			->join('__AD_SPACE__ AS `as` ON `as`.ad_space_id = __AD__.ad_space_id')
			->where($where)
			->select();
		if($timeLimit)
		{
			foreach($_AL as $k => $v)
			{
				if((time() < $v['a_start_time'] or time() > $v['a_end_time']) and 1 == $v['a_time_limit'])
				{
					unset($_AL[$k]);
				}
			}
		}

		return $_AL;
	}

	public function get_adInfo($adId)
	{
		$_AI = $this->join('__AD_SPACE__ AS `as` ON `as`.ad_space_id = __AD__.ad_space_id')
			->where('__AD__.ad_id = \''.$adId.'\'')->find();
		return $_AI;
	}

	public function add_ad($data)
	{
		$result = array('data' => '', 'error' => '');

		$data['a_start_time'] = strtotime($data['a_start_time']);
		$data['a_end_time'] = strtotime($data['a_end_time']);

		$_t_id = $this->insert($data);
		if(false === $_t_id)
		{
			$result['error'] = L('ADD_FAILED');
			return $result;
		}
		$result['data'] = $_t_id;

		/* 更新附件 */
		M('Upload')->update_upload($_t_id, ASession::get('member_id'));

		return $result;
	}

	public function edit_ad($data)
	{
		$result = array('data' => '', 'error' => '');

		if(isset($data['a_start_time']))
		{
			$data['a_start_time'] = strtotime($data['a_start_time']);
		}
		if(isset($data['a_end_time']))
		{
			$data['a_end_time'] = strtotime($data['a_end_time']);
		}

		if(false === $this->update($data))
		{
			$result['error'] = L('EDIT_FAILED');
			return $result;
		}

		/* 更新附件 */
		M('Upload')->update_upload($data['ad_id'], ASession::get('member_id'));

		return $result;
	}

	public function delete_ad($adId)
	{
		$result = array('data' => '', 'error' => '');

		$_AI = $this->where('ad_id = \''.$adId.'\'')->find();
		if(empty($_AI))
		{
			$result['error'] = L('ITEM_NOT_EXIST');
			return $result;
		}

		if(false === $this->delete($adId))
		{
			$result['error'] = L('DELETE_FAILED');
			return $result;
		}

		/* 删除上传文件 */
		$_AUL = M('Upload')->where("`u_item_type` = 'ad' and `u_item_id` = '".$adId."'")->select();
		if(!empty($_AUL))
		{
			foreach($_AUL as $au)
			{
				/* 删除文件 */
				@unlink(realpath($_SERVER['DOCUMENT_ROOT'].$a['u_src']));
			}
		}
		/* 删除上传表信息 */
		M('Upload')->where("`u_item_type` = 'ad' and `u_item_id` = '".$adId."'")->delete();

		return $result;
	}
}

?>