<?php
ob_start();
session_start();

$str_pin = str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
$_SESSION['pin'] = $str_pin;

if( !isset($_POST['account']) || !isset($_POST['password']) || !isset($_POST['valid_code']) || !( $static_str_account = trim($_POST['account']) ) || !( $static_str_valid_code = trim($_POST['valid_code']) ) )
	exit(json_encode(array('ErrCode'=>-1, 'ErrMessage'=>'輸入資料不足', 'RedirectURL'=>'')));
else if( !preg_match('/^\d{4}$/', $static_str_valid_code) )
	exit(json_encode(array('ErrCode'=>-1, 'ErrMessage'=>'輸入資料不正確', 'RedirectURL'=>'', 'ValidPin'=>$str_pin)));
else if( !isset($_SESSION['pass_key']) || $static_str_valid_code != $_SESSION['pass_key'] )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'驗證碼不正確，請重新輸入', 'RedirectURL'=>'', 'ValidPin'=>$str_pin)));
else
{
	$static_str_password = $_POST['password'];

	unset($_SESSION['pass_key']);
}

require_once('includes/common.php');

require_once('includes/author.php');
$obj_class_author = new class_author();

if( !$obj_class_author->login($static_str_account, $static_str_password) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'帳號密碼不正確，無法登入', 'RedirectURL'=>'', 'ValidPin'=>$str_pin)));
else if( !( $str_init_url = $obj_class_author->get_init_url() ) )
	exit(json_encode(array('ErrCode'=>0, 'ErrMessage'=>'預設網頁錯誤或不存在', 'RedirectURL'=>'', 'ValidPin'=>$str_pin)));

exit(json_encode(array('ErrCode'=>1, 'ErrMessage'=>'', 'RedirectURL'=>$str_init_url, 'ValidPin'=>'')));
?>