// Copyright (C) 2022 enoch@Laysense.com
// 
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
// 
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

<?php
namespace app\controller;

use support\Request;
use Webman\Captcha\CaptchaBuilder;
use support\View;

class login
{
    public function index(Request $request)
    {
        $msg=$request->get('msg', '');
        $to=$request->get('to', '/');
        View::assign('msg', $msg);
        View::assign('to', $to);
        return view('login');
    }
    
    public function check(Request $request)
    {
        $captcha = $request->post('code','0');
        // 对比session中的captcha值
        if (strtolower($captcha) !== $request->session()->get('captcha')) {
            return redirect('/login?msg=验证码错误');
        }
        $name = $request->post('name','0');
        $password = $request->post('password','0');
        if($name==getenv('admin') && $password==getenv('password')){
            $session = $request->session();
            $session->set('userinfo', 'admin');
            $to = $request->post('to','/admin');
            return redirect("$to");
        }else{
            return redirect('/login?msg=账号密码错误');
        }


        return response('错误');
    }

    public function captcha(Request $request)
    {
        // 初始化验证码类
        $builder = new CaptchaBuilder;
        // 生成验证码
        $builder->build();
        // 将验证码的值存储到session中
        $request->session()->set('captcha', strtolower($builder->getPhrase()));
        // 获得验证码图片二进制数据
        $img_content = $builder->get();
        // 输出验证码二进制数据
        return response($img_content, 200, ['Content-Type' => 'image/jpeg']);
    }

}