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

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

//返り値
//ret : 0:正常終了, -1:重複
$ret_array = array(
  "ret" => "0",
  "vseq" => "",
);

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

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

$header = $data["header"][0];

try {
  global $dbutil;
  global $stringUtil;
  $valutil = new getValueUtil();
  $logger->info("insupd_start");
  
  $ret = true;
  //$detail = $data["data"][0];

  //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'];
  }

  //業務日を取得
  $sdday = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];

  //新規の場合は、伝票番号採番
  if ($stringUtil->isEmpty($detail["vseq"])){
    $header["vseq"] = $dbutil->nextVal("innervseq");
  }

  $cnt = 0;
  $w_lcnt = 0;
  $w_dcnt = 1;

  foreach($data["data"] as $detail) {
$logger->info("dcnt", $w_dcnt);      
    if (!($stringUtil->isEmpty($detail["iseq"]))
      || (!($stringUtil->isEmpty($detail["jan"])) && !($stringUtil->isEmpty($detail["wpno"])))) { //埋まっているもの
        
      $w_lcnt = $w_lcnt + 1;
      //25行を超える場合は伝票番号を新規に取得 
      if ($w_lcnt > 25) {
        //伝票番号自動採番
        $header["vseq"] = $dbutil->nextVal("innertvseq");
        $w_dcnt = $w_dcnt + 1;
        $w_lcnt = 1;
      }

      //iloc取得
      if ($stringUtil->isEmpty($data["iloc"])){
        
        $whereParams=array();
        $whereParams["ijan"] = $detail["ijan"];
        $whereParams["spktcd"] = $detail["spktcd"];
        $sql = file_get_contents("./sql/getIloc.sql");
        $logger->info($sql, $whereParams);
        $result_iloc = $dbutil->select($sql, $whereParams);
        if ($result_iloc == null) {
          $iloc = "";
        } else {
          $detail["iloc"] = $result_iloc[0][iloc];
        }

      }

      $w_pno = $detail["psum"];
      $w_cst = 0;
      //単価取得
      $whereParams=array();
      $whereParams["ijan"] = $detail["ijan"];
      $sql = file_get_contents("./sql/getCst.sql");
      $logger->info($sql, $whereParams);
      $result_gdzcst = $dbutil->select($sql, $whereParams);
      if ($result_gdzcst == null) {
        $w_gdzcst = "0";
      } else {
        $w_gdzcst = $result_gdzcst[0][cst];
      }
$logger->info($detail);
      //update,insert
      if(!($stringUtil->isEmpty($detail["iseq"]))){
        updateAfr3161($header, $detail, $dbutil, $logger ,$w_pno, $w_lcnt, $w_gdzcst);
      } else{
        insertAfr3161($header, $detail, $dbutil, $logger ,$w_pno, $w_lcnt, $w_gdzcst);
      }

    }
  }
  
  //ロック解放
  lockReleaseAP($handle);
$logger->info("header:", $header);      
$logger->info("detail:", $detail);      
  if ($w_dcnt > 1){
    //w_dcntを返す
    $ret_array["dcnt"] = $w_dcnt;
  } else {
    //0を返す
    $ret_array["dcnt"] = 0;
  }
  
  $dbutil->commit();

  $ret_array["ret"] = $result["ret"];
  $ret_array["vseq"] = $header["vseq"];
  $response["data"] = $ret_array;

} 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("=== af9031x_updata_end ===");

function updateAfr3161($header, $data, $dbutil, $logger, $pno, $lcnt, $cst) {
  global $stringUtil;

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

  $valueData = array();
  $valueData["jan"]  = $data["jan"];
  $valueData["ijan"]  = $data["ijan"];
  $valueData["cst"]  = $cst;
  $valueData['chgcd'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  $valueData["dat"]  = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
  $valueData["pno"]  = $pno;
  $valueData["lcnt"]  = $lcnt;
  $valueData["cls1"]  = $data["cls1"];
  $valueData["wpno"]  = $data["wpno"];
  $valueData["iseq"]    = $data["iseq"];
  $valueData['ktktcd'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $valueData["spktcd"]  = $data["spktcd"];
  
  $logger->info("valuData",$valueData);

  //更新
  $sql = file_get_contents("./sql/update.sql");
  $result = $dbutil->update($sql, $valueData);
  $logger->info($sql, $valueData);
  $logger->info("did_update");

  return $reuslt;
}

function insertAfr3161($header, $data, $dbutil, $logger, $pno, $lcnt, $cst) {
  //global $stringUtil;

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

  $valueData = array();
  $valueData['ktktcd'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $valueData["spktcd"]  = $header["spktcd"];
  $valueData["cls1"]  = $header["cls1"];
  $valueData["vseq"] = $header["vseq"];
  $valueData["lcnt"] = $lcnt;
  $valueData["jan"]  = $data["jan"];
  $valueData["ijan"]  = $data["ijan"];
  $valueData["iloc"]  = $data["iloc"];
  $valueData["cst"]  = $cst;
  $valueData["pno"]    = $pno;
  $valueData["wpno"]  = $data["wpno"];
  $valueData['chgcd'] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["CHGCD"];
  
  $logger->info("valuData",$valueData);

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

  return $reuslt;
}

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

  $valueData = array();
  $valueData["wsid"] = 'AP'.$_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];
  $valueData["prgid"] = 'AF2A2X';
  $valueData["start_idat"] = $start_idat;
  $valueData["title"] = '棚卸入力';
  $valueData["inf2"] = $msg;

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


?>
