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

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


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

try {
  global $dbutil;

  $detail = $data["data"][0];
  $logger->info("data", $detail );

  insertUpdateAfm05( $data["header"], $detail, $dbutil, $logger );

  $dbutil->commit();

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



function insertUpdateAfm05($header, $data, $dbutil, $logger) {
  global $stringUtil;

  $valueData['ktktcd'] = $header['ktktcd'];
  $valueData['ktktnm'] = $data['ktktnm'];
  $valueData['ktktnk'] = $data['ktktnk'];

  $valueData['ktcls'] = $data['ktcls'];
  $valueData['ktzip'] = $data['ktzip'];
  $valueData['ktad1'] = $data['ktad1'];
  $valueData['ktad2'] = $data['ktad2'];
  $valueData['kttel'] = $data['kttel'];
  $valueData['ktfax'] = $data['ktfax'];
  
  $valueData['constr'] = $data['constr'];
  $valueData['dbuser'] = $data['dbuser'];
  $valueData['dbpass'] = $data['dbpass'];
  $valueData['hstr'] = $data['hstr'];
  $valueData['sdno'] = $data['sdno'];
  $valueData['sdcd'] = $data['sdcd'];
  $valueData['ipsegadr'] = $data['ipsegadr'];
  $valueData['constr2'] = $data['constr2'];
  $valueData['dbuser2'] = $data['dbuser2'];
  $valueData['dbpass2'] = $data['dbpass2'];
  $valueData['hstr2'] = $data['hstr2'];
  
  $valueData['htcls']  = $data['htcls'];
  $valueData['htpnt1'] = $stringUtil->toNumber($data['htpnt1']);
  $valueData['htpnt2'] = $stringUtil->toNumber($data['htpnt2']);
  $valueData['htlmt1'] = $stringUtil->toNumber($data['htlmt1']);
  $valueData['htlmt2'] = $stringUtil->toNumber($data['htlmt2']);

  $valueData['tday'] = $data['tday'];
  $valueData['nyflg'] = $data['nyflg'];

  $valueData['stp'] = $data['stp'];
  $valueData['ruktcd'] = $data['ruktcd'];
  
  $valueUpdate = $valueData;
  
  $valueUpdate['reg'] = $data['reg'];
  $valueUpdate['upd'] = $data['upd'];
  
  $logger->info("valuData",$valueData);

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

  if($result == 0){ //UpdateできなかったらInsert
    $sql = file_get_contents("./sql/insert.sql");
    $result = $dbutil->insert($sql, $valueData);
    $logger->info("did_insert");
  }

  return $reuslt;
}

?>
