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

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

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

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

$ktktcd = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];

$dats = date('Y/m/d H:i:s'); $logger->info("dats>>",$dats); //afs73用
$wsid = "AP".$ktktcd;
$pid = "AF2665X";

try {
  global $dbutil;
  $valutil = new getValueUtil();

  $ret = true;
  global $stringUtil;
  $header = $data["header"];
  $footer = $data["footer"];

  // ロック生成
  $handle = null;
  $result = lockRequestAP();
  if ($result['ret'] != 0) {
    $ret = $result["ret"];
    $msg = "登録に失敗しました。";

    $bat = $dbutil->nextVal("innerbat");
    $datt = date('Y/m/d H:i:s');
    $pnm = "入金入力";
    $inf1 = "入金入力　異常終了: ".date('Y/m/d H:i:s');
    $inf2 = "【".$ktktcd."】"."ロックエラー";
    $valutil->insertAfs73($bat,$wsid,$pid,$dats,$datt,$pnm,$inf1,$inf2);

    goto endReg;
  } else {
    $handle = $result['handle'];
    $logger->info("lock_handle",$handle);
  }


  // 登録前にget_sbatでaus75を再チェック
  $retSbat = get_sbat($dbutil, $header);
  $logger->info("retSbat",$retSbat);
  $header["sts"]  = $retSbat["sts"];
  $header["sbat"] = $retSbat["sbat"];
  $header["cdat"] = $retSbat["cdat"];

  if ($result['ret'] != 0) {
    $ret = $result["ret"];
    $msg = "登録に失敗しました。";

    $bat = $dbutil->nextVal("innerbat");
    $datt = date('Y/m/d H:i:s');
    $pnm = "入金入力";
    $inf1 = "入金入力　異常終了: ".date('Y/m/d H:i:s');
    $inf2 = "【".$ktktcd."】"."SBATエラー";
    $valutil->insertAfs73($bat,$wsid,$pid,$dats,$datt,$pnm,$inf1,$inf2);

    goto endReg;
  } else {
    $handle = $result['handle'];
    $logger->info("lock_handle",$handle);
  }


  //請求訂正対象のデータなのかをチェック
  $header["teiflg"] = "0";
  if($retSbat["sts"] == '3') {
    $worgadat = strtotime($header["orgadat"]);
    $wcdat = strtotime($retSbat["cdat"]);
    $logger->info("wortadat",$worgadat);
    $logger->info("wcdat",$wcdat);
    if($worgadat <= $wcdat) {
      $header["teiflg"] = "1";
    } else {
      $header["teiflg"] = "0";
    }
  }


  //vseqがない場合、viseq, vseq新規採番
  if($stringUtil->isEmpty($header["vseq"])) {
    $header["vseq"] = $valutil->get_seq("6");
  }
  if($stringUtil->isEmpty($header["viseq"])) {
    $header["viseq"] = $dbutil->nextVal("innerviseq");
  }


  if($retSbat["sts"] == '3') {
    $worgadat = strtotime($header["orgadat"]);
    $wcdat = strtotime($retSbat["cdat"]);
    $logger->info("wortadat",$worgadat);
    $logger->info("wcdat",$wcdat);
    if($worgadat <= $wcdat) {
      $header["sbat"] = $retSbat["sbat"];
    } else {
      $header["sbat"] = "-999";
    }
  } else {
    $header["sbat"] = "-999";
  }


  if(!$stringUtil->isEmpty($header["cuscd"])) {
    $whereParams = array();
    $whereParams["cucd"] = $header["cucd"];
    $whereParams["cuscd"] = $header["cuscd"];
    $sql = file_get_contents("./sql/get032info.sql");
    $ret = $dbutil->select($sql, $whereParams);
    $header["ktktcd"] = $ret[0]["slktcd"]; //aur32.ktktcdはafm032.slktcd
  } else {
    $header["ktktcd"] = '000';
  }

  $cnt = 0; //vlin用
  foreach($data["data"] as $detail) {
    //iseqが埋まっているレコード or tclsの入力があるレコードを対象とする
    if(!$stringUtil->isEmpty($detail["iseq"] || !$stringUtil->isEmpty($detail["tcls"]))) {
      if ($data["updMode"] != "1") { //削除以外
        if($detail["chkLineDel"] != '1') { // ins/upd
          $cnt = $cnt + 1;
          if(!$stringUtil->isEmpty($detail["iseq30"])) {
            //変更があるレコードだけ
            $logger->info("vlin",(int)$stringUtil->nvl($detail["vlin"],'-99999999'));
            $logger->info("cnt",$cnt);
            if($stringUtil->nvl($header["orgadat"],'NULL') != $stringUtil->nvl($header["adat"],'NULL')
            || $stringUtil->nvl($detail["orgtcls"],'NULL') != $stringUtil->nvl($detail["tcls"],'NULL')
            || $stringUtil->nvl($detail["orgtxt2"],'NULL') != $stringUtil->nvl($detail["txt2"],'NULL')
            || $stringUtil->nvl($stringUtil->toNumber($detail["orgamt"]),'-99999999') != $stringUtil->nvl($stringUtil->toNumber($detail["amt"]),'-99999999')
            || (int)$stringUtil->nvl($detail["orgvlin"],'-99999999') != $cnt
            ) {
              $logger->info("insert".$detail["cucd"]);
              updateAur32($header, $detail, $footer, $dbutil, $logger, $cnt );
            }
          } else {
            insertAur32($header, $detail, $footer, $dbutil, $logger, $cnt );
          }
        } else {
          deleteAur32($header, $detail, $footer, $dbutil, $logger, $cnt );
        }
      } else {
        deleteAur32($header, $detail, $footer, $dbutil, $logger, $cnt );
      }
    }
  }

  endReg:

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

  $dbutil->commit();


  $retData["vseq"] = $header["vseq"];
  $response["data"]   = $retData;

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

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

  $dbutil->rollback();
  //ロック解除
  if (!$stringUtil->isEmpty($handle)) {
    lockReleaseAP($handle); //lock解除
  }
} catch(Exception $e) {
  $response["status"] = "NG";
  $response["data"]   = $e->getMessage();

  $dbutil->rollback();
  //ロック解除
  if (!$stringUtil->isEmpty($handle)) {
    lockReleaseAP($handle); //lock解除
  }
} finally {
  $logger->info("response", $response );
  print( json_encode($response) );
}

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


function deleteAur32($header, $data, $footer, $dbutil, $logger, $vlin) {
  $valueData = array();

  if($header["sts"] == '3' && $header["teiflg"] == "1") {
    $valueData["iseq30"] = $data["iseq30"];
    $valueData["sbat"]   = $header["sbat"];
    $valueData["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
    $sql = file_get_contents("./sql/updateDel.sql");
    $logger->info("delUpd",$valueData);
    $result = $dbutil->update($sql, $valueData);
  } else {
    $valueData["iseq30"] = $data["iseq30"];
    $sql = file_get_contents("./sql/delete.sql");
    $logger->info("del",$valueData);    
    $result = $dbutil->delete($sql, $valueData);
  }
  
}

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

  $valueData = array();

  $valueData["adat"]  = $header["adat"];
  $valueData["tcls"]  = $data["tcls"];
  $valueData["vlin"]  = $vlin;
  $valueData["amt"]   = $stringUtil->toNumber($data["amt"]);
  $valueData["txt2"]  = $data["txt2"];
  $valueData["chgcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  $valueData["sbat"]  = $header["sbat"]; //Get_Sbatの返り値

  $logger->info("valuData",$valueData);

  $valueUpdate = $valueData;

  //update のみ
  $valueUpdate["iseq30"] = $data["iseq30"];

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

  return $reuslt;
}

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

  $valueData = array();

  $valueData["tcls"]   = $data["tcls"];
  $valueData["ktktcd"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $valueData["sdday"]  = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
  $valueData["cucd"]   = $header["cucd"];
  $valueData["cuscd"]  = $header["cuscd"];
  $valueData["adat"]   = $header["adat"];
  $valueData["viseq"]  = $header["viseq"];
  $valueData["vseq"]   = $header["vseq"];
  $valueData["vlin"]   = $vlin;
  $valueData["amt"]    = $stringUtil->toNumber($data["amt"]);
  $valueData["txt2"]   = $data["txt2"];
  $valueData["chgcd"]  = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  $valueData["sbat"]   = $header["sbat"]; //Get_Sbatの返り値
  
  $logger->info("valuData",$valueData);


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

  return $reuslt;
}

?>
