<?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"];

  //登録直前にaus75を再チェック
  $result = $valutil->getSbat("1","0",$ktktcd,$header["cucd"],$header["cuscd"]);
$logger->info("sbat:",$result);
  $ret = $result["ret"];
  $sbat = $result["sbat"];
  $cdat = $result["cdat"];
  $sts = $result["sts"];
  if ($ret == "0") {  //sbat OK
    $header["sbat"] = $sbat;
    $header["cdat"] = $cdat;
    $header["sts"] = $sts;
  } else {
    $ret = "-9";
    $msg = "データ取得に失敗しました。";
  }
  if ($ret == "0") {
    $w_old_adat = new DateTime($header["old_adat"]);
    $w_cdat = new DateTime($header["cdat"]);
    $w_adat = new DateTime($header["adat"]);
    /* 請求訂正対象のデータなのかをチェック */
  	if ($header["sts"] == "3") {
      //返品日
      if ($w_old_adat <= $w_cdat) {
  			$w_teiflg = "1";
      } else {
        $w_teiflg = "0";
      }
  	}
    $header["teiflg"] = $w_teiflg;

    //thflg取得
    $ret05 = $valutil->allMastData("0","afm05",$header["spktcd"]);
    $w_thflg = $ret05["thflg"];

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

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

    //担当コード取得
    $valueData = array();
    $valueData["cucd"] = $header["cucd"];
    $valueData["cuscd"] = $header["cuscd"];
    $sql = file_get_contents("./sql/getSpslcd.sql");
    $result = $dbutil->selectnocount($sql, $valueData);
    if ($result == null) {
      $w_spslcd = "";
    } else {
      $w_spslcd = $result[0]["spslcd"];
    }

    if ($header["sts"] == "3" ) {
      if ($w_adat <= $w_cdat) {
        $w_sbat = $header["sbat"];
      } else {
        $w_sbat = "-999";
      }
    } else {
      $w_sbat = "-999";
    }

    $vlin = 1;

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

          if ($header["cutaxcls"] == "1" && $header["cutax"] == "1") {  //総額得意先なら
  $logger->info("sogaku_cucd");
            $w_ntcst = Number($stringUtil->toNumber($detail["ncst"]));
            //計上日を渡す
            $w_ncst  = $valutil->calc_gdbcst("1","1",$ktktcd,$header["cucd"],$detail["ijan"],$w_ntcst,$header["adat"]);
  				} else {
  $logger->info("not_sogaku_cucd,cutax=".$header["cutax"]);
            $w_ncst = $stringUtil->toNumber($detail["ncst"]);
  					/* 税込単価(ntcst)の取得 */
            if ($header["cutax"] == "1") {
              //計上日を渡す
  						$w_ntcst = $valutil->get_ntcst($ktktcd, $detail["ijan"], $header["cucd"], $header["adat"], $w_ncst);
  					} else {
  						$w_ntcst = "";
  					}
  				}
  $logger->info("w_ncst>>".$w_ncst.",w_ntcst>>".$w_ntcst);

          if (!$stringUtil->isEmpty($detail["iseq30"])) { /* ISEQが埋まっているレコードを更新、以外は新規 */
  					if ($data["updMode"] != "1") { //削除以外
              if ($header["newmode"] == "NEW"
                    || $header["old_dat2"] != $header["dat2"]
                    || $header["old_adat"] != $header["adat"]
                    || $header["old_spktcd"] != $header["spktcd"]
                    || $header["old_dcubcd"] != $header["dcubcd"]
                    || $header["old_cuslip"] != $header["cuslip"]
                    || $header["old_bbno"] != $header["bbno"]
                    || $header["old_ltxt1"] != $header["ltxt1"]
                    || $header["old_ltxt2"] != $header["ltxt2"]
                    || $header["old_ltxt3"] != $header["ltxt3"]
                    || $footer["old_txt1"] != $footer["txt1"]
                    || $detail["old_jan"] != $detail["jan"]
                    || $detail["old_vlin"] != $vlin
                    || floatval($stringUtil->toNumber($detail["old_tpno"])) != floatval($stringUtil->toNumber($detail["tpno"]))
                    || floatval($stringUtil->toNumber($detail["old_ncst"])) != floatval($stringUtil->toNumber($detail["ncst"])) ) { //変更があれば

                $oparam = array();
                $oparam["ncst"] = $w_ncst;
                $oparam["ntcst"] = $w_ntcst;
                $oparam["sbat"] = $w_sbat;
                $oparam["thflg"] = $w_thflg;
                updateAur32($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
              } else {
                $oparam = array();
                updateAur32Nochange($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
              }
  					} else { //削除
              $oparam = array();
              $oparam["thflg"] = $w_thflg;
              deleteAur32($header, $detail, $dbutil, $oparam, $logger, $vlin, "denpyo");
            }
  				} else {
            if ($data["updMode"] != "1") { //削除以外
              $w_iseq31 = $dbutil->nextVal("innerseq");
              if ($header["cuhcls"] == "0") {
                $w_iseq32 = $dbutil->nextVal("innerseq");
              } else {
                $w_iseq32 = "";
              }
              $oparam = array();
              $oparam["iseq31"] = $w_iseq31;
              $oparam["iseq32"] = $w_iseq32;
              $oparam["ncst"] = $w_ncst;
              $oparam["ntcst"] = $w_ntcst;
              $oparam["sbat"] = $w_sbat;
              $oparam["thflg"] = $w_thflg;
              $oparam["spslcd"] = $w_spslcd;
              if ($w_thflg == "0") {
                insertAfr31($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
              }
              if ($header["cuhcls"] == "0") {
                insertAur32($header, $detail, $footer, $oparam, $dbutil, $logger, $vlin);
              }
  					}
          }
          $vlin = $vlin + 1;
        }
      }
    }

    $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($header, $data, $dbutil, $logger, $vlin, $pmode) {
  if (($pmode == "denpyo" && $oparam["thflg"] == 0) || $pmode == "line" ) {
    $valueData = array();
    $valueData["iseq31"] = $data["iseq31"];
    $sql = file_get_contents("./sql/delUpdateAfr31.sql");
    $result = $dbutil->update($sql, $valueData);
  }
  if ($header["cuhcls"] == "0") {
    $valueData = array();
    if ($header["sts"] == "3" and $header["teiflg"] == "1") {
      $valueData["iseq30"] = $data["iseq30"];
      $valueData["sbat"] = $header["sbat"];
      $valueData["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
      $sql = file_get_contents("./sql/delUpdateAur32.sql");
      $result = $dbutil->update($sql, $valueData);
    } else {
      $valueData["iseq30"] = $data["iseq30"];
      $sql = file_get_contents("./sql/delAur32.sql");
      $result = $dbutil->delete($sql, $valueData);
    }
  }
}

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

  if ($header["cuhcls"] == "0") {
    //aur32更新
    $updParams = array();
    $updParams["dat2"] = $header["dat2"];
    $updParams["adat"] = $header["adat"];
    $updParams["spktcd"] = $header["spktcd"];
    $updParams["dcubcd"] = $header["dcubcd"];
    $updParams["cuslip"] = $header["cuslip"];
    $updParams["bbno"] = $header["bbno"];
    $updParams["ltxt1"] = $header["ltxt1"];
    $updParams["ltxt2"] = $header["ltxt2"];
    $updParams["ltxt3"] = $header["ltxt3"];
    $updParams["vlin"] = $vlin;
    $updParams["ijan"] = $data["ijan"];
    $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
    $updParams["icst"] = $stringUtil->toNumber($oparam["ncst"]);
    $updParams["sal"] =  $stringUtil->toNumber($data["sal"]);
    $updParams["fcst"] = $stringUtil->toNumber($data["gdcst"]);
    $updParams["txt1"] = $footer["txt1"];
    $updParams["upchg"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
    $updParams["sbat"] = $oparam["sbat"];
    $updParams["cutaxcls"] = $header["cutaxcls"];
    $updParams["ntcst"] = $stringUtil->toNumber($oparam["ntcst"]);
    $updParams["ncst"] = $stringUtil->toNumber($oparam["ncst"]);
    $updParams["iseq30"] = $data["iseq30"];
    $sql = file_get_contents("./sql/updAur32.sql");
    $logger->info($sql, $updParams);
    $result = $dbutil->update($sql, $updParams);
    //iseq取得
    $selParams = array();
    $selParams["iseq30"] = $data["iseq30"];
    $sql = file_get_contents("./sql/getAur32AfterUpdate.sql");
    $logger->info($sql, $selParams);
    $result = $dbutil->select($sql, $selParams);
    if ($result == "") {
      $w_tmp = "";
    } else {
      $w_tmp = $result[0]["iseq30"];
    }
   }

   if ($oparam["thflg"] == "0") {
     $updParams = array();
     $updParams["dat2"] = $header["dat2"];
     $updParams["adat"] = $header["adat"];
     $updParams["spktcd"] = $header["spktcd"];
     $updParams["vlin"] = $vlin;
     $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
     $updParams["ncst"] = $stringUtil->toNumber($oparam["ncst"]);
     $updParams["nn1"] = $w_tmp;
     $updParams["iseq31"] = $data["iseq31"];
     $sql = file_get_contents("./sql/updAfr31.sql");
     $logger->info($sql, $updParams);
     $result = $dbutil->update($sql, $updParams);
   }

  return $reuslt;
}

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

  if ($header["cuhcls"] == "0") {
    //acr30更新
    $updParams = array();
    $updParams["iseq30"] = $data["iseq30"];
    $sql = file_get_contents("./sql/updAcr30.sql");
    $logger->info($sql, $updParams);
    $result = $dbutil->update($sql, $updParams);
   }

  return $reuslt;
}

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

  $updParams = array();

  $updParams["iseq31"] = $oparam["iseq31"];
  $updParams["jan"] = $data["jan"];
  $updParams["ktktcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $updParams["spktcd"] = $header["spktcd"];
  $updParams["cucd"] = $header["cucd"];
  $updParams["cuscd"] = $header["cuscd"];
  $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
  $updParams["ncst"] = $stringUtil->toNumber($oparam["ncst"]);
  $updParams["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  $updParams["dat2"] = $header["dat2"];
  $updParams["adat"] = $header["adat"];
  $updParams["iseq32"] = $oparam["iseq32"];
  $updParams["cuiseq"] = $header["cuiseq"];
  $updParams["vseq"] = $header["vseq"];
  $updParams["vlin"] = $vlin;

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

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

  $updParams = array();

  $updParams["iseq32"] = $oparam["iseq32"];
  $updParams["ktktcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $updParams["sdday"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
  $updParams["ijan"] = $data["ijan"];
  $updParams["cucd"] = $header["cucd"];
  $updParams["cuscd"] = $header["cuscd"];
  $updParams["adat"] = $header["adat"];
  $updParams["dat2"] = $header["dat2"];
  $updParams["spktcd"] = $header["spktcd"];
  $updParams["viseq"] = $header["viseq"];
  $updParams["vseq"] = $header["vseq"];
  $updParams["vlin"] = $vlin;
  $updParams["cuslip"] = $header["cuslip"];
  $updParams["tpno"] = $stringUtil->toNumber($data["tpno"]);
  $updParams["ncst"] = $stringUtil->toNumber($oparam["ncst"]);
  $updParams["sal"] =  $stringUtil->toNumber($data["sal"]);
  $updParams["fcst"] = $stringUtil->toNumber($data["fcst"]);
  $updParams["s_cst"] = $stringUtil->toNumber($data["s_cst"]);
  $updParams["spslcd"] = $oparam["spslcd"];
  $updParams["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  $updParams["txt1"] = $footer["txt1"];
  $updParams["dcubcd"] = $header["dcubcd"];
  $updParams["bbno"] = $header["bbno"];
  $updParams["ltxt1"] = $header["ltxt1"];
  $updParams["ltxt2"] = $header["ltxt2"];
  $updParams["ltxt3"] = $header["ltxt3"];
  $updParams["iseq31"] = $oparam["iseq31"];
  $updParams["sbat"] = $oparam["sbat"];
  $updParams["ntcst"] = $stringUtil->toNumber($oparam["ntcst"]);

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

  return $reuslt;
}

?>
