<?php
//共通
require_once '../../base/common.php';
$logger = new logger(basename(__FILE__));
$logger->info("=== af238x_update_start ===");

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

//返り値
$request_body = file_get_contents('php://input');
$data = json_decode($request_body, true);

$logger->info("data", $data);

try {
  global $dbutil;
  global $stringUtil;
  $valutil = new getValueUtil();
  $ktktcd = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];

  $ret = "0";
  $errmsg = "";
  $header = $data["header"];
  $footer = $data["footer"];


  //StartiDat取得
  $sql = file_get_contents("./sql/getStartIdat.sql");
  $result = $dbutil->selectnocount($sql);
  $start_idat = $result[0]["idat"];

  // ロック生成
	$handle = null;
  $result = lockRequestAP();
  if ($result['ret'] != 0) {
    //afs73Insert
    insertAfs73($dbutil, $start_idat, "ロックエラー");
    throw new UserException("E0002", "登録に失敗しました。",null);
  } else {
    $handle = $result['handle'];
  }

  //伝票番号の入力がない場合は自動採番
  if($stringUtil->isEmpty($header["vseq"])) {
    $result = $valutil->get_seq("1");
    $header["vseq"] = $result;
$logger->info("getVseq",$result);
  }

  //新規の場合は、内部伝票番号を採番
  if($stringUtil->isEmpty($header["viseq"])) {
    $viseq = $dbutil->nextVal("innerviseq");
    $header["viseq"] = $viseq;
$logger->info("getViseq",$result);
  }

  $retvseq = $header["vseq"];

  $vlin = 1;

  foreach($data["data"] as $key => $detail) {
$logger->info("detail>>",$detail);
    if (!$stringUtil->isEmpty($detail["chkLineDel"])) {   /* 行削除された分を削除 */
      deleteAur32($detail["iseq30"], $dbutil, $logger, $vlin);
    } else {
      /* ISEQが埋まっているレコード or JANの入力があるレコードを対象とする */
      if (!$stringUtil->isEmpty($detail["iseq30"])
            || !$stringUtil->isEmpty($detail["ijan"]) ) {

        if (!$stringUtil->isEmpty($detail["iseq30"])) { /* ISEQが埋まっているレコードを更新、以外は新規 */
					if ($data["updMode"] != "1") { //削除以外
            if ($header["newmode"] == "NEW"
                  || $header["old_adat"] != $header["adat"]
                  || $detail["old_jan"] != $detail["jan"]
                  || $detail["old_txt2"] != $detail["txt2"]
                  || $detail["old_vlin"] != $vlin
                  || floatval($stringUtil->toNumber($detail["old_tpno"])) != floatval($stringUtil->toNumber($detail["tpno"]))
                  || floatval($stringUtil->toNumber($detail["old_fcst"])) != floatval($stringUtil->toNumber($detail["fcst"])) ) { //変更があれば

              $oparam = array();
              updateAur32($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
            }
					} else { //削除
            deleteAur32($detail["iseq30"], $dbutil, $logger, $vlin);
          }
				} else {
          if ($data["updMode"] != "1") { //削除以外
            $oparam = array();
            insertAur32($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
					}
        }
        $vlin = $vlin + 1;
      }
    }
  }

  //ロック解除
  if (!$stringUtil->isEmpty($handle)) {
    lockReleaseAP($handle); //lock解除
  }

  $dbutil->commit();

  $retData["ret"] = $ret;
  $retData["errmsg"] = $errmsg;
  $retData["vseq"] = $retvseq;
  $response["data"]   = $retData;

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

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

  $dbutil->rollback();

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

  $dbutil->rollback();

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

$logger->info("=== af238x_updata_end ===");

function deleteAur32($iseq30, $dbutil, $logger, $vlin) {
  $valueData = array();
  $valueData["iseq30"] = $iseq30;

  $sql = file_get_contents("./sql/delete.sql");
  $result = $dbutil->delete($sql, $valueData);
}

function updateAur32($header, $data, $footer, $oparam, $dbutil, $logger, $vlin) {
  global $stringUtil;
  $valutil = new getValueUtil();

  $updParams = array();

  $updParams["adat"] = $header["adat"];
  $updParams["vlin"] = $vlin;
  $updParams["ijan"] = $data["ijan"];
  $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
  $updParams["fcst"] = $stringUtil->toNumber($data["gdcst"]);
  $updParams["txt2"] = $data["txt2"];
  $updParams["upchg"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];

  $updParams["iseq30"] = $data["iseq30"];

  $sql = file_get_contents("./sql/update.sql");
  $logger->info($sql, $updParams);
  $result = $dbutil->update($sql, $updParams);

  return $reuslt;
}

function insertAur32($header, $data, $footer, $oparam, $dbutil, $logger, $vlin) {
  global $stringUtil;
  $valutil = new getValueUtil();

  $updParams = array();

  $updParams["tcls"] = $header["tcls"];
  $updParams["ktktcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $updParams["sdday"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
  $updParams["spktcd"] = $header["spktcd"];
  $updParams["ijan"] = $data["ijan"];
  $updParams["mcd"] = $header["mcd"];
  $updParams["adat"] = $header["adat"];
  $updParams["viseq"] = $header["viseq"];
  $updParams["vseq"] = $header["vseq"];
  $updParams["vlin"] = $vlin;
  $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
  $updParams["fcst"] = $stringUtil->toNumber($data["fcst"]);
  $updParams["s_fcst"] = $stringUtil->toNumber($data["s_fcst"]);
  $updParams["txt2"] = $data["txt2"];
  $updParams["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];

  $sql = file_get_contents("./sql/insert.sql");
  $logger->info($sql, $updParams);
  $result = $dbutil->insert($sql, $updParams);

  return $reuslt;
}

function insertAfs73($dbutil, $start_idat, $msg, $tcls) {
  global $stringUtil;

  $valueData = array();
  $valueData["wsid"] = 'AP'.$_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $valueData["prgid"] = 'AF238X';
  $valueData["start_idat"] = $start_idat;
  $valueData["title"] = '仕入値引入力登録';
  $valueData["inf2"] = $msg;

  $sql = file_get_contents("./sql/insertAfs73.sql");
  $result = $dbutil->insert($sql, $valueData);
  $dbutil->commit();
}

?>
