<?php

namespace Admin\Controller;
use Think\Controller;

class PublicController extends Controller{

    public function login(){
        $this->display();
    }

    /**
     * 检验登录信息
     */
    public function checkLogin(){
        /**检测用户名密码是否正确**/
        $username = I("username"," ","trim"); //接收用户名，并且使用trim函数去除首尾空格
        $password = I("password"," ","md5"); //接收密码，并且使用md5函数加密
        $return   = $this->checkPassword($username,$password);

        if(!$return){
            $res['status']  = 0;
            $res['message'] = '用户名或者密码错误!';
            $this->ajaxReturn($res);
        }else{
            $data = array(
                "loginip"  =>get_client_ip(),       //获取ip地址
                "logintime"=>date("Y-m-d H:i:s"),  //记录登陆日期
            );
            M("admin")->save($data);                 //增加数据
            session('admin_id', $return["id"]);     //将admin_id存入session
            session('admin_username', $return["username"]); //将admin_username存入session
            $res['status']  = 1;
            $res['message'] = '登录成功!';
            $this->ajaxReturn($res);
        }
    }


    /***
     * 检测用户名密码是否匹配
     * @param $username
     * @param $password
     * @return bool
     */
    public function checkPassword($username,$password){
        $map['username'] = $username;
        $admin = M('admin')->where($map)->find();
        if($admin['password'] === $password){
            return $admin;
        }else{
            return false;
        }
    }
    /**
     * 退出
     */
    public function logout(){
        session('admin_id',null);
        session('admin_username',null);
        $this->redirect("login");
    }



}
