<?php

namespace App\Http\Controllers\Admin;

    use App\Model\Adminuser;
    use App\Model\Tablelist;
    use Illuminate\Support\Facades\Crypt;
    use Illuminate\Support\Facades\Input;
    use Illuminate\Support\Facades\Validator;
    use Session;
    class IndexController extends CommonController{
        public function index()
        {
            $data = Tablelist::orderby('id','asc')->paginate(10);
            return view('admin.index',compact('data'));
        }

//        登陆
        public function login()
        {
            if($input = Input::all())
            {
                $user = Adminuser::first();
                if($input['user_name']!=$user->name || $input['user_pswd']!=Crypt::decrypt($user->pswd)){
                    return back()->with('msg','账号或密码错误！');
                }
                session(['user'=>$user]);
                return redirect('/');
            }else{
                session(['user'=>null]);
                return view('admin.login');
            }
        }

//        管理员修改自己密码
        public function change_pswd()
        {
            return view('admin.change_pswd');
        }
        public function pswd()
        {
            if($input = Input::all()){

                $rules = [
                    'pswd_n'=>'required|between:6,20|confirmed',
                ];
                $msg = [
                    'pswd_n.required'=>'新密码不能为空！',
                    'pswd_n.between'=>'新密码必须在6-20 位！',
                    'pswd_n.confirmed'=>'新密码前后输入不一致！',
                ];
                $validator = Validator::make($input,$rules,$msg);

                if($validator->passes()){
                    $user = Adminuser::first();
                    $_pswd = Crypt::decrypt($user->pswd);
                    if($input['pswd_o']==$_pswd){
                        $user->pswd = Crypt::encrypt($input['pswd_n']);
                        $user->save();
                        return back()->with('errors','密码修改成功！');
                    }else{
                        return back()->with('errors','原密码错误!');
                    }
                }else{
                    return back()->withErrors($validator);
                }
            }
            else{
                return view('admin.change_pswd');
            }
        }

//        登出
        public function out()
        {
            session(['user'=>null]);
            return redirect('/');
        }

    }