<?php

namespace App\Http\Controllers\Cp\Manage;

use App\Http\Controllers\Controller;
use App\Modules\CpUser\Services\CpUserService;
use Illuminate\Http\Request;
use App\Modules\CpUser\Models\CpUser;
use Cache;

class AuthController extends Controller
{
    /**
     * @apiDefine Manage 管理
     */

     /**
     * @apiVersion 1.0.0
     * @apiDescription 管理后台登陆
     * @api {POST} auth/login 管理后台登陆
     * @apiGroup Manage
     * @apiName login
     * @apiParam {String}  username 账号.
     * @apiParam {String}  password 密码.
     * @apiSuccessExample {json} Success-Response:
     *
     *     {
     *         "code": 0,
     *         "msg": "",
     *         "data": {}
     *     }
     */
    function login(Request $request)
    {
    	$msg = '';
    	do{
    		$username = $request->has('username') ? trim($request->input('username')) : '';
    		$password = $request->has('password') ? trim($request->input('password')) : '';
    		
    		if(!$username || !$password) {
    			$msg = '账号或者密码不能为空';
    			break;
    		}
    		 
    		$cp_user = CpUserService::getCpUser($username);
    		
    		if($cp_user && $cp_user->password == md5($password."^-^zhuishuyun^_^"))
    		{
    			if($cp_user->is_enabled == 0) {
	    			$msg = '无效账号';
	    			break;
    			}
    			$request->session()->put('cp_manage_auth', $cp_user->id);
    			$request->session()->put('cp_manage_user', serialize($cp_user));
    		
    			$options = [];
    			$options =[
    			'login'=>'ok',
    			'username'=>$username
    			];
    		
    			$options = json_encode($options);
    			// 成功后跳后台
    			return redirect('index');
    		
    		}else{
    			$msg = '账号或者密码错误';
    			break;
    		}
    	}while(false);

        return redirect('/login?msg='.$msg);
    }
    
    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
    	return Validator::make($data, [
    			'name' => 'required|max:255',
    			'email' => 'required|email|max:255|unique:users',
    			'password' => 'required|confirmed|min:6',
    			]);
    }


}