<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class CardOrder_Model extends MY_Model {
    const CODE = 1;
    const MONEY = 2;

	const SUCCESS = 1;
    const WAIT = 3;
    const WAITPAY = 4;
    public $table = 'cardorder';


    public function __construct()
    {
        parent::__construct();
    }

    public function createOrder($type, $duration, $uid, $status,$amount = 0){

        $time = time();
        $start_time = $time;
        $end_time = strtotime('+'.$duration.' day', $time);

        $data['start_time'] = $start_time;
        $data['end_time'] = $end_time;
        $data['type'] = $type;
        $data['duration'] = $duration;
        $data['uid'] = $uid;
        $data['status'] = $status;
        $data['ordernumber'] = $this->createOrderNUmber();
        $data['create_time'] = $time;
        //$data['channel'] = $channel;
        $data['amount'] = $amount;
        $this->db->insert($this->table, $data);
        return $data['ordernumber'];

    }

    private function createOrderNUmber(){
        return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    public function updateOrderStatus($ordernumber, $status, $channel = ''){
        $this->db->where('ordernumber', $ordernumber);
        $data['status'] = $status;
        if(!empty($channel)){
            $data['channel'] = $channel;
        }
        $this->db->update($this->table, $data);
    }


    public function getByOrdernumber($ordernumber){
        $this->db->where('ordernumber', $ordernumber);
        return $this->db->get($this->table)->row_array();
    }

    public function insert($data){
        $data['ordernumber'] = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        $data['create_time'] = time();
        $this->db->insert($this->table, $data);
    }


    public function get_record($uid){
    	$this->db->where('uid', $uid);
    	$this->db->where('status', self::SUCCESS);
        $this->db->order_by('create_time', 'desc');
    	$result = $this->db->get($this->table)->result_array();

    	if(empty($result)){
    		return array();
    	}

    	foreach($result as $row){
			$temp['start_time'] = date('Y-m-d H:i:s', $row['start_time']);
			$temp['end_time'] = date('Y-m-d H:i:s', $row['end_time']);
			$temp['type'] = $row['type'];
			$temp['duration'] = $row['duration'];
			$data[] = $temp;
		}

		return $data;
    }
}
/* End of file card_model.php */
/* Location: /application/models/card_model.php */