<?php
namespace app\index\controller;

use \think\Controller;
use \think\Request;
use \think\Session;
use \think\Config;
use \think\Cache;
class Panel extends Controller
{
	protected $request;
	protected static $account;
	private static $uif;
	 
	
    
	public function __construct(Request $request)
    {
		parent::__construct();
		self::$account = \app\index\model\Account::instance();
		if(!Session::has('unique_id')){
			$this->redirect('index/account/login',302);
		}
		self::$uif['unique_id'] = Session::get('unique_id');
		if(!self::$uif = self::$account->findUser(self::$uif['unique_id'],'unique_id')){
			$this->redirect('index/account/login',302);
		}
    	$this->request = $request;
		
    }
	
	public function index(){
		$data = [
			'act'=>'user_lookup',
			// 'user_key'=>Session::get('user_key'),
			'unique_id'=>self::$uif['unique_id'],
			'cloudflare_email'=>self::$uif['email'],
		];
		$return = performRequest($data);
		$return = returnCheck($return);
		if(!is_array($return)){
			return $this->error($return);
		}
		$domain = $return["response"]["hosted_zones"];
		$this->assign('domain',$domain);
		return $this->fetch();
	}
	
	public function adddomain(){
		
		if($this->request->isPost()){
			if(!$this->request->has('zone_name','param')){
				return $this->error('没有设置主域!');
			}
			$zone = $this->request->post('zone_name'); //取主域
			$domain = \app\index\model\Domain::instance();
			if($domain->getEarliestHost($zone)){
				return $this->error('这个域名已经被别人使用了!');
			}
			$data = [
				'act'=>'zone_set',
				'user_key'=>Session::get('user_key'),
				'zone_name'=>$zone,
				'subdomains'=>'',
			];
			$sqlData = [];
			$sub = [];
			$sub['type'] = $this->request->post('type/a');
			$sub['sub'] = $this->request->post('sub/a');
			$sub['record'] = $this->request->post('record/a');
			foreach($sub['type'] as $key=>$val){
				if(!$sub['type'][$key] || !$sub['sub'][$key] || !$sub['record'][$key]){
					unset($sub['type'][$key],$sub['sub'][$key],$sub['record'][$key]);
					continue;
				}
				//当为泛域名时跳过(不允许添加泛域名)
				if($sub['sub'][$key] =='*'){
					continue;
				}
				$recordData = [];
				$recordData['unique_id'] = Session::get('unique_id');
				$recordData['domain'] = $zone;
				$recordData['sub'] = $sub['sub'][$key];
				if($val == "A"){
					if(!recordChick($sub['record'][$key],'A')){
						return $this->error("子域名{$sub['sub'][$key]}的值不是一个IP!");
					}
					if(!$cif = ip2cname($sub['record'][$key])){
						return $this->error("转换子域名{$sub['sub'][$key]}时出现错误!");
					}
					$recordData['type'] = 'A';
					$recordData['ip'] = $sub['record'][$key];
					if(!$cif){
						return $this->error("子域{$sub['sub'][$key]}在设置解析时发生错误,请联系管理员!");
					}else{
						$sub['record'][$key] = $cif['cname']; //使用cname覆盖原来的解析ip
						$recordData['cname'] = $sub['record'][$key];
						$recordData['record_id'] = $cif['record_id'];
					}
				}elseif($val == "CNAME"){
					$recordData['type'] = 'CNAME';
					$recordData['ip'] = null;
					$recordData['cname'] = $sub['record'][$key];
					$recordData['record_id'] = null;
				}else{
					return $this->error('模式错误,我们只支持A模式和CNAME模式.');
				}

				if($sub['sub'][$key] == '@'){
					$data['resolve_to'] = $recordData['cname'];
					$sqlData['_www'] = $recordData;
					$sqlData['_www']['sub'] = 'www';
				}else{
					$data['subdomains'] .= "{$recordData['sub']}:{$sub['record'][$key]},"; 
				}
				$sqlData[] = $recordData;
				
				unset($recordData);
			}
			$data['subdomains'] = substr($data['subdomains'], 0, -1);
			$return = performRequest($data);
			$return = returnCheck($return);
			if(!is_array($return)){
				return $this->error($return);
			}
			if(in_array('www',$sub['sub'])){
				unset($sqlData['_www']); //当子域包含www的时候删除默认值
			}
			$domain->addMultiDomainInfo($sqlData);
			return $this->success('域名添加成功','index/panel/index');
		}else{
			return $this->fetch();
		}
		
	}

	public function deldomain(){
		$zone = $this->request->param('domain');
		$data = [
			'act'=>'zone_delete',
			'user_key'=>Session::get('user_key'),
			'zone_name'=>$zone
		];
		$return = performRequest($data);
		$return = returnCheck($return);
		if(!is_array($return)){
			return $this->error($return);
		}
		$unique_id = Session::get('unique_id');
		$domain = \app\index\model\Domain::instance();
		$subList = $domain->delAllDomainInfo($zone);
		Cache::rm('cf_'.$zone);
		return $this->success('域名删除成功!');
	}


	//获取域名下的子域名
	private function getDomainList($zone){
		$data = [
			'act'=>'zone_lookup',
			'user_key'=>Session::get('user_key'),
			'zone_name'=>$zone,
		];
		$return = performRequest($data);
		$return = returnCheck($return);
		return $return;

	}

	private function getComodoSub($zone,$sub = true){
			if(!$lastDomain =Cache::get('comodo-'.$zone)){
				$lastDomain = $this->getDomainList($zone);
				if(!is_array($lastDomain)){
					return ['code'=>-1,'data'=>$this->error($return)];
				}
			}
			foreach($lastDomain['response']['hosted_cnames'] as $key=>$val){
				if(substr($val,-12) == 'comodoca.com'){//如果回源域名是comodo验证域
					Cache::set('comodo-'.$zone,$lastDomain); //取到comodo域名的时候缓存记录
					if($sub){
						$sub = substr($key,0,strlen($key) - strlen($zone) - 1);
						return ['code'=>1,'data'=>$sub.':'.$val];
					}else{
						$sub = substr($key,0,strlen($key) - strlen($zone) - 1);
						return ['code'=>1,'data'=>['sub'=>$sub,'record'=>$val]];
					}
					break;
				}
			}
			return ['code'=>0,'data'=>null];
	}
}