<?php
namespace app\index\controller;

use \think\Controller;
use \ think\Request;
use \think\Session;
use \think\Cache;
class Account extends Controller
{
	protected $request;
    
	public function __construct(Request $request)
    {
		parent::__construct();
    	$this->request = $request;
		
    }
    
	public function login(){
		if($this->request->isPost()){
			$data = [
				'act'=>'user_auth',
				'cloudflare_email'=>$this->request->post('account'),
				'cloudflare_pass'=>$this->request->post('passwd'),
				
			];

			$account = \app\index\model\Account::instance();
			$uif = $account->findUser($data['cloudflare_email']);

			if(!$uif){
				$data['unique_id'] = md5(time().rand(1,9999));
			}else{
				$data['unique_id'] = $uif['unique_id'];
			}
			$return = performRequest($data);
			$return = returnCheck($return);
			if(!is_array($return)){
				return $this->error($return);
			}
			
			if(!$uif){
				$uif = [
					'email'=>$return['response']['cloudflare_email'],
					'username'=>isset($return['response']['cloudflare_username'])?$return['response']['cloudflare_username']:null,
					'unique_id'=>$return['response']['unique_id'],
					'user_key'=>$return['response']['user_key'],
					'user_api_key'=>$return['response']['user_api_key']
				];
				$uif = $account->addUser($uif);
				$msg = "登录成功!,如果您是第一次登录,您将会受到一封cloudflare的邮件,您的账户将会和我们关联.";
			}else{
				$msg = "登录成功!.";
			}
			session::set('id',$uif['id']);
			session::set('unique_id',$uif['unique_id']);
			session::set('user_key',$return['response']['user_key']);
			session::set('user_api_key',$return['response']['user_api_key']);
			return $this->success($msg,'index/panel/index');
		}else{
			return $this->fetch();
		}
	}

	public function logout(){
		session::delete('id');
		session::delete('unique_id');
		session::delete('user_key');
		session::delete('user_api_key');
		$this->redirect('index/account/login',302);
	}
	
	
}