<?php
//共通
require_once '../base/common.php';
require_once '../util/dateUtil.php';
require_once '../util/loginUtil.php';
$logger = new logger(basename(__FILE__));
$logger->info("===".$GLOBALS['SYSTEM_NO']."_login_start===");

$response["status"] = "OK";

try {
  $dateUtil = new dateUtil();

  // セッションクリア
  $serverUtil->deleteSession();

  global $dbutil;

  $errflg = false;
  $commitflg = false;

  $requestBody = file_get_contents('php://input');
  $data = json_decode($requestBody, true);
  $logger->info("data", $data );

  // 入力値
  $id     = $data["user"];
  $pass   = $data["p"];
  $iv     = $data["i"];
  $key1   = $data["k"];
  $ip     = $data["ip"];
  $lmode  = $data["lmode"];  //0=通常, 1=強制
  $loginseq = $data["seq"]; //login seq

  // IP設定
  if($stringUtil->isEmpty($ip) || $ip == "0.0.0.0") {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
  }
  if($stringUtil->isEmpty($ip) || $ip == "0.0.0.0") {
    $ip = $_SERVER["REMOTE_ADDR"];
  }
  if($stringUtil->isEmpty($ip) ){
    $ip = "0.0.0.0";
  }
  $logger->info($ip, "IPADDRESS");
  //ipアドレスをxxx.xxx.xx.xx -> xxxxxxxxxxxxに変換
  $wiparry = explode(".", $ip); //分割
  $wip = '';
  foreach ($wiparry as $key => $value) {
    $wip .= sprintf('%03d', $value);
  }
  $ip = $wip;
  $logger->info($ip, "IPADDRESS_New");

  // パスワード復号化
  $encData  = base64_decode( $pass );

  $logger->info("key1");
  $iv   = hex2bin($iv);
  $key1 = hex2bin($key1);
  $logger->info("key2");

  // 復号に使うメソッド
  $method = 'AES-256-CBC';
  // 復号に使うオプション

  $options = OPENSSL_RAW_DATA;
  $decData = openssl_decrypt($encData, $method, $key1, OPENSSL_RAW_DATA, $iv);
  $logger->info("passwd>".$decData);

  // ログイン処理
  session_start();

  $loginUtil = new loginUtil($dbutil, $logger);
  $ret = $loginUtil->login($lmode, $loginseq, $id, $decData, $GLOBALS['SYSTEM_ACCD'], $GLOBALS['SYSTEM_VEND'], $ip);
  if($ret["errcd"] != null) {
    if ($ret["updflg"] == "1") {
      $dbutil->commit();
    }
    $response["status"] = "NG";
    $retData["errcd"]   = $ret["errcd"];
    $retData["msg"]     = $ret["errmsg"];
    $response["data"]   = $retData;
  } else {
    $iseq331 = $ret["iseq311"];
    $sid = session_id();
    //session情報記録
    $loginUtil->setAfw89($sid, $id, $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"], $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"], $GLOBALS['SYSTEM_ACCD'], $ip, $iseq331);

    $response["data"]   = "./product/menu/menu01.php";
  }




} catch(userException $ue) {
  $logger->info("userException", $retData);
  $retData["code"]  = $ue->getErrorCode();
  $retData["msg"]   = $ue->getErrorMessage();

  $response["status"] = "NG";
  $response["data"]   = $retData;

} catch(Exception $e) {
  $logger->info("Exception", $retData);
  $response["status"] = "NG";
  $retData["msg"] = $e->getMessage();
  $response["data"]   = $retData;

} finally {
  $logger->info("response", $response );
  print( json_encode($response) );
  $logger->info("=== end ===");
}


?>
