<?php

// 启动文件
require_once __DIR__ . '/../core/bootstrap.php';

// 程序配置
$conf = include CONF . '/conf.php';

// 控制器
$con = new \sc\Controller(__DIR__ . '/page');

// 帮助类
$hel = new \sc\Helper();

if ($con->request->isAjax()) {
    // 登录验证
    $account = $con->request->post('username');

    $secret = $con->db->table('user')->find('u_ciphers')->where('u_account = ?', [$account])->one();

    if (false == $secret) {
        // 账号不存在
        $con->json(['err' => '账号或密码错误请重试']);
    } else {
        $submit = $con->request->post('password');
        if (secret_verify($submit, $secret['u_ciphers'])) {
            // 保存SESSION
            $index = base64_encode('sem-cms_manager_index');
            $account = base64_encode($account);
            $con->session->set($index, $account);
            // 保存COOKIE
            if ('1' == $con->request->post('remember')) {
                $host = $con->request->server('HTTP_HOST');
                $path = $con->request->server('REQUEST_URI');
                $path = substr($path, 0, strrpos($path, '/'));
                setcookie($index, $account, time() + 2592000, $path, $host, false, true);
            }
            // 记录登录时间,IP
            $account = base64_decode($account);
            $con->db->table('user')->update([
                'u_date' => date('Y-m-d H:i:s'),
                'u_ip' => ip2long($con->request->ip())
            ], 'u_account = ?', [$account])->row();
            // 跳转至首页
            $con->json(['url' => $hel->path() . '/']);
        } else {
            // 密码错误
            $con->json(['err' => '账号或密码错误请重试']);
        }
    }
} else {
    $index = base64_encode('sem-cms_manager_index');
    $index_session = $con->session->get($index);
    $index_cookie = $con->request->cookie($index);
    if (!empty($index_session) || !empty($index_cookie)) {
        // 提示信息
        $con->session->set('err', '您已登录，请勿重复登录');
        $con->redirect($hel->path() . '/');
    } else {
        // 登录页面
        $con->render('login', [
            'path' => $hel->path(),
            'msg'  => $con->session->remove('msg'),
            'err'  => $con->session->remove('err')
        ]);
    }
}

// 验证密码
function secret_verify($submit, $secret)
{
    $submit = base64_encode(md5(base64_encode(sha1($submit))));

    return $submit == $secret;
}
