<?php
/**
 * register emlog
 * @package EMLOG
 * @link https://www.emlog.net
 */

/**
 * @var string $action
 * @var object $CACHE
 */

require_once 'globals.php';

if (empty($action)) {

    $br = '<a href="./">控制台</a><a><cite>正版授权</cite></a>';

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;
    $domain = getDomain();
    $sql = "select * from {$db_prefix}authorization where domain='{$domain}'";
    $res = $db->once_fetch_array($sql);
    $emkey =  empty($res) ? false : $res['emkey'];

    include View::getAdmView('header');
    require_once(View::getAdmView('auth'));
    include View::getAdmView('footer');
    View::output();
}

if ($action === 'auth') {
    $emkey = Input::postStrVar('emkey');
    if (empty($emkey)) {
        output::error('请输入授权码');
    }
    $r = Register::doReg($emkey);


    if($r['code'] == 200){

        $emkey_type = $r['data'];

        $db = Database::getInstance();
        $db_prefix = DB_PREFIX;
        $domain = getDomain();

        $sql = "INSERT INTO `{$db_prefix}authorization` (`emkey`, `domain`, `type`) VALUES ('{$emkey}', '{$domain}', '{$emkey_type}');";

        $db->query($sql);

        output::ok();
    }else{
        output::error($r['msg']);
    }

    if ($r === false) {
        output::error('授权码错误或请求授权失败，请重试');
    }

    output::ok();
}
