<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Cookie;

class LoginController extends Controller
{
    public function Index(){
    	return view("login.login");
    }
    public function CheckLogin(Request $req){
		$current_timestamp = date('Y-m-d H:i:s');
		$sql = sprintf("SELECT `idPs`,`PsNnameF`,`PsNameS`,`PsNickName`,`idPosition`,`idDept`,`UN`,`PW` FROM `dperson`
			WHERE (UN= '%s')
			AND (PW = '%s') ", $req->input("username"),$req->input("pass"));
		$chk = DB::select($sql);

		if(!empty($chk)){

			$tm = time()+(60*60*24*365);
			return redirect("home")
			->withCookie(cookie('idPs', $chk[0]->idPs,$tm))
			->withCookie(cookie('nickname', $chk[0]->PsNickName,$tm))
			->withCookie(cookie('name', $chk[0]->PsNnameF." ".$chk[0]->PsNameS,$tm))
			->withCookie(cookie('idPosition', $chk[0]->idPosition,$tm))
			->withCookie(cookie('idDept', $chk[0]->idDept,$tm));
		}else{
			
			session()->flash('state','1');
			return view("login.login");
		}

	}

	public function Logout(){

		if (isset($_COOKIE['idPs'])) {
			unset($_COOKIE['idPs']); 
			setcookie('idPs', null, -1, '/'); 
			return redirect("login");
		} else {
			return false;
		}

		// setcookie('idPs',"0",-1,'','');
		// setcookie('nickname');
		// setcookie('name');
		// setcookie('idPosition');
		// setcookie('idDept');
		// session()->flush();
		// return redirect("login");
	}
}
