<?php
/**
 * Copy Right IJH.CC
 * Each engineer has a duty to keep the code elegant
 * $Id$
 */

if(!defined('__CORE_DIR')){
    exit("Access Denied");
}

class Mdl_Hongbao_Hongbao extends Mdl_Table
{   
  
    protected $_table = 'hongbao';
    protected $_pk = 'hongbao_id';
    protected $_cols = 'hongbao_id,title,need_amount,amount,uid,key,is_used,dateline,clientip,endline,usedline,usedip';
    protected $cd_key = 'hsoewocnsdl2479sdfew_12whf';






    public function create($data, $checked=false)
    {
        $num = $data['num'];
        if(!$checked && !$data = $this->_check_schema($data)){
            return false;
        }
        for ($i = 1; $i <= $num; $i++) {
                $datas[$i]['title'] = $data['title'];
                $datas[$i]['need_amount'] = $data['need_amount'];
                $datas[$i]['amount'] = $data['amount'];
                $datas[$i]['endline'] = $data['endline'];
                $datas[$i]['dateline'] = __CFG::TIME;
                $datas[$i]['clientip'] = __IP;
            }
            
            foreach ($datas as $key => $v) {
                $hongbao_id = $this->db->insert($this->_table, $v, true);
                $keys = md5($this->cd_key.$hongbao_id);
                $keys = substr($keys,10,10);
                $this->batch($hongbao_id,array('key'=>$keys));
            }
        return $hongbao_id;
    }
    
    
    public function add($data, $checked=false)
    {
        $uid = intval($data['uid']);
        if(!$checked && !$data = $this->_check_schema($data)){
            return false;
        }
        $data['uid'] = $uid;
        $hongbao_id = $this->db->insert($this->_table, $data, true);
        $keys = md5($this->cd_key.$hongbao_id);
        $keys = substr($keys,10,10);
        $this->batch($hongbao_id,array('key'=>$keys));
        return $hongbao_id;
    }
    
    
    public function update($val, $data, $checked=false)
    {
        if(isset($val) && !empty($data) && is_array($data)) {
            $uid = intval($data['uid']);
            $this->_checkpk();
            if(!$checked && !($data = $this->_check_schema($data, $val))){
                return false;
            }
            $data['uid'] = $uid;
            if($ret = $this->db->update($this->_table, $data, self::field($this->_pk, $val))){
                $this->clear_cache($val);
            }
            return $ret;
        }
        return false;
    }
    
    public function updates($hongbao_id,$data,$checked=false)
    {
        return $this->db->update($this->_table, $data, self::field($this->_pk, $hongbao_id));
    }
    
}