<?php
/**
 * Class crm model
 */
class crmMod extends mod{
	protected $crmLocal = null;
	protected $tables = [];
	public $logic = null;
	protected $baseData = null;
	protected $nextId = null;
	function __construct(){
		parent::__construct([]);
		$this->logic = new logicMod();
		$this->crmLocal = new LibDb(mvc::$cfg['db']['money_crm']);
        $this->tables = [
            ['name'=>'do_user','key'=>['usr_id','usr_username'],'isbig'=>0,'remark'=>'职员表','function'=>null],
            ['name'=>'yj_team','key'=>'te_id','isbig'=>0,'remark'=>'团队表','function'=>null],
            ['name'=>'yj_user','key'=>'u_id','isbig'=>0,'remark'=>'业务员表','function'=>null],
            ['name'=>'yja_department','key'=>'dep_id','isbig'=>0,'remark'=>'部门表','function'=>null],
            ['name'=>'yja_money','key'=>'mon_id','isbig'=>true,'remark'=>'业绩表','function'=>null],
            ['name'=>'yja_money_ser','key'=>'mos_id','isbig'=>true,'remark'=>'业绩项目表','function'=>null],
            ['name'=>'yja_paytype','key'=>'ypt_id','isbig'=>0,'remark'=>'付款方式表','function'=>null],
            ['name'=>'yja_service','key'=>'ser_id','isbig'=>0,'remark'=>'服务项目表','function'=>null],
            ['name'=>'yja_site','key'=>'site_id','isbig'=>0,'remark'=>'宜配的公司表','function'=>null],
        ];
		$this->baseData = $this->getMoneyBaseData();
		$this->nextId = $this->logic->getMaxId() + 1;

    }
	/**
	 * Method 列表数据
	 * @param string $where 查询sql条件
	 * @param int $page 页码(从1开始)
	 * @param int $pagesize 分页大小
	 * @param string $sidx 排序字段(单个)
	 * @param string $sord 排序方式 asc|desc
	 * @param string $orderby 排序sql(可多个)[优先]
	 * @return array 数据集
	 */
	public function list($where='',$page=0,$pagesize=0,$sidx='',$sord='asc',$orderby=''){
		$sql = '
			SELECT *,FROM_UNIXTIME(mon_date,"%Y-%m-%d") mon_date1 FROM yja_money 
			JOIN yja_money_ser ON mon_id=mos_mon_id
			JOIN yj_user ON u_id=mon_u_id
			ORDER BY mon_date desc,mon_id DESC
		';
		if(trim($where)!='') {
			if(strtolower(substr(trim($where),0,3))!=='and') $where = ' AND ' . $where;
			$sql .= $where;
		}
		if($sidx=='' && $orderby=="") $orderby =  $this->e['order']; //默认排序
		if($orderby!=''){
			$sql.= sprintf(' ORDER BY %s', $orderby);
		}else if($sidx!=''){
			$sql.= sprintf(' ORDER BY %s %s',$sidx,$sord);
		}
		if($page>0 && $pagesize>0){
			$pages = $this->crmLocal->PageLimit($sql,$page,$pagesize);
			$sql .= $pages['limit'];
		}
		$rows = $this->crmLocal->Table($sql);
		foreach($rows as $i=>$row){
			$rows[$i] = $this->formatRow($row);
		}
		$footerData=[];
		$data = [
			'page'=> $pages['page'],
			'total'=> $pages['total'],
			'records' => $pages['records'],
			"userdata"=> $footerData,
			'rows' => $rows
		];
		mvc::runtimeAdd();
		return $data;
	}

	public function formatRow($row){
		$item = [];
		$item['v_date'] = $row['mon_date1'];
		foreach($item as $k=>$v){
			$row[$k] = $v;
		}
		return $row;
	}

	public function getMoneyBaseData(){
		$result = [];
		$crmDb = new db(I('cfg.libs.database.money_crm'));
		$q = (new sqler());
		foreach($this->tables as $table){
			if(! $table['isbig']){
				$tableName = $table['name'];
				$q->table($tableName)->map($table['key']);
				$result[$tableName] = $crmDb->select($q)->all();
			}
		}
		return $result;
	}

	public function newVouvherList($formatNewVouvherRows=true, $where = '', $page, $pagesize = 500, $order= null)
	{
		$order = $order ?: ['mon_date' => 'DESC', 'mon_id' => 'DESC'];

		$q = new sqler($this->logic->db);
		//构建
		$q->table('money_crm.yja_money')
			->join('money_crm.yja_money_ser', ['mon_id' => '@mos_mon_id'])
			->join('money_crm.yja_service', ['mos_ser_id' => '@ser_id'])
			->join('money_crm.yj_user', ['u_id' => '@mon_u_id'])
		->join('money_crm.yja_paytype', ['ypt_id' => '@mon_ypt_id'])
		->leftJoin('money_crm._qg_filter_mon_id', ['filter_mon_id' => '@mon_id'])
		->where('mon_check1', 1)
		//->where('mon_check2', 1) 经理审核
		->where('mos_pay_money{!}', 0)
		->where($where)
		->order($order)
		;
		//统计 所有记录
		$itemRecords = $q->count('mos_id');
		mvc::runtimeAdd('统计 所有记录');

		//统计 mon_id
		//$arr_mon_id = $q->distinct('mon_id')->column('mon_id')->page($page, $pagesize)->all() ?: [0];
		$arr_mon_id = $q->distinct('mon_id')->column('mon_id')->all() ?: [0];
		mvc::runtimeAdd('统计 mon_id');

		//取结果
		$q->clearFields()->clearLimit();
		//$map = $q->where('mon_id', $arr_mon_id)->map('mon_id', true)->all();
		$map = $q->map('mon_id', true)->all();
		mvc::runtimeAdd('取结果');

		//dd($q->sql());
		//是否是已生成的凭证
		$fromMap = (new sqler($this->logic->db))
				->table('money.voucher')
				->where('v_from', 'crm')
				->and('v_from_id', $arr_mon_id)
				->group('v_from_id')
				->map('v_from_id',['v_cycle','v_seq'])
				->all();
		$arr_from_id = array_keys($fromMap);
		//过滤弃用的mon_id
		$filterArr = [];
		foreach ($map as $mon_id => $rows) {
			foreach($rows as $row){
				if($row['filter_mon_id']) $filterArr[$row['filter_mon_id']] = true;
			} 
		}
		mvc::runtimeAdd('过滤弃用的mon_id');

		//转凭证结构
		$data = [];
		foreach ($map as $mon_id=>$rows) {
			$items = $this->crmRowToVoucherRow($rows, $this->nextId);
			foreach ($items as $v) {
				$v['filter'] =  isset($filterArr[$v['v_seq']]);
				$v['iscreate'] = in_array($v['v_seq'], $arr_from_id) ? 1 : 0;
				$v['v_cycle'] = !$v['iscreate'] ? $v['v_cycle'] : $fromMap[$v['mon_id']]['v_cycle'];
				$v['v_seq'] = !$v['iscreate'] ? $v['v_seq'] : $fromMap[$v['mon_id']]['v_seq'];
				array_push($data, $v);
			}
		}
		//dd($data);
		mvc::runtimeAdd('转凭证结构');
		if($formatNewVouvherRows) $this->formatNewVouvherRows($data);
		mvc::runtimeAdd('填充凭证显示内容');

		//查找没有进入凭证的记录
		$q2 = new sqler($this->logic->db);
		$q2->table('money_crm.yja_money')->join('money_crm.yja_money_ser', ['mon_id' => '@mos_mon_id'])->where('mon_check1', 1)->where($where);
		$serRows = $q2->all();
		$notFoundRows = [];
		$i=0;
		foreach($serRows as $serRow){
			$mon_id = $serRow['mon_id'];
			$mos_id = $serRow['mos_id'];
			$mapRows = isset($map[$mon_id]) ? $map[$mon_id] : [];
			$found = false;
			if($mapRows){
				if(false === array_search($mos_id, array_column($mapRows, 'mos_id'))){
					$found = false;
				}else{
					$found = true;
				}
			}else{
				$found = false;
			}
			if($found == false){
				foreach($serRow as $k=>$v){
					if(is_numeric($v) && strlen($v)>=10) $v = date("Y-m-d H:i:s");
					$serRow[$k] = $v;
				}					
				$_error = [];
				if(empty($serRow['mon_ypt_id'])){
					$_error[] = '未知的支付方式, mon_ypt_id = '. $serRow['mon_ypt_id'];
				}
				if($serRow['mos_pay_money']=='0.00') {
					$_error[] = '支付金额为 0 可能是退款也可能是异常 ';
				}
				$serRow[$i.'___ERROR'] = $_error;
				$i++;
				$notFoundRows[] = $serRow;
			}
		}

		$monRecourds = count($map);
		$data = [
			'page' => $q->page,
			'total' => $q->total,
			'records' => $monRecourds,
			'rows' => $data,
			'monRecourds'=> $monRecourds,
			'itemRecords' => $itemRecords,
			'pagesize' => $pagesize,
			'notFoundRows' => $notFoundRows,
		];
		//mvc::runtimeView();
		return $data;
	}


	/**
	 * crm 数据转凭证记录
	 *
	 * @return array
	 */
	public function crmRowToVoucherRow($rows):array
	{
		$items = [];

		$firstRow = reset($rows);
		$seq = $firstRow['mon_id'];
		//$subjectPrentId  = mb_substr($firstRow['ypt_name'],-2)=='现金' ? 10091 : 10092;
		$subjectPrentId  = $firstRow['ypt_type']=='现金账户' ? 10091 : 10092;
		
		//借
		$j_money = 0;
		foreach ($rows as $row) {
			$j_money += $row['mos_pay_money'] * 1;
		}
		$j_data = [
			'vid' => $this->nextId++,
			'seq' => $seq,
			'date' => $firstRow['mon_date'],
			'subjectPrentId' => $subjectPrentId,
			'subjectCrmKey' => $firstRow['mon_ypt_id'],
			'depCrmKey' => null,
			'userCrmKey' => null,
			'money' => $j_money,
			'client' => null,
			'summary' => $firstRow['mon_remark'],
			'state' => 0,
		];
		
		if(is_null($j_money) || $j_money == 0)return $items;

		$item = $this->logic->buildVoucherRow($j_data);
		if(empty($item)){
			dd('构建凭证失败',$firstRow,$j_data);
		}
		$item['mon_id'] = $row['mon_id'];
		$item['v_from_id'] = $row['v_from_id'];
		$items[] = $item;

		//贷
		//找父ID
		foreach($rows as $row){
			$tq = new sqler($this->logic->db);
			$subjectPrentId = '';
			if($row['ser_code']) {
				$subjectPrentId = $tq->table('object')->field('o_parent_id')->where('o_code', trim($row['ser_code']))->one();
			}
			$subjectPrentId = $subjectPrentId ?: 10094; //默认主营业务收入
			$d_data = [
				'vid' => $this->nextId++,
				'seq' => $seq,
				'date' => $row['mon_date'],
				'subjectPrentId' => $subjectPrentId,
				'subjectCrmKey' => $row['mos_ser_id'],
				'depCrmKey' => $row['u_dep_id'],
				'userCrmKey' => $row['u_name'] . $row['u_jobnum'] ?: '',
				'money' => $row['mos_pay_money'],
				'client' => $row['mon_customer_name'],
				'summary' => $row['mon_remark'],
				'state' => 0,
			];
			//dump($row, $subjectPrentId,$d_data);
			$item = $this->logic->buildVoucherRow($d_data);
			if (empty($item)) {
				dd('构建凭证失败', $row, $d_data);
			}
			$item['mon_id'] = $row['mon_id'];
			$item['v_from_id'] = $row['v_from_id'];
			$items[] = $item;
		}
		return $items;
	}

	public function formatNewVouvherRows(&$rows)
	{
		$subjects = [];
		$subjectKeywords = [];
		$objects = [];
		foreach ($rows as $row) {
			if ($row['v_subject'])  $subjects[$row['v_subject']] = '';
			if ($row['v_object_1']) $objects[$row['v_object_1']] = '';
			if ($row['v_object_2']) $objects[$row['v_object_2']] = '';
			if ($row['v_object_4']) $objects[$row['v_object_4']] = '';
		}
		if ($subjects) {
			$subjectKeys = array_keys($subjects);
			sort($subjectKeys);
			foreach ($subjectKeys as $oid) {
				$fullname = $this->dbRead->One("SELECT getObjectFullName(" . $oid . ")");
				$keyword = $this->dbRead->One("SELECT getObjectKeyword(" . $oid . ")");
				$subjects[$oid] = $fullname;
				$subjectKeywords[$oid] = $keyword;
			}
		}
		if ($objects) {
			$objKeys = array_keys($objects);
			sort($objKeys);
			$objects = $this->dbRead->Table("SELECT o_id,o_name,o_keyword FROM `object` where o_id in(" . implode(',', $objKeys) . ")");
			$objects = array_column($objects, null, 'o_id');
		}
		foreach ($rows as $i => $row) {
			if (isset($subjects[$row['v_subject']])) $row['subjectText'] = $subjects[$row['v_subject']];
			if (isset($subjectKeywords[$row['v_subject']])) $row['subjectKeyword'] = $subjectKeywords[$row['v_subject']];
			if (isset($objects[$row['v_object_1']])) {
				$row['depText'] = $objects[$row['v_object_1']]['o_name'];
				//$row['depKeyword'] = $objects[$row['v_object_1']]['o_keyword'];
			}
			if (isset($objects[$row['v_object_2']])) {
				$row['staffText'] = $objects[$row['v_object_2']]['o_name'];
				//$row['staffKeyword'] = $objects[$row['v_object_2']]['o_keyword'];
			}
			if (isset($objects[$row['v_object_4']])) {
				$row['clientText'] = $objects[$row['v_object_4']]['o_name'];
				//$row['clientKeyword'] = $objects[$row['v_object_2']]['o_keyword'];
			}
			$row['cycleseq'] = substr($row['v_cycle'],2).'-'. $row['v_seq'];
			$rows[$i] = $row;
		}
	}


	/**生成凭证 */
	function createVoucher($params)
	{
		$where = "mon_date >='" . strtotime($params['dateBegin']) . "' AND mon_date <='" . strtotime($params['dateEnd'] . ' 23:59:59') . "'";
		$data = $this->newVouvherList(false,$where,0,1000000, ['mon_date' => 'ASC', 'mon_id' => 'ASC']);
		if(empty($data) || empty($data['rows'])){
			return '没有找到任何数据';
		}
		$db = $this->logic->db;
		$db->begin();

		$cycleSeqArr = [];
		$arr_mon_id_seq = [];
		$insertQ = (new sqler())->table('voucher');
		foreach($data['rows'] as $i => $row){
			if($row['filter']===true || $row['filter']=='true'){
				continue; //过滤弃用记录
			}
			//已生成过的凭证处理
			if ($row['iscreate']){
				if(! $params['reCreate']){
					continue; //过滤已生成的记录, 如果没有重新生成标识的话
				}else{
					//如果重新生成，将删除未审核过的已生成的凭证
					$findQ = (new sqler($db))->table('voucher')
						->and('v_state{!}', 1)
						->and('v_cycle', $row['v_cycle'])
						->and('v_seq', $row['v_seq']);
					if(! $findQ->has() ){
						//如果没有找到，表示凭证是审核状态, 将不处理，需要反审核
						continue;
					}else{
						//如果凭证没有被审核则删除旧的凭证
						$db->delete($findQ);
					}
				}
			}

			$cycle = $row['v_cycle'];
			$mon_id = $row['mon_id'];
			if(isset($arr_mon_id_seq[$mon_id])){
				$seq = $arr_mon_id_seq[$mon_id];
			}else{
				//获取当月下一个期号
				if (!isset($cycleSeqArr[$cycle])) {
					$seq = $this->logic->getMaxCycleByYearMonth($cycle) + 1;
				} else {
					$seq = $cycleSeqArr[$cycle] + 1;
				}
				$cycleSeqArr[$cycle] = $seq;
				$arr_mon_id_seq[$mon_id] = $seq;
			}

			$copyKeys=['v_cycle','v_year', 'v_date', 'v_subject', 'v_j', 'v_d', 'v_direction'
						, 'v_object_1', 'v_object_2', 'v_object_4','v_client', 'v_summary'
			];
						
			$newItem = [];
			foreach($row as $k=>$v){
				if(in_array($k, $copyKeys)){
					$newItem[$k] = $v;
				}
			}
			$newItem['v_seq'] = $seq;
			$newItem['v_state'] = $params['state'];
			$newItem['v_client'] = $row['v_client'] ?: '';
			$newItem['v_from'] = 'crm';
			$newItem['v_from_id'] = $mon_id;
			$insertQ->push($newItem);
			unset($data['rows'][$i]); //节省内存
		}//$data['rows'] END
		if(!$insertQ->hasLots()){
			return '没有符合生成条件的凭证';
		}
		//dd($insertQ);
		$db->insert($insertQ);
		$db->end();
		return '1';
	}


	/**************** 支出凭证 ************************************************************************** */

	public function outPayList($formatNewVouvherRows = true, $where = '', $page, $pagesize = 1500, $order = null)
	{
		$order = $order ?: ['pay_date' => 'DESC', 'pay_id' => 'DESC'];
		$q = new sqler($this->logic->db);
		$tq = new sqler($this->logic->db);
		//构建
		$q->table('money_crm.out_payment') 
			->join('money_crm.out_items', ['pay_ois_id' => '@ois_id'])
			->join('money_crm.out_payment_detail', ['pay_id' => '@pam_pay_id'])
			->join('money_crm.out_payment_links', ['pay_id' => '@pls_pay_id'])
			->join('money_crm.yja_paytype', ['pam_ypt_id' => '@ypt_id'])
			->join('money_crm.yja_department', ['pls_department' => '@dep_name'])
			//->where('pay_status', 1) //审核
			->where('pay_amount{!}', 0)
			->where($where)
			->order(['pay_date'=>'DESC', 'pls_pay_id' => 'DESC']);
		$rows = $q->map('pay_id')->all(); // out_payment_links 有重复记录
		dd($this->$q->sql());
		//统计 所有记录
		$records = count($rows);
		mvc::runtimeAdd('统计 所有记录');
		//转凭证结构
		$data = [];
		$fromIdArr = [];
		foreach ($rows as $i => $row) {

			$time = strtotime($row['pay_date']);
			$seq = str_pad($row['pay_id'],5,'0',STR_PAD_LEFT);
			//找父ID
			$subjectPrentId = $tq->table('object')->field('o_parent_id')->where('o_code',trim($row['ois_code']))->one();
			if(empty($subjectPrentId)){
				dd('构建凭证失败, 未找到此编码 ', $row['ois_code']);
			}
			$j_data = [
				'vid' => $this->nextId++,
				'seq' => $seq,
				'date' => date('Y-m-d', $time),
				'subjectPrentId' => $subjectPrentId,
				'subjectCrmKey' => $row['pay_ois_id'],
				'depCrmKey' => $row['dep_id'],
				'userCrmKey' => $row['pls_users'] . $row['pls_users_nums'] ?: '',
				'money' => $row['pay_amount'],
				"client" => $row['pay_customer'],
				'summary' => $row['pay_remark'],
				'direction'=> 1,
				'state' => 0,
			];

			$item = $this->logic->buildVoucherRow($j_data);
			if (empty($item)) {
				dd('构建凭证失败', $row, $j_data);
			}
			$item['group_id'] = '';
			$item['from_id'] = $row['pay_id'];
			$data[] = $item;

			//贷
			switch ($row['ypt_type']) {
				case '银行账户':
					$subjectPrentId = 10092; //银行存款
					break;
				case '现金账户':
					$subjectPrentId = 10091; //库存现金
					break;
				
			}

			$d_data = [
				'vid' => $this->nextId++,
				'seq' => $seq,
				'date' => date('Y-m-d', $time),
				'subjectPrentId' => $subjectPrentId, //主营业务收入
				'subjectCrmKey' => $row['pam_ypt_id'],
				'depCrmKey' => $row['dep_id'],
				'userCrmKey' => $row['pls_users'] . $row['pls_users_nums'] ?: '',
				'money' => $row['pay_amount'],
				"client" => $row['pay_customer'],
				'summary' => $row['pay_remark'],
				'direction' => 0,
				'state' => 0,
			];
			$item = $this->logic->buildVoucherRow($d_data);
			if (empty($item)) {
				dd('构建凭证失败', $row, $d_data);
			}
			$item['group_id'] = '';
			$item['from_id'] = $row['pay_id'];

			$fromIdArr[$item['from_id']] = true;
			$data[] = $item;
		}
		$from = 'crm-outpay';
		//是否是已生成的凭证
		if($fromIdArr){
			$fromMap = (new sqler($this->logic->db))
				->table('money.voucher')
				->where('v_from', $from)
				->and('v_from_id', array_keys($fromIdArr))
				->group('v_from_id')
				->map('v_from_id', ['v_cycle', 'v_seq'])
				->all();
		}else{
			$fromIdArr = [];
		}
		foreach($data as $k=>$v){
			$fromId = $v['form_id'];
			$v['from'] = $from;
			$v['filter'] =  false;
			$v['iscreate'] = false;

			if(isset($fromMap[$v['from_id']])){
				$v['iscreate'] = true;
				$v['v_cycle'] = $fromMap[$v['from_id']]['v_cycle'];
				$v['v_seq'] = $fromMap[$v['from_id']]['v_seq'];
			}
			$data[$k] = $v;
		}
		//dd($data);

		mvc::runtimeAdd('转凭证结构');
		if ($formatNewVouvherRows) $this->formatNewVouvherRows($data);
		mvc::runtimeAdd('填充凭证显示内容');

		$data = [
			'page' => 1,
			'total' => 1,
			'records' => $records,
			'rows' => $data,
			'itemRecords'=> count($data),
			'pagesize' => $pagesize,
		];
		//mvc::runtimeView();
		return $data;
	}

	/**生成凭证2 */
	function createVoucher2($params, $function)
	{
		$where = "pay_date >='" . $params['dateBegin'] . "' AND pay_date <='" . $params['dateEnd'] . ' 23:59:59' . "'";
		$data = call_user_func_array([$this, $function], [false, $where, 0, 1000000, ['pay_date' => 'ASC', 'pay_id' => 'ASC']]);
		//$data = $this->outPayList(false, $where, 0, 1000000, ['pay_date' => 'ASC', 'pay_id' => 'ASC']);
		if (empty($data) || empty($data['rows'])) {
			return '没有找到任何数据';
		}
		$db = $this->logic->db;
		$db->begin();
		$cycleSeqArr = [];
		$arr_from_id_seq = [];
		$insertQ = (new sqler())->table('voucher');
		foreach ($data['rows'] as $i => $row) {
			if ($row['filter'] === true || $row['filter'] == 'true') {
				continue; //过滤弃用记录
			}
			//已生成过的凭证处理
			if ($row['iscreate']) {
				if (!$params['reCreate']) {
					continue; //过滤已生成的记录, 如果没有重新生成标识的话
				} else {
					//如果重新生成，将删除未审核过的已生成的凭证
					$findQ = (new sqler($db))->table('voucher')
					->and('v_state{!}', 1)
						->and('v_cycle', $row['v_cycle'])
						->and('v_seq', $row['v_seq']);
					if (!$findQ->has()) {
						//如果没有找到，表示凭证是审核状态, 将不处理，需要反审核
						continue;
					} else {
						//如果凭证没有被审核则删除旧的凭证
						$db->delete($findQ);
					}
				}
			}

			$cycle = $row['v_cycle'];
			$from_id = $row['from_id'];
			if (isset($arr_from_id_seq[$from_id])) {
				$seq = $arr_from_id_seq[$from_id];
			} else {
				//获取当月下一个期号
				if (!isset($cycleSeqArr[$cycle])) {
					$seq = $this->logic->getMaxCycleByYearMonth($cycle) + 1;
				} else {
					$seq = $cycleSeqArr[$cycle] + 1;
				}
				$cycleSeqArr[$cycle] = $seq;
				$arr_from_id_seq[$from_id] = $seq;
			}

			$copyKeys = [
				'v_cycle', 'v_year', 'v_date', 'v_subject', 'v_j', 'v_d', 'v_direction', 'v_object_1', 'v_object_2', 'v_object_4', 'v_client', 'v_summary'
			];

			$newItem = [];
			foreach ($row as $k => $v) {
				if (in_array($k, $copyKeys)) {
					$newItem[$k] = $v;
				}
			}
			$newItem['v_seq'] = $seq;
			$newItem['v_state'] = $params['state'];
			$newItem['v_client'] = $row['v_client'] ?: '';
			$newItem['v_from'] = $row['from'];
			$newItem['v_from_id'] = $from_id;
			$insertQ->push($newItem);
			unset($data['rows'][$i]); //节省内存
		} //$data['rows'] END
		if (!$insertQ->hasLots()) {
			return '没有符合生成条件的凭证';
		}
		//dd($insertQ);
		$db->insert($insertQ);
		$db->end();
		return '1';
	}
}

