<?php
include('setup/config.php');
session_start();
$_SESSION['error'] = '';
$login = check_current_user_login($ARR_USERS, $SALT);
$currentuser = $login['user'];

if($currentuser){
    $sessionname = md5($currentuser->username.$SALT);
    $_SESSION[$sessionname] = FALSE;
	session_unset();
	session_destroy();
}


/* CHECK LOGIN */
session_start();
$postu = "";
$postp = "";
if (isset($_POST['u'])) {
    $postu = $_POST['u'];
}
if (isset($_POST['p'])) {
    $postp = $_POST['p'];
}
$iserror = true;

//var_dump($_SERVER);
//var_dump($_POST);
//var_dump(strpos($_SERVER['HTTP_HOST'], 'localhost'));
//var_dump(in_array($_SERVER['REMOTE_ADDR'], $arrAddressIP));
//var_dump($arrAddressIP);
//var_dump($_SERVER['REMOTE_ADDR']);
$checkIP = in_array($_SERVER['REMOTE_ADDR'], $arrAddressIP);
//var_dump($checkIP);
//$checkIP = true;


$ip = getenv('HTTP_CLIENT_IP')?:
	getenv('HTTP_X_FORWARDED_FOR')?:
	getenv('HTTP_X_FORWARDED')?:
	getenv('HTTP_FORWARDED_FOR')?:
	getenv('HTTP_FORWARDED')?:
	getenv('REMOTE_ADDR'); 

file_put_contents('iplogin',date('Y-m-d H:i:s').':'.$ip."\r\n", FILE_APPEND);


$ARR_USERS = array();

$listUser = 'data/User.json';
$ARR_USERS = json_decode(file_get_contents($listUser));

$checkIP =  true;

//die();
if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false || $checkIP == true) {
    foreach ($ARR_USERS as $u) {
        if ($u->name == $_POST['u'] AND $u->password == $_POST['p']) {
            $sessionname = md5($u->name . $SALT);
            $_SESSION[$sessionname] = TRUE;
            $iserror = false;
            break;
        }
    }
} 
//print_r($_SESSION);
//die();
/* if ( isset($_POST['u']) and isset($_POST['p']) ) {
  if ( $_POST['u'] == $USER AND $_POST['p'] == $PASS ){
  // ADD salt for security
  $sessionname = md5($USER.$SALT);
  $_SESSION[$sessionname] = TRUE;
  $_SESSION['error'] = FALSE;
  header('location: index.php');
  exit;
  } else {
  $_SESSION['error'] = TRUE;
  header('location: login.php');
  exit;
  }
  } else {
  $_SESSION['error'] = TRUE;
  header('location: login.php');
  exit;
  } */
$_SESSION['error'] = $iserror;
if ($iserror) {
    header('location: login.php');
    exit;
} else {  
    header('location: index.php');
    exit;
}
