<?php
$cate_id = "BASE_OPERATION"; //현재 메뉴 ID 필수!!!
include_once "{$_SERVER['DOCUMENT_ROOT']}/common.inc.php";
include_once _SVC_INC_PATH_ ."/auth_check.php";
include_once _HOME_INC_PATH_ ."/ajax_init.php";


if( !_notAuth("R") ){/************ 권한체크*/
  switch( $_REQUEST['mode'] ){
    case "getOperationList":
      $sql = "USP_B_OPERATION_S10";

      $rst = $baseObj->DB->exec($sql);

      $rows = array();
      if( $rst ){
        $retval['code'] = true;
        while( $row = $baseObj->DB->fetch_array($rst) ){
          $row['OP_CD_OLD'] = $row['OP_CD'];

          $rows[] = $row;
        }
        $retval['data'] = $rows;
      }
      $retval['code'] = 1;
      break;


    case "putOperation":
      if( _notAuth("W") ) break; /************ 권한체크*/

      $_REQUEST['reqdata'] = json_decode($_REQUEST['reqdata']);
      $rst = true;
      $ok_cd = array();
      foreach( $_REQUEST['reqdata'] as $data ){
        $data = (array)$data;

        $cdata = $data;
        unset($cdata['_STATUS_']);
        unset($cdata['USE_FLG']);

        if( empty(array_filter($cdata)) ){
          if( $data['_STATUS_'] == 'I' ) continue; //빈열제거
          if( $data['_STATUS_'] == 'U' ) $data['_STATUS_'] = 'D'; //빈열제거
        }

        if(!$data['OP_CD']) { $retval['mesg'] = cUtil\Mlang::getText("공정코드가 누락된 행은 반영되지 않습니다."); $rst=false; break; }

        $chksql = "USP_B_OPERATION_S20"; //CD 중복검사용
        $chkparams = Array( //CD 중복검사용
          $data['OP_CD']
        );

        if( $data['OP_CD'] && $data['_STATUS_'] == 'D' ){
          $sql = "USP_B_OPERATION_D10";
          $params = Array(
            "OP_CD" => $data['OP_CD'],
          );
        }else{
          if( $data['OP_CD'] && $data['_STATUS_'] == 'U' ) {
            $chkparams[] = $data['OP_CD_OLD']; //CD 중복검사용

            $sql = "USP_B_OPERATION_U10";
            $params = Array();
          }else{
            $sql = "USP_B_OPERATION_I10";
            $params = Array();
          }

          $rst = $baseObj->DB->exec($chksql, $chkparams);
          if( $rst ){
            $row = $baseObj->DB->fetch_array($rst);
            if( $row['OP_CD'] == $data['OP_CD'] ){
              $rst = 0;
              $retval['mesg'] = cUtil\Mlang::getText("{@1} 는 이미 사용중인 코드입니다.",array($data['OP_CD'])); break;
            }
          }

          $params = array_merge($params, Array(
            "OP_CD"        => $data['OP_CD']?:"",
            "OP_NM"        => $data['OP_NM']?:"",
            "OP_GRP"       => $data['OP_GRP']?:"",
            "REMK"         => $data['REMK']?:"",
            "USE_FLG"      => $data['USE_FLG']?:"",
            "MAKE_USER_ID" => $GLOBALS['_Umem']['member_id'],
          ));
        }
        $rst2 = $baseObj->DB->exec($sql, $params);
        if( $rst2 ) $ok_cd[] = $data['OP_CD'];
        $rst = $rst && $rst2;
      }

      $retval['data'] = $ok_cd;
      if( $rst ){
        $retval['code'] = 1;
      }
      break;
  }
}



if( !$_REQUEST['no_echo'] ){
  echo json_encode($retval);
}