<?php
/*
* @Overview 부서 등록
* @History 2024-03-28 / 이원기 / 최초작성
           2024-04-05 / 박민희 / 설비 사진 업로드 
*/


$cate_id="BASE_FACILITY";
include_once "{$_SERVER['DOCUMENT_ROOT']}/common.inc.php";
include_once _SVC_INC_PATH_ ."/auth_check.php";
include_once _HOME_INC_PATH_ ."/ajax_init.php";

$_tmp_dir = _UP_PATH_."/temp"; //임시파일저장경로
$_faclt_dir = _UP_PATH_."/faclt"; //설비 저장 경로


if( !_notAuth("R") ){/************ 권한체크*/
  switch( $_REQUEST['mode'] ){
    case "getFacilityList":

      $sql = "USP_B_FACILITY_S10";
      $params = Array(
        "USEFLAG"           => $_REQUEST['USEFLAG']?:'',
        "FACLT_CD"          => $_REQUEST['FACLT_CD']?:'',
        "FACLT_NM"          => $_REQUEST['FACLT_NM']?:'',
        "FACLT_GRP"          => $_REQUEST['FACLT_GRP']?:'',
      );
      $rst = $baseObj->DB->exec($sql,$params);

      $rows = array();


      if( $rst ){
        $retval['code'] = true;
        while( $row = $baseObj->DB->fetch_array($rst) ){
//          $row['FACLT_CD_OLD'] = $row['FACLT_CD'];
          $row['PUR_DT'] = $row['PUR_DT'] ? getDT_date($row['PUR_DT']) : null;
          $rows[] = $row;
        }
        $retval['data'] = $rows;
      }
      $retval['code'] = 1;
      break;

    case "getRepairInfo":
      $sql = "USP_B_FACILITY_S20";
      $params = Array(
        $_REQUEST['FACLT_CD'],
      );
      $rst = $baseObj->DB->exec($sql, $params);
      if( $rst ){
        $retval['data'] = $baseObj->DB->fetch_array($rst);
        $retval['data']['FACLT_CD_OLD'] = $retval['data']['FACLT_CD'];

        $sql = "USP_ZB_ATTACH_S10";
        $params = Array(
          "file_id" => $_REQUEST['file_id'],
          "gubun"   => "faclt",
          "nid"     => $_REQUEST['FACLT_CD'],
        );
        $rst2 = $baseObj->DB->exec($sql, $params);
        if( $rst2 ){
          $retval['data']['ATT'] = [];
          while( $fr = $baseObj->DB->fetch_array($rst2) ){
            $retval['data']['ATT'][$fr['sid']] = $fr;
          }
        }

        $sql = "USP_B_FACILITY_HST_S10";
        $params = Array(
          $_REQUEST['FACLT_CD'],
          'Y'
        );
        $rst3 = $baseObj->DB->exec($sql, $params);
        if( $rst3 ){
          $retval['code'] = 1;
          $rows = Array();
          while( $row = $baseObj->DB->fetch_array($rst3) ){
            $row['REPAIR_DT'] = $row['REPAIR_DT'] ? getDT_date($row['REPAIR_DT']) : null;
            $rows[] = $row;
          }
          $retval['data']['REPAIR'] = $rows;
        }
      }
      break;

      case "deleteImg":

        
        $rst = true;
        $fal_sql = "USP_B_FACILITY_D20";
        $fal_params = Array(
           "FACLT_CD"           => $_POST['FACLT_CD']
         );               
        $rst = $baseObj->DB->exec($fal_sql, $fal_params);

        if($rst){ 
          $sql = "USP_ZB_ATTACH_D10";
          $params = array(
              "file_id" => $_POST['FILE_ID'] ?: "",
              "gubun"   => "faclt",
              "nid"     => $_POST['FACLT_CD'] ?: "",
              "sid"     => $_POST['SID'] ?: "",
          );
         };  
         $rst = $baseObj->DB->exec($sql, $params);
    
        if($rst){
          @unlink("{$_faclt_dir}/{$_POST['FACLT_CD']}_{$_POST['SID']}_{$_POST['FILE_ID']}.dat");
         }
    
        if ($rst) {
            $retval['code'] = true;
            $retval['mesg'] = '정상적으로 삭제되었습니다.';
        } else {
            $retval['code'] = false;
        }
        break;
    
        case "deleteForm":
          $fal_params = Array();
          $params = Array();
          $retval = array('code' => false, 'mesg' => '', 'data' => '');

          
          if (_notAuth("W")) {
              $retval['mesg'] = '권한이 없습니다.';
              break; /************ 권한체크 */
          }
          
          $reqdata = json_decode($_REQUEST['reqdata']);
          if (!$reqdata) {
              $retval['mesg'] = '잘못된 요청 데이터입니다.';
              break;
          }
      
          foreach ($reqdata as $request) {
              $request = (array)$request;
              $_REQUEST['RS_CODE'] = "";
              $_REQUEST['RS_MSG'] = "";
      
              if ($request['FACLT_CD'] && $request['_STATUS_'] == 'D') { 
                  $fal_sql = "USP_B_FACILITY_D10";
                  $fal_params = array(
                      "FACLT_CD" => $request['FACLT_CD'],
                      "RS_CODE" => array(&$_REQUEST['RS_CODE'], SQLSRV_PARAM_OUT),
                      "RS_MSG" => array(&$_REQUEST['RS_MSG'], SQLSRV_PARAM_OUT)
                  );
      
                  $rst1 = $baseObj->DB->exec($fal_sql, $fal_params);
      
                  if ($rst1 && $_REQUEST['RS_CODE'] == '0') {
                      $retval['code'] = true;
                      $retval['mesg'] = $_REQUEST['RS_MSG'];
                  } else {
                      $retval['code'] = false;
                      $retval['mesg'] = $_REQUEST['RS_MSG'];
                      break; // 한 번 실패하면 나머지 작업도 실패로 간주하고 종료
                  }
      
                  if ($rst1) {
                      $sql = "USP_ZB_ATTACH_D10";
                      $params = array(
                          "file_id" => $request['FILE_ID'] ?: "",
                          "gubun" => "faclt",
                          "nid" => $request['FACLT_CD'] ?: "",
                          "sid" => $request['SID'] ?: ""
                      );
      
                      $rst2 = $baseObj->DB->exec($sql, $params);
      
                      if ($rst2) {
                          @unlink("{$_faclt_dir}/{$request['FACLT_CD']}_{$request['SID']}_{$request['FILE_ID']}.dat");
                      } else {
                          $retval['code'] = false;
                          $retval['mesg'] = '파일이 삭제되지 않았습니다.';
                          break; 
                      }
                  }
              }
          }
          break;
      
    case "getprocess":
      $sql = "USP_B_PRO_FACLT_S10";
      $params = Array(
        "FACLT_CD"           => $_REQUEST['FACLT_CD']?:''
      );
      $rst = $baseObj->DB->exec($sql,$params);

      $rows = array();


      if( $rst ){
        $retval['code'] = true;
        while( $row = $baseObj->DB->fetch_array($rst) ){
          $rows[] = $row;
        }
        $retval['data'] = $rows;
      }
      break;
    case "putProcess":
      $params = Array();
      if( _notAuth("W") ) break; /************ 권한체크*/


      foreach( json_decode($_REQUEST['reqdata']) as $request ){

        $request = (array)$request;

        if( !$request['FACLT_CD'] ){
          $retval['mesg'] = cUtil\Mlang::getText("설비코드를 입력하지 않았습니다."); break;
        }
//        else if( !$request['FACLT_NM'] ){
//          $retval['mesg'] = cUtil\Mlang::getText("설비명을 입력하지 않았습니다."); break;
//        }

        if( $request['FACLT_CD'] && $request['_STATUS_'] == 'D' ){
          $sql = "USP_B_PRO_FACLT_D10";
          $params = Array(
            "FACLT_CD"        => $request['FACLT_CD'],
            "OP_CD"           => $request['OP_CD'],
          );
        }else {
          if ($request['FACLT_CD'] && $request['_STATUS_'] == 'U') {
            $sql = "USP_B_PRO_FACLT_U10";
          } else {
            $sql = "USP_B_PRO_FACLT_I10";
          }
          $_REQUEST['RS_CODE'] = "";
          $_REQUEST['RS_MSG'] = "";
          $params = Array(
            "FACLT_CD"     => $request['FACLT_CD'] ?: "",
            "OP_CD"        => $request['OP_CD'] ?: "",
            "SEQNO"        => $request['SEQNO'] ?: "",
            "MAKE_USER_ID" => $GLOBALS['_Umem']['member_id'],

          
            "RS_CODE"		   => array(&$_REQUEST['RS_CODE'], SQLSRV_PARAM_OUT),
            "RS_MSG"			 => array(&$_REQUEST['RS_MSG'], SQLSRV_PARAM_OUT)
          );


          if(strlen($data['REMK']) > 100){$_REQUEST['RS_MSG'] = cUtil\Mlang::getText("비고는 100자 내로 작성해주세요."); $rst=false; break;}
      }
       
        $rst = $baseObj->DB->exec($sql, $params);

        if($rst && !$_REQUEST['RS_CODE']){
          $retval['code'] = true;
      } else {
          $retval['code'] = false;
          $retval['mesg']  = $_REQUEST['RS_MSG'];
      }

    }
    break;

    case "setForm":
    case "putForm":

    
      $upfiles = array();
      $sid =$_POST['SID']?:uniqid();

      if ($_POST['tmp_file'] && file_exists($_tmp_dir . "/{$_POST['tmp_file']}")) {
        $upfiles = \Frody\Util\MultiFileUpload::swfFormFileInfo($_POST['tmp_file'], $_tmp_dir);
      }

      $params = array(
        "gubun"       => "faclt",
        "nid"         =>$_POST['FACLT_CD']?: "",
        "sid"         => $sid,
        "file_name"   => $upfiles[0]['name']?: "",
        "file_size"   => $upfiles[0]['size']?: "",
        "file_type"   => $upfiles[0]['type']?: "",
        "file_width"  => $upfiles[0]['width'],
        "file_height" => $upfiles[0]['height'],
        "file_exp"    =>$_POST['file_exp'] ?: "",
        "reg_date"    =>$_POST['reg_date'] ?: ""
      );

      if ($upfiles) {
        $sql = "USP_ZB_ATTACH_I10";
        //$rst2 = false;
        //$rst2 = $baseObj->DB->result($baseObj->DB->exec($sql, $params),0,0);
        $data['FILE_ID'] = $baseObj->DB->result($baseObj->DB->exec($sql, $params),0,0);
        if ($data['FILE_ID']) {
          \Frody\Util\MultiFileUpload::swfMoveUploadedFile($upfiles[0]['tmp_name'], "{$_faclt_dir}/{$_POST['FACLT_CD']}_{$sid}_{$data['FILE_ID']}.dat");
        }
      }
      

      $_REQUEST['RS_CODE'] = "";
      $_REQUEST['RS_MSG'] = "";
  
      if($_POST['mode'] == "putForm"){
        $sql = "USP_B_FACILITY_I10";
      }else if($_POST['mode'] == "setForm"){
        $sql = "USP_B_FACILITY_U10";
      }


      $params1 = array(
        "FACLT_CD"          =>  $_POST['FACLT_CD']            ?: "",
        "FACLT_NM"          =>  $_POST['FACLT_NM']            ?: "",
        "FACLT_MNG_NO"      =>  $_POST['FACLT_MNG_NO']        ?: "",
        "MAJR_EMP_NO"       =>  $_POST['MAJR_EMP_NO']         ?: "",
        "MINR_EMP_NO"       =>  $_POST['MINR_EMP_NO']         ?: "",
        "PUR_BP_NM"         =>  $_POST['PUR_BP_NM']           ?: "",
        "PUR_DT"            =>  $_POST['PUR_DT']              ?: null,
        "PUR_REPRE_NM"      =>  $_POST['PUR_REPRE_NM']        ?: "",
        "PUR_PRSN_NM"       =>  $_POST['PUR_PRSN_NM']         ?: "",
        "PUR_TEL_NO"        =>  $_POST['PUR_TEL_NO']          ?: "",
        "MAKER_NM"          =>  $_POST['MAKER_NM']            ?: "",
        "INTNL_USE_DEPT_CD" =>  $_POST['INTNL_USE_DEPT_CD']   ?: "",
        "FACLT_SPEC"        =>  $_POST['FACLT_SPEC']          ?: "",
        "PURPOS_USAGE"      =>  $_POST['PURPOS_USAGE']        ?: "",
        // "WRK_TEAM"         =>  $_POST['WRK_TEAM']           ?: "",
        "ITEM_GRP"          =>  $_POST['ITEM_GRP']           ?: "",
        "MANUL_FLG"         =>  $_POST['MANUL_FLG']           ?: "",
        "USE_FLG"           =>  $_POST['USE_FLG']             ?: "Y",
        "MAKE_USER_ID"      =>  $_POST['_Umem']['member_id']        ,
        "FILE_ID"           =>  $data['FILE_ID']                    ,
        "RS_CODE"		        => array(&$_REQUEST['RS_CODE'], SQLSRV_PARAM_OUT),
        "RS_MSG"			      => array(&$_REQUEST['RS_MSG'], SQLSRV_PARAM_OUT)
      );      
      

      // 데이터베이스 작업 실행
      $rst = $baseObj->DB->exec($sql, $params1);
    

      if( $_REQUEST['RS_CODE'] === "E" ){
        $retval['mesg']  = $_REQUEST['RS_MSG'];
        $retval['code'] = false;
      }else{
        $retval['code'] = true;
      }
      break;
    case "getRepair":
      $sql = "USP_P_FACILITY_REPAIR_HST_S20";
      $params = Array(
        "FACLT_CD"           => $_REQUEST['FACLT_CD']?:''
      );
      $rst = $baseObj->DB->exec($sql,$params);

      $rows = array();


      if( $rst ){
        $retval['code'] = true;
        while( $row = $baseObj->DB->fetch_array($rst) ){
          $rows[] = $row;
        }
        $retval['data'] = $rows;
      }
      break;
    case "putTempFile":
      if( isset($_FILES["upfile"]) ){

        $fdata['tmp_name'] = \Frody\Util\MultiFileUpload::swfFormSaveFile($_FILES["upfile"], $_tmp_dir);

        $retval['code'] = 1;
        $retval['data'] = $fdata;

        \Frody\Util\MultiFileUpload::swfCleanDir($_tmp_dir);
      }
      break;
    
    }
  }
  
if( !$_REQUEST['no_echo'] ){
  echo json_encode($retval);
}