<?php

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

class User extends Api_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	
	public function __construct()
	{
		parent::__construct();
		$this->load->model('User_model');
	}

	/**
	 * [card card用户信息]
	 * @return [type] [json]
	 */
	
	public function card()
	{

		if(!$this->user->checkLogin()){
			$this->json(10, '用户未登录');
		}
		$this->json(0, '成功', array());
	}

	/**
	 * [cardcreate 五折卡申请]
	 * @return [json  data] [json格式状态码]
	 */
	public function cardcreate()
	{
  

		if(!$this->user->checkLogin()){
			$this->json(10, '用户未登录');
		}
		$this->load->model('user_model');
		$userinfo = $this->user_model->getByUid($this->user->uid);

		if(!empty($userinfo)){
			$this->json(550, '用户已经开过卡');
		}

		$rules_config = array(
			array(
		        'field' => 'realname',
		        'label' => '真实姓名',
		        'rules' => 'trim|required'
		    ),
		    array(
		        'field' => 'tel',
		        'label' => '手机号码',
		        'rules' => 'trim|required|regex_match[/^1[34578]\d{9}$/]',
		        'errors' => array('regex_match' => '手机号码错误')
		    )
		);

		$this->load->library('form_validation', $rules_config);
		$this->form_validation->set_data($_POST);

		if(!$this->form_validation->run())
	    {
			$this->json('50', strip_tags($this->form_validation->error_string()));	    	
	    }

	    if($this->User_model->checkCardInfo('user',$this->user->username)){
	    	$this->json('21', '已经激活');
	    }



  

		$getdata = array(
    		'uid' =>$this->user->uid,
    		'username' => $this->user->username,
    		'realname' => $this->input->post('realname',TRUE),
    		'opencard_time' => time(),
    		'sex' => intval($this->input->post('sex')),
    		'age' => intval($this->input->post('age')),
    		'tel' => $this->input->post('tel')
    	);

    	if(!$this->User_model->saveCardInfo($getdata))
    	{
    		$this->json('500', '错误');
    	}
    	else
    	{
	    	$this->json('0', '成功');		    		
    	}					

    
		
	}


	public function createOrder(){
		if(!$this->user->checkLogin()){
			$this->json(10, '没有登录');
		}
		$id = intval($this->input->post('price_id'));

		$this->load->model('Price_model', 'price');
		$price_info = $this->price->getById($id);

		if(empty($price_info)){
			$this->json('550', 'price_info error');
		}

		$duration = $price_info['duration']; 
		$amount = $price_info['price'] * 100;

		$this->load->model('cardorder_model', 'order');
		$ordernumber = $this->order->createOrder(CardOrder_Model::MONEY, $duration, $this->user->uid, CardOrder_Model::WAIT, $amount);

		$data['duration'] = $duration;
		$data['amount'] = $amount;
		$data['ordernumber'] = $ordernumber;

		$this->json('0', 'success', $data);


	}


	public function pay(){
		$ordernumber = $this->input->post('order_no');
		$channel = $this->input->post('channel');
		$this->load->model('cardorder_model', 'order');
		$orderinfo = $this->order->getByOrdernumber($ordernumber);

		if(empty($orderinfo)){
			$this->json('550', 'ordernumber error');
		}

		$this->load->library('ping');
		$charge = $this->ping->createCharge($ordernumber, $orderinfo['amount'], $channel, '卡片购买', '激活');
		$result = $this->ping->request();


	    $json = json_decode($result);
	    if(isset($json->error) && $json->error->type == 'channel_error')
	    {
	        $file = fopen("log.txt","a+");

	        $str = $json->error->type."\n".$json->error->message."\n".$json->error->code."\n".date('Y-m-d H:i:s',time())."\n";
	        fputs($file,$str);
	        fclose($file);
	        echo $result;
	        exit;
	    }


		$this->order->updateOrderStatus($ordernumber, CardOrder_Model::WAITPAY, $channel);
		echo $result;
		exit;
	}


	public function code(){

		$code = $this->input->post('code');

		

		if(!$this->user->checkLogin('')){
			$this->json(10, '没有登录');
		}

		$this->load->model('code_model');

		$code = $this->code_model->getCode($code);

	

		if(!$code){
			$this->json(557, '激活失败,兑换码不存在');
		}

		if($code['status'] == 2){
			$this->json(558, '兑换码已经被使用');
		}

		if(time() > strtotime('+'.$code['expires'].' month', $code['create_time'])){
			$this->json(559, '兑换码过期');
		}
		
		$this->load->model('cardorder_model', 'order');
		$ordernumber = $this->order->createOrder(CardOrder_Model::CODE, $code['duration'], $this->user->uid, CardOrder_Model::WAIT);
		$this->code_model->useCode($code['code'], $this->user->username, $ordernumber);
		$this->user->buy($code['duration'], $ordernumber, 0, CardOrder_Model::CODE);

		$info = $this->user->getUserInfo();
		$this->json('0', 'success', $this->user->formatUserinfo($info));
	}


	public function card_record(){
		$this->load->model('cardorder_model');

		if(!$this->user->checkLogin()){
			$this->json(10, '没有登录');
		}

		$data = $this->cardorder_model->get_record($this->user->uid);


		$this->json(0, 'success', $data);

	}

	public function buy_record(){

		$page = intval($this->input->post('page'));
        $pagesize = intval($this->input->post('pagesize'));

        $page = $page < 1 ? 1 : $page;
        $pagesize = $pagesize < 1 ? 10 : $pagesize;

		if($page < 1){
			$this->json('550', 'page error');
		}

		if(!$this->user->checkLogin()){
			$this->json(10, '没有登录');
		}

		$start = ($page - 1) * $pagesize;
		$this->load->model('shoporder_model', 'shoporder');
		$data = $this->shoporder->getRecordByUid($this->user->uid, $start, $pagesize);
		$this->load->model('user_model');
		$userinfo = $this->user_model->getByUid($this->user->uid);
		$json['save_money'] = $userinfo['save_money'];
		$json['list'] = $data;

		$this->json(0, 'success', $json);
	}
}
