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

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


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

try {
  global $dbutil;

  foreach($data["data"] as $detail) {
    $logger->info("data", $detail );

    insertUpdateAfm02( $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("===at906x_update_end===");



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

  $valueData['area'] = $header['area'];
  $valueData['anm'] = $data['anm'];
  $valueData['anms'] = $data['anms'];
  $valueData['aknm'] = $data['aknm'];
  $valueData['aknms'] = $data['aknms'];
  $valueData['aprf'] = $data['aprf'];
  $valueData['stp'] = $data['stp'];

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

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

  return $reuslt;
}

?>
