<?php
!defined('BASEPATH') && die('No direct script access allowed');

session_start();

class Account extends TRU_Controller
{
	function __construct() {
		header('Content-Type:text/html; charset=utf-8');
		parent::__construct();

        $this->load->library('user_agent');
        $this->is_mobile = $this->agent->is_mobile();
        $platform = $this->agent->mobile();
        ($platform == 'iPad') ? $this->is_mobile = FALSE : '';

        // 记录登录方式
        $login_type = uri('lt');
        if ($login_type) {
            $_SESSION['login_type'] = $login_type;
        }
	}

	function login() {
		if (isset($_POST['loginsubmit'])) {
			$username = p('username');
			$password = p('password');

			$ret = uc_user_login($username, $password);
			$uid = $ret[0];
			if ($uid > 0) {
				// 绑定QQ登录
				if (isset($_SESSION['qq_token']) && isset($_SESSION['qq_openid'])) {
					$this->db->from('iapps_new_connect');
					$this->db->where('uid', $uid);
					$this->db->where('contype', 'qq');
					if ($this->db->count_all_results()) {
						redirect('/account/login/', 3, '您的帐号已经绑定其它QQ帐号，请先解除绑定或使用其它帐号登录。');
					}
					$this->db->insert('iapps_new_connect', array('uid'=>$uid, 'contype'=>'qq', 'contoken'=>$_SESSION['qq_token'], 'conuid'=>$_SESSION['qq_openid']));
					unset($_SESSION['qq_token'], $_SESSION['qq_openid']);
				}
				// 绑定新浪微博登录
				if (isset($_SESSION['sina_token']) && isset($_SESSION['sina_uid'])) {
					$this->db->from('iapps_new_connect');
					$this->db->where('uid', $uid);
					$this->db->where('contype', 'sina');
					if ($this->db->count_all_results()) {
						redirect('/account/login/', 3, '您的帐号已经绑定其它新浪微博帐号，请先解除绑定或使用其它帐号登录。');
					}
					$this->db->insert('iapps_new_connect', array('uid'=>$uid, 'contype'=>'sina', 'contoken'=>$_SESSION['sina_token'], 'conuid'=>$_SESSION['sina_uid']));
					unset($_SESSION['sina_token'], $_SESSION['sina_uid']);
				}
				// 同步登录代码
				echo uc_user_synlogin($uid);
                                // 跳转到登陆之前的页面 或 首页
                                $redirect_url = p('redirect') ? p('redirect') : '/';
				echo '<meta http-equiv="refresh" content="1;url=' . $redirect_url . '" />';
				exit;
			} else {
				echo '登录失败';
			}
		}

		$result['url'] = c('url');
		// 获取跳转地址：先检测url、再检测Cookie
		$redirect_url = uri('redirect');
		$redirect_url = urldecode($redirect_url);
        if ($redirect_url) {
	        $result['redirect_url'] = $redirect_url;
        } else {
        	$result['redirect_url'] = isset($_SESSION['login_redirect_url']) ? $_SESSION['login_redirect_url'] : '/';
        }
        $result['iapps_config'] = $this->iapps_config;

        if($this->is_mobile) {
            $this->load->view('mobile/header/header', $result);
            $this->load->view('mobile/account/login', $result);
            $this->load->view('mobile/footer/footer', $result);
        } else {
		    $this->load->view('account/login', $result);
        }
	}

    function register() {
    	if (isset($_POST['regsubmit'])) {
    		$username = p('username');
    		$password = p('password');
    		$repassword = p('repassword');
    		$email = p('email');

    		$username = trim($username);
    		$password = trim($password);
    		$repassword = trim($repassword);
    		$email = trim($email);

    		if (empty($username)) {
    			redirect('/account/register/', 3, '用户名必须填写');
    		}
    		if (empty($password)) {
    			redirect('/account/register/', 3, '密码不能为空');
    		}
    		if ($password != $repassword) {
    			redirect('/account/register/', 3, '两次输入的密码不一致');
    		}
    		if (empty($email)) {
    			redirect('/account/register/', 3, '请填写您的电子邮箱');
    		}

	        // TODO 发起HTTP请求的方法最好封装成一个通用方法
	        $params = array(
	            'username' => $username,
	            'password' => $password,
	            'email' => $email,
	            'field1' => $username, // 用户昵称
	            'agreebbrule' => 'yes'
	        );

	        $ch = curl_init();
	        curl_setopt_array($ch, array(
	            CURLOPT_RETURNTRANSFER => true,
	            CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
	            CURLOPT_POST => true,
	            CURLOPT_POSTFIELDS => http_build_query($params),
	            CURLOPT_URL => 'http://bbs.iapps.im/opendz/index.php?mod=register'
	        ));
	        $result = curl_exec($ch);
	        curl_close($ch);

	        $result = json_decode($result, true);
	        if (null === $result) {
	            redirect('/account/register/', 3, '发生未知错误，请尝试重新注册');
	        }

	        if (isset($result['uid']) && $result['uid'] > 0) {
	        	if (isset($_SESSION['qq_token']) && isset($_SESSION['qq_openid'])) {
	        		$this->db->insert('iapps_new_connect', array('uid'=>$result['uid'], 'contype'=>'qq', 'contoken'=>$_SESSION['qq_token'], 'conuid'=>$_SESSION['qq_openid']));
	        	}
	        	if (isset($_SESSION['sina_token']) && isset($_SESSION['sina_uid'])) {
	        		$this->db->insert('iapps_new_connect', array('uid'=>$result['uid'], 'contype'=>'sina', 'contoken'=>$_SESSION['sina_token'], 'conuid'=>$_SESSION['sina_uid']));
	        	}
	        	// 同步登录代码
	        	echo uc_user_synlogin($result['uid']);
    			$callback_url = isset($_SESSION['login_redirect_url']) ? $_SESSION['login_redirect_url'] : '/';
				unset($_SESSION['login_redirect_url']);
	        	redirect($callback_url, 3, '注册成功，正在前往指定页面...');
	        } else {
	        	redirect('/account/register/', 3, '注册失败：'.$result['errmsg']);
	        }
    	}

        $result['url'] = c('url');
        $result['iapps_config'] = $this->iapps_config;

        if($this->is_mobile) {
            $this->load->view('mobile/header/header', $result);
            $this->load->view('mobile/account/register', $result);
            $this->load->view('mobile/footer/footer', $result);
        } else {
            $this->load->view('account/register', $result);
        }

    }

    /* 绑定页面 */
    function bind() {
    	if (!isset($_COOKIE['con_login_type']) || !isset($_COOKIE['con_auth'])) {
			redirect('javascript:history.back();', 3, '您还没有登录授权，请先登录授权');
    	}

    	if (isset($_POST['act'])) {
    		// 检测是否登录授权
    		$con_login_type = $_COOKIE['con_login_type'];
			$conuid = ayy_authcode($_COOKIE['con_auth']);
			$this->db->select('contoken');
			$this->db->from('iapps_new_connect_guest');
			$this->db->where('conuid', $conuid);
			$this->db->where('contype', $con_login_type);
			$query = $this->db->get();
			$contoken = $query->row_array()['contoken'];
			if (!$contoken) {
				redirect('javascript:history.back();', 3, '您还没有授权，无法绑定');
			}

			// 验证输入项
    		$username = p('username');
    		$password = p('password');
    		$act = p('act');
    		if (empty($username)) {
    			redirect('javascript:history.back();', 3, '用户名必须填写');
    		}
            $redirect_url = p('redirect') ? p('redirect') : '/';
    		if ($act == 1) { // 绑定已有账号
				
                if (empty($password)) {
                    redirect('javascript:history.back();', 3, '密码不能为空');
                }

				$ret = uc_user_login($username, $password);
				$uid = $ret[0];
				if ($uid > 0) {
					// 验证账号是否已经绑定过
    				$this->db->from('iapps_new_connect');
					$this->db->where('uid', $uid);
					$this->db->where('contype', $con_login_type);
					if ($this->db->count_all_results()) {
						redirect('javascript:history.back();', 3, '该的帐号已经绑定过了');
					}
					$this->db->insert('iapps_new_connect', array('uid'=>$uid, 'contype'=>$con_login_type, 'contoken'=>$contoken, 'conuid'=>$conuid));
					$this->db->delete('iapps_new_connect_guest', array('conuid' => $conuid, 'contype' => $con_login_type));
					
			    	setcookie("con_login_type", "", time() - 3600, "/");
			    	setcookie("con_auth", "", time() - 3600, "/");

					// 同步登录代码
					echo uc_user_synlogin($uid);

                    if ($_SESSION['login_type'] == 'app') {
                        echo '<script type="text/javascript">location.href = "jscall://synlogin/' . $uid . '";</script>';
                        exit;
                    }

					unset($_SESSION['login_redirect_url']);
    				redirect($redirect_url, 1, '登录成功');
				} else {
    				redirect('javascript:history.back();', 3, '用户名或密码错误，导致绑定失败');
				}

    		} else if ($act == 2) { // 绑定新账号

    			// $confirm_password = p('confirm_password');
    			$email = p('email');
				// if ($password != $confirm_password) {
	    		// 	redirect('javascript:history.back();', 3, '两次输入的密码不一致');
	    		// }
				if (empty($email)) {
	    			redirect('javascript:history.back();', 3, '请填写您的电子邮箱');
	    		}

	    		// 注册新账号

                $password = md5(rand(100, 9999));

	    		$params = array( 'username' => $username, 'password' => $password, 'email' => $email, 'field1' => $username, 'agreebbrule' => 'yes' );
		        $ch = curl_init();
		        curl_setopt_array($ch, array(
		            CURLOPT_RETURNTRANSFER => true,
		            CURLOPT_USERAGENT => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0',
		            CURLOPT_POST => true,
		            CURLOPT_POSTFIELDS => http_build_query($params),
		            CURLOPT_URL => 'http://bbs.iapps.im/opendz/index.php?mod=register'
		        ));
		        $result = curl_exec($ch);
		        curl_close($ch);

		        $result = json_decode($result, true);
		        if (null === $result) {
		            redirect('javascript:history.back();', 3, '遇到未知错误，请尝试重新提交');
		        }
			    if (isset($result['uid']) && $result['uid'] > 0) {
					$this->db->insert('iapps_new_connect', array('uid'=>$result['uid'], 'contype'=>$con_login_type, 'contoken'=>$contoken, 'conuid'=>$conuid));
			    	$this->db->delete('iapps_new_connect_guest', array('conuid' => $conuid, 'contype' => $con_login_type));
					
			    	setcookie("con_login_type", "", time() - 3600, "/");
			    	setcookie("con_auth", "", time() - 3600, "/");

		        	// 同步登录代码
		        	echo uc_user_synlogin($result['uid']);

                    if ($_SESSION['login_type'] == 'app') {
                        echo '<script type="text/javascript">location.href = "jscall://synlogin/' . $result['uid'] . '";</script>';
                        exit;
                    }

					unset($_SESSION['login_redirect_url']);
		        	redirect($redirect_url, 3, '登录成功');
		        } else {
		        	redirect('javascript:history.back();', 3, '新账号注册失败：【' . $result['errmsg']. '】');
		        }

    		}
    	}

    	// 获取回调页面
    	$redirect_url = uri('redirect');
    	$redirect_url = urldecode($redirect_url);
    	if (empty($redirect_url)) {
    		$redirect_url = isset($_SESSION['login_redirect_url']) ? $_SESSION['login_redirect_url'] : '/';
    	}

    	$contype = $_COOKIE['con_login_type'];
    	$conuid = $_COOKIE['con_auth'];
    	$conuid = ayy_authcode($conuid);

    	$this->db->select('connick,conuid');
    	$this->db->from("iapps_new_connect_guest");
    	$this->db->where('conuid', $conuid);
    	$this->db->where('contype', $contype);
    	$query = $this->db->get();
    	if (!$query->num_rows()) {
			header("Location:{$redirect_url}");
    		exit;
    	}
    	$row = $query->row_array();
		
		switch ($contype) {
		 	case 'qq':
		 		$avatar = 'http://q.qlogo.cn/qqapp/100529160/' . $row['conuid'] . '/100';
		 		break;
		 	case 'sina':
		 		$avatar = 'http://tp1.sinaimg.cn/' . $row['conuid'] . '/180/0/1';
		 		break;
		} 
		$result['url'] = c('url');
		$result['con_avatar'] = $avatar;
		$result['con_nickname'] = $row['connick'];
		$result['redirect_url'] = $redirect_url;
		$result['iapps_config'] = $this->iapps_config;
		if ($this->is_mobile) {
			$this->load->view('mobile/header/header', $result);
            $this->load->view('mobile/account/bind_view', $result);
            $this->load->view('mobile/footer/footer', $result);
		} else {
			$this->load->view('account/bind_view', $result);
		}
		
    }

    /* 退出游客状态 */
    function bind_out() {
    	setcookie("con_login_type", "", time() - 3600, "/");
    	setcookie("con_auth", "", time() - 3600, "/");
		redirect('/', 1, '退出成功');
    }
}
?>