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

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

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

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(
    "sts" => "",
    "com" => "",
  );  //ヘッダー・フッター情報

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

  if ($stringUtil->isEmpty($header["vseq"])) {  //新規
    $newMode = "NEW";
    $ret_header["maxvlin"] = "99"; //最大行数
  } else {  //データ検索
    $whereParams = array();
    $whereParams["ktktcd"] = $ktktcd;
    $whereParams["spktcd"] = $header["spktcd"];
    $whereParams["vseq"] = $header["vseq"];
    $sql = file_get_contents("./sql/search.sql");
$logger->info('search>>'.$sql, $whereParams);
    $result = $dbutil->select($sql, $whereParams);
    if ($result == null) {  //ありえない
      $ret = "-1";
    } else {
      $newMode = "UPD";
      $ret_detail = $result;

      //ヘッダー情報
      $ret_header["sts"] = $ret_detail[0]["sts"];
      $ret_header["com"] = $ret_detail[0]["com"];

      foreach($ret_detail as $key => $detail) {
        //不良品在庫数
        $ret_detail[$key]["psum"] = getPsum($dbutil, $detail["ijan"], $header["spktcd"]);
        //金額cal_amt
        $ret_detail[$key]["amt"] = $valutil->calc_amt("", $detail["pno"], $detail["cst"], "2", $ktktcd, $ret_header["scutaxc"]);
      }
      $ret_header["maxvlin"] = "20"; //最大行数
    }
  }

$logger->info("search_mode:".$newMode);
  $ret_header["newmode"] = $newMode;

  $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("=== af24ax_search_end ===", $response);

?>
