<?php
 namespace VnChocola\Module\Login\LoginIndex;
 use HttpRequest;
 use Logger;
 use Request;
 use TCMS\Controller;
 use TCMS\TException;
 class IndexController extends Controller {
 public function __construct() {
 }
 private function addStyle() {
 view()->addStyle(asset('style/devexpress/dx.common.css'));
 view()->addStyle(asset('style/devexpress/dx.light.css'));
 view()->addStyle(asset('style/login.reset.min.css'));
 view()->addStyle(asset('style/login.css'));
 view()->addScript(asset('script/jquery-1.12.4.js'));
 view()->addScript(asset('script/devexpress/dx.all.js'));
 view()->addScript(asset('script/globals.js'));
 view()->addScript(asset('script/login/login.js'));
 }
 public function index() {
 $auth = load_auth();
 if(!$auth) {
 throw new TException("Không tìm thấy auth extension");
 }
 if($auth->auth()) {
 $auth->logout();
 }
 $this->addStyle();
 return view([ 'redirect_url' => \Request::get('redirect_url') ]);
 }
 public function postLogin() {
 view()->redirect_url = \Request::get('redirect_url');
 $email = \Request::get('email');
 if(!$email) {
 view()->addErrorMessage('message', lang('login.error_email'));
 $this->addStyle();
 return view('index');
 }
 $password = \Request::get('password');
 if(!$email) {
 view()->addErrorMessage('message', lang('login.error_pass'));
 $this->addStyle();
 return view('index');
 }
 $auth = load_auth();
 if(!$auth) {
 throw new TException("Không tìm thấy auth extension");
 }
 $loginRes = $auth->login($email, $password);
 if($loginRes === true) {
 $redirectUrl = \Request::get('redirect_url');
 if($redirectUrl) return redirect($redirectUrl);
 return redirect(base_url('/'));
 }
 $this->addStyle();
 if($loginRes->getHttpCode() == 401) {
 view()->addErrorMessage('message', 'tải khoản hoặc mật khẩu sai');
 }
 else {
 if(ENVIRONMENT == 'dev') view()->addErrorMessage('message', $loginRes->getError());
 else view()->addErrorMessage('message', 'Kết nối API server thất bại. Vui lòng kiểm tra lại . ' . API_URL);
 }
 return view('index');
 }
 public function loginMobile() {
 $token = Request::get('token', '');
 if(!$token) return redirect(base_url());
 $auth = load_auth('api-auth');
 $info = $auth->decodeToken($token);
 include_library('Cookie');
 \Cookie::set('_apitoken', $token);
 \Cookie::set('_loginInfo', json_encode([ 'id' => $info->id, 'name' => $info->name, 'loginDate' => date('Y-m-d', time()) ]), 86500);
 $lang = Request::get('lang_key', '');
 if($lang) \Cookie::set("web_lang", $lang, 86400 * 30, '/');
 $redirectUrl = \Request::get('redirect_url');
 if(strlen($redirectUrl) > 0) {
 return redirect(base_url('/'.$redirectUrl));
 }
 return redirect(base_url());
 }
 }
