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

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

$gInit_array = array( //初期値
  "iseq" => "",
);

//ret = 0 OK, 1=売上伝票複数, 2=受注伝票複数, -1=売上伝票無し(ありえない), -2=受注伝票無し, -9=エラー
try {
  global $dbutil;
  global $stringUtil;
  $valutil = new getValueUtil();

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

  // SQL実行
  $header = $data["header"];
$logger->info("header>>",$header);
  $ret_array = array(); //return用
  $ret_detail = array();  //データ用
  $ret_header = array();  //ヘッダー・フッター情報
  $ret_header["del_flg"] = "0";

  $ret = "0";
  $newMode = "NEW";
  $ktktcd = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["LGKTKTCD"];

  $w_cuiseq = "";
  if ($header["tcls"] == "01") {  //売上
    if (!$stringUtil->isEmpty($header["cvseq"])) {  //受注伝票番号入力
      $whereParams = array();
      $whereParams["ktktcd"] = $ktktcd;
      $whereParams["cucd"] = $header["cucd"];
      $whereParams["cuscd"] = $header["cuscd"];
      $whereParams["cvseq"] = $header["cvseq"];
      $whereParams["cuiseq"] = $header["cuiseq"]; //修正:viseq特定の場合
      $sql = file_get_contents("./sql/getCuiseq.sql");
$logger->info($sql, $whereParams);
      $result = $dbutil->selectnocount($sql, $whereParams);
$logger->info("getcuiseq>>",$result);
      if ($result[0]["cnt"] == "1") {
        $w_cuiseq = $result[0]["cuiseq"];
        $newMode = "UNDER"; //動きとしては更新
      } else if ($result[0]["cnt"] == "0") { //データなし → エラー
        $ret = "-1";
        $msg = "受注データがありません。";
      } else {  //伝票複数
        $ret = "2";
      }
    }
  }

  if ($ret == "0") {  //受注伝票有 or 指定無し
    if ($newMode != "UNDER") { //受注下敷きじゃない場合、入力した伝票番号より
      //sbat取得
      $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
        if (!$stringUtil->isEmpty($header["vseq"])) { //修正:vseq入力あり
          $whereParams = array();
          $whereParams["ktktcd"] = $ktktcd;
          $whereParams["cucd"] = $header["cucd"];
          $whereParams["cuscd"] = $header["cuscd"];
          $whereParams["vseq"] = $header["vseq"];
          $whereParams["tcls"] = $header["tcls"];
          $whereParams["sts"] = $sts;
          $whereParams["sbat"] = $sbat;
          $whereParams["viseq"] = $header["viseq"]; //修正:viseq特定の場合
          $sql = file_get_contents("./sql/getViseq.sql");
    $logger->info($sql, $whereParams);
          $result = $dbutil->selectnocount($sql, $whereParams);
    $logger->info("getviseq>>",$result);
          if ($result[0]["cnt"] == "1") {
            $w_viseq = $result[0]["viseq"];
            $newMode = "UPD";
          } else if ($result[0]["cnt"] == "0") { //データなし → 新規
            $newMode = "NEW";
          } else {  //伝票複数
            $ret = "1";
          }
        }
      } else {
        $ret = "-9";
        $msg = "データ取得に失敗しました。";
      }
    }
  }

$logger->info("newmode:".$newMode);
  if ($ret == "0") {  //ここまでOK 新規 or 伝票特定
    //cutax,cutaxc取得
    $ret_afm03 = $valutil->allMastData("", "afm03", $header["cucd"]);
    if ($stringUtil->isEmpty($ret_afm03["cutax"])) {
      $ret_header["cutax"] = "0";
    } else {
      $ret_header["cutax"] = $ret_afm03["cutax"];
    }
    if ($stringUtil->isEmpty($ret_afm03["cutaxc"])) {
      $ret_header["cutaxc"] = "0";
    } else {
      $ret_header["cutaxc"] = $ret_afm03["cutaxc"];
    }
    if ($stringUtil->isEmpty($ret_afm03["cutaxdiv"])) {
      $ret_header["cutaxdiv"] = "0";
    } else {
      $ret_header["cutaxdiv"] = $ret_afm03["cutaxdiv"];
    }

    if ($newMode == "UPD" || $newMode == "UNDER") { //表示
      if ($newMode == "UNDER") { //受注下敷き
$logger->info("3123Start");
        $ret_header["maxvlin"] = $valutil->getMaxRecord($header["cucd"]); //最大行数

        $whereParams = array();
        $whereParams["ktktcd"] = $ktktcd;
        $whereParams["vseq"] = $header["vseq"];
        $whereParams["cvseq"] = $header["cvseq"];
        $whereParams["cucd"] = $header["cucd"];
        $whereParams["cuscd"] = $header["cuscd"];
        $whereParams["cuiseq"] = $w_cuiseq;
        $whereParams["cutaxcls"] = $header["cutaxcls"];
        $whereParams["cutax"] = $ret_header["cutax"];
        $sql = file_get_contents("./sql/search3123.sql");
      } else {
$logger->info("UPD start");
        $whereParams = array();
        $whereParams["ktktcd"] = $ktktcd;
        $whereParams["vseq"] = $header["vseq"];
        $whereParams["cucd"] = $header["cucd"];
        $whereParams["cuscd"] = $header["cuscd"];
        $whereParams["tcls"] = $header["tcls"];
        $whereParams["sts"] = $sts;
        $whereParams["sbat"] = $sbat;
        $whereParams["viseq"] = $w_viseq;
        $whereParams["cutaxcls"] = $header["cutaxcls"];
        $whereParams["cutax"] = $ret_header["cutax"];
        $sql = file_get_contents("./sql/search.sql");
      }
$logger->info('search>>'.$sql, $whereParams);
      $result = $dbutil->select($sql, $whereParams);
$logger->info($result);
      if ($result == null) {  //ありえない
        $ret = "-1";
      } else {
        $ret_detail = $result;
        //受注下敷き
        $ret_header["cvseq"] = $ret_detail[0]["cvseq"];
        $ret_header["cuiseq"] = $ret_detail[0]["cuiseq"];
        if (!$stringUtil->isEmpty($header["cvseq"])) {  //受注伝票番号入力
          $ret_header["vseq"] = ""; //伝票番号無効
        }
        //ヘッダー情報
        $ret_header["cunm"] = $ret_detail[0]["cunm"];
        $ret_header["spnm"] = $ret_detail[0]["spnm"];
        $ret_header["maxviln"] = $ret_detail[0]["vno"];
        $ret_header["viseq"] = $ret_detail[0]["viseq"];
        $ret_header["dat3"] = $ret_detail[0]["dat3"];
        $ret_header["dat4"] = $ret_detail[0]["dat4"];
        $ret_header["hvseq"] = $ret_detail[0]["hvseq"];
        $ret_header["spktcd"] = $ret_detail[0]["spktcd"];
        $ret_header["spktnm"] = $ret_detail[0]["spktnm"];
        $ret_header["dat2"] = $ret_detail[0]["dat2"];
        $ret_header["old_dat2"] = $ret_detail[0]["dat2"];
        $ret_header["adat"] = $ret_detail[0]["adat"];
        $ret_header["old_adat"] = $ret_detail[0]["adat"];
        $ret_header["dcubcd"] = $ret_detail[0]["dcubcd"];
        $ret_header["old_dcubcd"] = $ret_detail[0]["dcubcd"];
        $ret_header["cuslip"] = $ret_detail[0]["cuslip"];
        $ret_header["old_cuslip"] = $ret_detail[0]["cuslip"];
        $ret_header["bbno"] = $ret_detail[0]["bbno"];
        $ret_header["old_bbno"] = $ret_detail[0]["bbno"];
        $ret_header["dtxt1"] = $ret_detail[0]["dtxt1"];
        $ret_header["old_dtxt1"] = $ret_detail[0]["dtxt1"];
        $ret_header["dtxt2"] = $ret_detail[0]["dtxt2"];
        $ret_header["old_dtxt2"] = $ret_detail[0]["dtxt2"];
        $ret_header["ltxt1"] = $ret_detail[0]["ltxt1"];
        $ret_header["old_ltxt1"] = $ret_detail[0]["ltxt1"];
        $ret_header["ltxt2"] = $ret_detail[0]["ltxt2"];
        $ret_header["old_ltxt2"] = $ret_detail[0]["ltxt2"];
        //受注のvseq,cuiseq
        $ret_header["cvseq"] = $ret_detail[0]["cvseq"];
        $ret_header["cuiseq"] = $ret_detail[0]["cuiseq"];
        //フッター情報
        $ret_header["txt1"] = $ret_detail[0]["txt1"];
        $ret_header["old_txt1"] = $ret_detail[0]["txt1"];
        $ret_header["chgcdnm"] = $ret_detail[0]["chgcdnm"];
        $ret_header["idat"] = $ret_detail[0]["idat"];

        foreach($ret_detail as $key => $detail) {
          //消費税情報セット
          $ret_taxrt = $valutil->FmGetTaxrdivTaxrt($detail["ijan"], $ret_header["adat"], $ktktcd);
          $ret_detail[$key]["gdtax"] = $ret_taxrt["gdtax"];
          $ret_detail[$key]["gdtaxrt"] = $ret_taxrt["gdtaxrt"];
          $ret_detail[$key]["taxrt"] = $ret_taxrt["taxrt"];
          $ret_detail[$key]["taxinfo"] = $ret_taxrt["taxinfo"];
          //納入金額cal_amt
          $ret_detail[$key]["s_cst"] = $valutil->calc_amt($header["cucd"], $detail["tpno"], $detail["dsp_ncst"], "1", $ktktcd, $ret_header["cutaxc"]);

          //更新情報セット
          if (!$stringUtil->isEmpty($detail["udat"])) {
            $udat = $detail["udat"];
          } else {
            $udat = $detail["idat"];
          }
          if ($udat > $detail["idat"]) {  // 更新日時＞入力日時の場合
            if (!$stringUtil->isEmpty($ret_header["udat"])) { //更新日時に既に入力があり、
      				// 現在の行の更新日時のほうが大きい場合上書き
              if ($ret_header["udat"] < $detail["udat"]) {
                $ret_header["udat"] = $detail["udat"];
                $ret_header["upchgnm"] = $detail["upchgnm"];
              }
            } else {  // 更新日時に既に入力がなければ
              $ret_header["udat"] = $detail["udat"];
              $ret_header["upchgnm"] = $detail["upchgnm"];
            }
          }

          if ($detail["prop"] == "2") { //prop=2のデータが含まれているデータは削除不可
            $ret_header["del_flg"] = "1";
          }
        }

      }
    } else {  //新規
      $ret_header["maxvlin"] = $valutil->getMaxRecord($header["cucd"]);
      $ret_header["dat2"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
      $ret_header["adat"] = $_SESSION[$GLOBALS['SYSTEM_NAME_EN']]["SDDAY"];
    }
  }

  if ($newMode == "NEW") {  //新規なら出庫倉庫デフォルト表示
    $sql = file_get_contents("./sql/getDefSpktcd.sql");
    $whereParams = array();
    $whereParams["cucd"] = $header["cucd"];
    $whereParams["cuscd"] = $header["cuscd"];
    $result = $dbutil->selectnocount($sql, $whereParams);
$logger->info("defspktcd",$result);
    if ($result == null) {
      $ret_header["spktcd"] = "";
      $ret_header["spktnm"] = "";
    } else {
      $ret_header["spktcd"] = $result[0]["spktcd"];
      $ret_header["spktnm"] = $result[0]["spktnm"];
    }
  }
$logger->info("search_mode:".$newMode);
  $ret_header["newmode"] = $newMode;
  $ret_header["sbat"] = $sbat;
  $ret_header["cdat"] = $cdat;
  $ret_header["sts"] = $sts;

  $ret_array["ret"] = $ret;
  $ret_array["msg"] = $msg;
  $ret_array["ret_array"] = $ret_detail;
  $ret_array["ret_header"] = $ret_header;
  $ret_array["cnt"] = $cnt;
  $result = $ret_array;

  $logger->info('search_ret',$result );
  $response["status"] = "OK";
  $response["data"]   = json_encode($result, true);

} 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 {
  print(json_encode($response));
}


$logger->info("=== af222x_search_end ===", $response);

?>
