<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDrive.php'; // 세션 등 여러가지 포함됨 파일 포함

// 불러오는 파일 리스트 require_once($_SERVER['DOCUMENT_ROOT'] . "/output/write_form_script.php"); 

if(!isset($_SESSION["level"]) || $_SESSION["level"]>5) {
	 sleep(1);
		  header("Location:" . $WebSite . "login/login_form.php");  
	 exit;
}

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';

$mode = isset($_REQUEST['mode']) ? $_REQUEST['mode'] : '';  
$num = isset($_REQUEST["num"]) ? $_REQUEST["num"] : "";
$tablename = isset($_REQUEST["tablename"]) ? $_REQUEST["tablename"] : "";

require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDriveSecond.php'; // attached, image에 대한 정보 불러오기  
require_once $_SERVER['DOCUMENT_ROOT'].'/estimate/fetch_unitprice.php'; // 견적에 필요한 함수포함  slatPrice 함수 포함


// 절곡단가 가져오는 임시테이블
$tablename_tmp = 'price_bend'; 

try {
	// 최신 데이터를 가져오기 위해 ORDER BY와 LIMIT을 추가
	$sql = "SELECT * FROM {$DB}.$tablename_tmp where (is_deleted IS NULL or is_deleted = '0') ORDER BY num DESC LIMIT 1";
	$stmh = $pdo->prepare($sql); 
	$stmh->execute();
	$row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.     	   	
	$itemList_bend = isset($row['itemList']) ? $row['itemList'] : [];
	$load_priceDate = $row['registedate'] ?? '';

	// itemList 문자열일 때만 json_decode 실행
	if (is_string($itemList_bend)) {
		$itemList_bend = json_decode($itemList_bend, true);
	}

	// itemList 유효한 배열이 아닐 경우 빈 배열로 초기화
	if (!is_array($itemList_bend)) {
		$itemList_bend = [];
	}		
	
} catch (PDOException $Exception) {
	print "오류: ".$Exception->getMessage();
}
	
// 주자재 단가 가져오기
$tablename_price_raw_materials = 'price_raw_materials';
$query = "SELECT itemList FROM $DB.$tablename_price_raw_materials WHERE is_deleted IS NULL OR is_deleted = 0";
$stmt = $pdo->prepare($query);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 대상 자재 목록 (구분 항목)
$materials = ['방화', '방범','조인트바', '실리카', '화이바', '와이어', '신설비상문','제연커튼','실리카원단','화이바원단','와이어원단','단열셔터','이중파이프'];

// 자재 단가 저장용 배열
$materialBasePrice = [];
// 자재 코드
$materialBaseCode = [];

foreach ($materials as $material) {
    foreach ($rows as $row) {
        $itemList = json_decode($row['itemList'], true);
        $price = unapprovedSlatPrice($itemList, '', $material); // col1=스크린, col2=각 자재명 col15에서 비인정 불러옴
        $code = unapprovedSlatCode($itemList,  $material); // col1=스크린, col2=각 자재명
        $materialBasePrice[$material] = floatval($price);
        $materialBaseCode[$material] = $code;            
    }
}

// print_r($materialBasePrice);
// print_r($materialBaseCode);

// 자바스크립트에 단가 데이터 전달
echo "<script>";
echo "window.materialBasePrice = " . json_encode($materialBasePrice, JSON_UNESCAPED_UNICODE) . ";";
echo "window.materialBaseCode = " . json_encode($materialBaseCode, JSON_UNESCAPED_UNICODE) . ";";
echo "var item_bend = " . json_encode($itemList_bend) . ";";
echo "</script>";


// 전동개폐기 등 Ecount 단가 가져오기

// (2) KDunitprice 테이블 전체 또는 필요한 prodcode만 조회
$prodcode_sql = "
    SELECT
        prodcode,
        item_name,
        spec,
        unitprice
    FROM {$DB}.KDunitprice
    WHERE is_deleted IS NULL
";
$stmt = $pdo->prepare($prodcode_sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);

// (3) PHP associative 배열에 담기
$unitInfo = [];
foreach ($rows as $r) {
    $unitInfo[$r['item_name']] = [
        'prodcode'  => $r['prodcode'],
        'item_name' => $r['item_name'],
        'spec'      => $r['spec'],
        'price'     => (float)$r['unitprice'],
    ];
}

// print_r($unitInfo);

// (4) JS 전역 변수로 내보내기
echo "<script>\n";
echo "  window.unitInfo = " . json_encode($unitInfo, JSON_UNESCAPED_UNICODE) . ";\n";
echo "</script>";

if($mode === 'copy')
	$title_message = "(데이터복사) 수주내역";
else
	$title_message = "수주내역 " ;

$authorities = ["개발자","전진","노완호","이세희","함신옥","손금주","이은진","이경호","김진호","이세희","함신옥"];

// 서버에서 날짜 값을 받아온다고 가정
$receivedCode = ""; // 예시값, 실제로는 서버에서 받아오는 값으로 대체

if(!empty($authority))
	echo 'authority : ' . $authority ;
?>  
<title> <?=$title_message?> </title>
<link href="css/mystyle.css?v=<?php echo time(); ?>" rel="stylesheet">   <!-- 늘 읽어오는 CSS 설정법 pdf 프린터설정에 대한 css -->
</head>

<?php   
include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';
  
// 첨부 이미지에 대한 부분
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();	
 
$today = date("Y-m-d"); // 현재일자 변수지정

  if(isset($_REQUEST["regist_state"]))  // 등록하면 1로 설정 접수상태
   $regist_state=$_REQUEST["regist_state"];
  else
   $regist_state="등록";

  if ($mode=="modify" || !empty($num) )
  {
    try{
      $sql = "select * from $DB.$tablename where num = ? ";
      $stmh = $pdo->prepare($sql); 

      $stmh->bindValue(1,$num,PDO::PARAM_STR); 
      $stmh->execute();
      $count = $stmh->rowCount();            
	  $row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.
    if($count<1){  
      print "검색결과가 없습니다.<br>";
     }else{
        include '_row.php';	        		
		if($indate!="0000-00-00") $indate = date("Y-m-d", strtotime( $indate) );
				else $indate="";	 
		if($outdate!="0000-00-00") $outdate = date("Y-m-d", strtotime( $outdate) );
				else $outdate="";	 	
				
		// output_extra 테이블에서 데이터 불러오기
		require_once $_SERVER['DOCUMENT_ROOT'] . '/output/load_output_extraTable.php';				
			  
      }
     }catch (PDOException $Exception) {
       print "오류: ".$Exception->getMessage();
     }
  }
else if ($mode!="modify" && $mode!="view" && $mode!="copy" ){    // 수정모드가 아닐때 신규 자료일때는 변수 초기화 한다.
    include '_request.php';
    $outdate=date("Y-m-d");
    $indate=date("Y-m-d");
    $orderdate=date("Y-m-d");
    $orderman=$_SESSION["name"];
    $outworkplace=null;
    $outputplace=null;
    $receiver=null;
    $phone=null;
    $comment=null;
    $updatecomment=null;
    $con_num=null;
    $steel=null;	  
    $motor=null;	  			
    $delivery=null;	 		
    
    $regist_state="등록";	  		
    $is_deleted=null;
    $motor_state ='등록';
    $bend_state ='등록';
	  
	$root="경동";	  			  
	if(!empty($_SESSION["division"])) 
		if($_SESSION["division"]=='주일')		 
				$root="주일";	  	 
  } 
  
  else { // 복사, 분할등 선택시
	   try{
      $sql = "select * from $DB.$tablename where num = ? ";
      $stmh = $pdo->prepare($sql); 

      $stmh->bindValue(1,$num,PDO::PARAM_STR); 
      $stmh->execute();
      $count = $stmh->rowCount();            
	  $row = $stmh->fetch(PDO::FETCH_ASSOC);  // $row 배열로 DB 정보를 불러온다.

	  if($count<1){  
		print "검색결과가 없습니다.<br>";
		}else{

       include '_row.php';
	   	  
	 if($indate!="0000-00-00") $indate = date("Y-m-d", strtotime( $indate) );
			else $indate="";	 
	 if($outdate!="0000-00-00") $outdate = date("Y-m-d", strtotime( $outdate) );
			else $outdate="";	 

		$outdate=date("Y-m-d");
		$indate=date("Y-m-d");
		$orderdate=date("Y-m-d");
		$orderman=$_SESSION["name"];	

	  // output_extra 테이블에서 데이터 불러오기
	  $sql_extra = "SELECT * FROM $DB.$tablename_sub WHERE parent_num = ?";
	  $stmh_extra = $pdo->prepare($sql_extra);
	  $stmh_extra->bindValue(1, $num, PDO::PARAM_STR);
	  $stmh_extra->execute();
	  $row_extra = $stmh_extra->fetch(PDO::FETCH_ASSOC);

	  // 값이 있으면 _row_extra.php로 변수화
	  if ($row_extra) {
		  include '_row_extra.php';
	  }	
			  
      }
     }catch (PDOException $Exception) {
       print "오류: ".$Exception->getMessage();
     }  
	  
  } 
  
  //  print 'devMode : ' . $devMode; 
  // print 'ET_total : ' . $ET_total; 
	// print 'regist_state : ' . $regist_state;
	// print 'prodcode : ' . $prodCode ;  

	// (2) PHP에서 JSON 직렬화
	$deliveryfeeList_jsonString = json_encode($deliveryfeeList); // 물류비용 JSON
	// (3) HTML에서 문제될 수 있는 특수문자를 URL 인코딩
	//     rawurlencode() / urlencode() 등 사용 가능
	$deliveryfeeList_encodedJson = rawurlencode($deliveryfeeList_jsonString);  
	$detailJson_jsonString = json_encode($detailJson); // 물류비용 JSON
	$detailJson_jsonString_encodedJson = rawurlencode($detailJson_jsonString); 
?>  
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data" onkeydown="if (event.key === 'Enter') event.preventDefault();">
<input type="hidden" id="timekey" name="timekey" value="<?= isset($timekey) ? $timekey : '' ?>"> <!-- 신규데이터 작성시 parentid key값으로 사용 -->				
<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">
<input type="hidden" id="num" name="num" value="<?= isset($num) ? $num : '' ?>">
<input type="hidden" id="level" name="level" value="<?= isset($level) ? $level : '' ?>">
<input type="hidden" id="user_id" name="user_id" value="<?= isset($user_id) ? $user_id : '' ?>">
<input type="hidden" id="user_name" name="user_name" value="<?= isset($user_name) ? $user_name : '' ?>">
<input type="hidden" id="update_log" name="update_log" value="<?= isset($update_log) ? $update_log : NULL ?>">
<input type="hidden" id="tablename" name="tablename" value="<?= isset($tablename) ? $tablename : '' ?>">
<input type="hidden" id="is_deleted" name="is_deleted" value="<?= isset($is_deleted) ? $is_deleted : '0' ?>">
<input type="hidden" id="motor_state" name="motor_state" value="<?= isset($motor_state) ? $motor_state : '등록' ?>">
<input type="hidden" id="bend_state" name="bend_state" value="<?= isset($bend_state) ? $bend_state : '등록' ?>">
<input type="hidden" id="screenlist" name="screenlist" >
<input type="hidden" id="screen_su" name="screen_su" value="<?= isset($screen_su) ? $screen_su : '' ?>">
<input type="hidden" id="screen_m2" name="screen_m2" value="<?= isset($screen_m2) ? $screen_m2 : '' ?>">
<input type="hidden" id="screen" name="screen" value="<?= isset($screen) ? $screen : '' ?>">
<input type="hidden" id="slatlist" name="slatlist" >
<input type="hidden" id="slat_su" name="slat_su" value="<?= isset($slat_su) ? $slat_su : '' ?>">
<input type="hidden" id="slat_m2" name="slat_m2" value="<?= isset($slat_m2) ? $slat_m2 : '' ?>">
<input type="hidden" id="slat" name="slat" value="<?= isset($slat) ? $slat : '' ?>">
<input type="hidden" id="estimateList" name="estimateList" >
<input type="hidden" id="estimateList_auto" name="estimateList_auto" >
<input type="hidden" id="estimateSlatList" name="estimateSlatList" >
<input type="hidden" id="estimateSlatList_auto" name="estimateSlatList_auto" >
<input type="hidden" id="etcList" name="etcList">
<input type="hidden" id="screen_unapprovedList" name="screen_unapprovedList">
<input type="hidden" id="slat_unapprovedList" name="slat_unapprovedList">
<input type="hidden" id="motorList" name="motorList">
<input type="hidden" id="bendList" name="bendList">
<input type="hidden" id="controllerList" name="controllerList">
<input type="hidden" id="accountList" name="accountList">

<input type="hidden" id="deliveryfeeList" name="deliveryfeeList"  value="<?php echo $deliveryfeeList_encodedJson; ?>">

<input type="hidden" id="pjnum" name="pjnum" value="<?= isset($pjnum) ? $pjnum : '' ?>">
<input type="hidden" id="major_category" name="major_category" value="<?= isset($major_category) ? $major_category : '' ?>">
<input type="hidden" id="position" name="position" value="<?= isset($position) ? $position : '' ?>">
<input type="hidden" id="makeWidth" name="makeWidth" value="<?= isset($makeWidth) ? $makeWidth : '' ?>">
<input type="hidden" id="makeHeight" name="makeHeight" value="<?= isset($makeHeight) ? $makeHeight : '' ?>">
<input type="hidden" id="estimateSurang" name="estimateSurang" value="<?= isset($estimateSurang) ? $estimateSurang : '' ?>">
<input type="hidden" id="EstimateFirstSum" name="EstimateFirstSum" value="<?= isset($EstimateFirstSum) ? $EstimateFirstSum : '' ?>">
<input type="hidden" id="EstimateUpdatetSum" name="EstimateUpdatetSum" value="<?= isset($EstimateUpdatetSum) ? $EstimateUpdatetSum : '' ?>">
<input type="hidden" id="EstimateDiffer" name="EstimateDiffer" value="<?= isset($EstimateDiffer) ? $EstimateDiffer : '' ?>">
<input type="hidden" id="EstimateDiscountRate" name="EstimateDiscountRate" value="<?= isset($EstimateDiscountRate) ? $EstimateDiscountRate : '' ?>">
<input type="hidden" id="EstimateDiscount" name="EstimateDiscount" value="<?= isset($EstimateDiscount) ? $EstimateDiscount : '' ?>">
<input type="hidden" id="EstimateFinalSum" name="EstimateFinalSum" value="<?= isset($EstimateFinalSum) ? $EstimateFinalSum : '' ?>">
<input type="hidden" id="maguriWing" name="maguriWing" value="<?= isset($maguriWing) ? $maguriWing : '' ?>">
<input type="hidden" id="inspectionFee" name="inspectionFee" value="<?= isset($inspectionFee) ? $inspectionFee : '500000' ?>">
<input type="hidden" id="detailJson" name="detailJson"  value="<?php echo $detailJson_jsonString_encodedJson; ?>">

<!-- 전체화면 모달 (부트스트랩 X) -->
<!-- 비인정품 거래명세 -->
<div id="fullscreenModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); z-index:1050;">
  <div style="background:white; width:1880px; height:950px; margin:40px auto; padding:20px; border-radius:8px; position:relative;">    
      <div class="d-flex justify-content-between bg-dark text-white" >
        <h3 class="p-2">발주 내역 + 가격 입력</h3>
        <button type="button" id="closeAccountModal" style="background:none; border:none; color:white; font-size:24px;">&times;</button>
      </div>
	  <div class="custom-modal-body">
        <div class="row">
          <!-- 왼쪽 -->
          <div class="col-5 border-end overflow-auto">
            <h3 class="mb-3">📋 발주 내역</h3>
          </div>

          <!-- 오른쪽 -->
          <div class="col-7 overflow-auto">
            <h3 class="mb-3">💰 가격 입력</h3>
            <div class="row mb-2">
              <div class="col-3">
                <label class="form-label fs-6">일자</label>
                <input type="date" id="accountDate" name="accountDate" class="form-control form-control-sm">
              </div>
              <div class="col-3">
                <label class="form-label fs-6">거래처</label>
                <input type="text" id="accountCompany" name="accountCompany" class="form-control form-control-sm">
              </div>
            </div>
            <div class="row">
              <div class="col-6">
                <div class="d-flex justify-content-start">
                <button type="button" class="btn btn-sm btn-outline-danger mb-1 remove-row-account-all me-1" onclick="
                    Swal.fire({
                        title: '전체행을 삭제하시겠습니까?',
                        icon: 'warning',
                        showCancelButton: true,
                        confirmButtonColor: '#d33',
                        cancelButtonColor: '#3085d6',
                        confirmButtonText: '네',
                        cancelButtonText: '취소'
                    }).then((result) => {
                        if (result.isConfirmed) {
                            $('#account_listBody tr').remove();
                            updateTableSums();
                            alertToast('전체행이 삭제되었습니다');
                        }
                    });">전체행 삭제</button>
                <button type="button" class="btn btn-sm btn-outline-primary mb-1 add-row-account mx-1">+ 행추가</button>
                <button type="button" id="recalcBtn" class="btn btn-sm btn-outline-primary mb-1 ms-5 me-2">  <i class="bi bi-calculator"></i> 재계산 </button>                             
                <button type="button" id="transactionRecordBtn" class="btn btn-sm btn-outline-success mb-1 mx-2">  <i class="bi bi-card"></i> 거래명세서 </button>                             
              </div>            
            </div>            
              <div class="col-6"> 
                <div class="d-flex justify-content-end">
                  <button type="button" id="saveAccountBtn" class="btn btn-primary ms-5 me-2">저장</button>            
                  <button type="button" class="btn btn-secondary ms-1" id="closeAccountModal2">닫기</button>
                </div>
              </div>
            </div>            
            <div class="table-responsive mb-2">
              <table class="table table-bordered table-hover table-sm text-center" id="accountList">
                <thead class="table-secondary">
                  <tr>
                    <th>일련번호</th>
                    <th style="width:100px;"> 품목코드</th>
                    <th style="width:200px;"> 품목명</th>
                    <th style="width:180px;"> 규격</th>
                    <th style="width:70px;"> 수량</th>
                    <th style="width:80px;"> 단가</th>
                    <th style="width:80px;"> 공급가액</th>
                    <th style="width:80px;"> 부가세</th>
                    <th class="w-15">적요</th>
                  </tr>
                </thead>
                <tbody id="account_listBody"></tbody>
                <tfoot class="table-light fw-bold">
                  <tr>
                    <td colspan="4" class="text-end">합계</td>
                    <td class="text-end" id="sumQty">0</td>
                    <td></td>
                    <td class="text-end" id="sumSupply">0</td>
                    <td class="text-end" id="sumVAT">0</td>
                    <td class="text-end" id="sumTotal">0</td>
                  </tr>
                </tfoot>
              </table>
            </div>
          </div>
    </div>
  </div>
</div>
</div>

<div class="container"> 
<div class="row justify-content-center align-items-center ">	        
		<div class="card align-middle " style="width:70rem; padding:0;">	
		<div class="card-body text-center"  style="padding:4;" >							
			<div class="row d-flex justify-content-center align-items-center mb-3" >					
				<div class="col-sm-1">
					<div class="d-flex p-1 mb-1  justify-content-start align-items-center ">				
						<?=$mode?>								
				   </div>
				</div>			
				<div class="col-sm-9" >					
					<div class="d-flex p-1 mb-1  justify-content-center align-items-center ">	 
          <label for="devMode" class ="text-danger me-5" title="개발모드는 현업업무사용자는 나타나지 않습니다.">
              <input type="checkbox" id="devMode" name="devMode" data-readonly="true" value="1" <?= ($devMode === '1') ? 'checked' : '' ?>>
                개발모드             
              </label>            
          <h4>
            <?=$title_message?>
        </h4> &nbsp; &nbsp; &nbsp; &nbsp;

					<?php if($mode =='view') { ?>		
            <!-- 개발자전용 -->
					<button type="button" class="btn btn-dark btn-sm mx-1" onclick="location.href='write_form.php?mode=modify&num=<?=$num?>&tablename=<?=$tablename?>';" >  <i class="bi bi-pencil-square"></i>  수정 </button>
					<button id="copyBtn" class="btn btn-primary  btn-sm mx-1" type="button"><i class="bi bi-copy"></i> 복사</button>					
					<button id="deleteBtn" class="btn btn-danger  btn-sm mx-1" type="button"><i class="bi bi-trash2"></i> 삭제</button>						
					<?php } ?>		
				   <?php if($mode!=='view') { ?>
						<button id="saveBtn" class="btn  btn-dark btn-sm me-1 " type="button">
						<? if((int)$num>0) print ' <i class="bi bi-hdd-fill"></i> 저장';  else print ' <i class="bi bi-hdd-fill"></i> 저장'; ?></button>		   			
				   <?  } ?>		
					<button type="button" class="btn btn-outline-dark  btn-sm me-2" id="showlogBtn"   > H
					
						</div>
					</div>			
				<div class="col-sm-2" >					
					<button type="button" class="btn btn-outline-dark   btn-sm " onclick="self.close();" > <i class="bi bi-box-arrow-left"></i> 창닫기 </button>	&nbsp; 				
				</div>	
			   </div>	
			</div>
		</div>		
	</div>		
</div>	

<?php include $_SERVER['DOCUMENT_ROOT'] . '/output/common/output_write_form.php'; //  공통으로 들어가는 부분  임시로 사용하는 1 붙임 ?>

<div class="container-fluid"> 

<div class="row d-flex justify-content-center align-items-center mb-1">	        
		<div class="col-sm-12 rounded"  > 
		<div class="card align-middle " >		
		<div class="card-body text-center">
			<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
				<span class="text-center badge bg-info-subtle border border-info-subtle text-dark fs-6 me-3"> 배송비 기록 </span>
				<button type='button' class='btn btn-outline-dark  btn-sm viewNoBtn add-row-deliveryfee me-2' data-table='deliveryfeeTable' style='margin-right: 5px; border:0px;'>+</button>
			</div>

			<div class="row p-1 mb-1 justify-content-center align-items-center">
				<table id="deliveryfeeTable" class="table table-hover table-bordered">
					<thead style="display: none;">
						<tr>
							<th class="text-center" >구분</th>
							<th class="text-center" >하차업체명</th>
							<th class="text-center" >상차지</th>
							<th class="text-center" >물류업체명</th>
							<th class="text-center" >차량톤수</th>
							<th class="text-center" >금 액</th>
							<th class="text-center" >부가세</th>
							<th class="text-center" >합계</th>
							<th class="text-center" >착/선불</th>
							<th class="text-center" >차량번호</th>	
							<th class="text-center" >기사 연락처</th>
							<th class="text-center" >비고</th>
						</tr>
					</thead>
					<tbody id="deliveryfeeTableBody">
						<!-- JavaScript에서 동적으로 생성된 행이 여기에 추가됩니다 -->
					</tbody>
				</table>
			</div>
		</div>
	</div>
	</div>
	</div>  
</div> <!-- end of container 배송비 기록 -->

 <!-- 비인정제품/부자재 보기 -->
<div id="showUAcontainer" class="container-fluid"> 
	<div class="card align-middle">
		<div class="card-body text-start align-items-center">
			<button type="button" id="showGroupViewBtn" class="btn btn-primary btn-sm me-3">
				<i class="bi bi-chevron-down" id="showGroupViewIcon"></i> &nbsp; 비인정제품/부자재 보기
			</button>      
   
      <?php if($mode !== 'view'): ?>            
        <button type="button" id="deleteUnapprovedBtn" class="btn btn-outline-danger btn-sm me-3" onclick="deleteAllUnapprovedItems()"> <i class="bi bi-trash"></i> 비인정 전체 삭제 </button>
        <?php  else : ?>																								
									<button type='button' id="loadOrderBtn_UA" class='btn btn-warning-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> 발주서 </button>
									<button type='button' id="loadScreenWorkBtn_UA" class='btn btn-primary-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> (스크린) 작업일지 </button>
									<button type='button' id="loadSlatWorkBtn_UA" class='btn btn-primary-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> (철재) 작업일지 </button>
									<button type='button' id="loadBendingWorkBtn_UA" class='btn btn-success-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> 절곡 작업일지 </button>
									<button type='button' id="loadOutputWorkBtn_UA" class='btn btn-secondary-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> 출고증 </button>									
									<!-- 
                  <button type='button' id="loadmidInspectScreenBtn_UA" class='btn btn-danger-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> 중간검사 </button>                   
									<button type='button' id="loadmidInspectBendingBtn_UA" class='btn btn-danger-subtle btn-sm me-2 shadow-sm hover-lift' style="transition: all 0.2s ease; transform: translateY(0);" onmouseover="this.style.transform='translateY(-3px)'; this.style.boxShadow='0 4px 8px rgba(0,0,0,0.1)'; this.style.backgroundColor='#e9ecef';" onmouseout="this.style.transform='translateY(0)'; this.style.boxShadow='0 2px 4px rgba(0,0,0,0.05)'; this.style.backgroundColor='';"><i class="bi bi-card-text"></i> 절곡-중간검사 </button>
                  -->
      <?php endif; ?>

			<div id="showGroupViewDiv" class="mt-5">			
		<!-- ================================================
     비인정 스크린 테이블 영역
    ================================================ -->
    <div class="row d-flex justify-content-start align-items-center mb-1">
    <div class="col-sm-12 rounded">
        <div class="d-flex p-1 mb-1 justify-content-start align-items-center">
            <span class="text-center badge bg-primary-subtle border border-primary-subtle text-dark fs-6 me-3">
                스크린 비인정제품
            </span>
            <?php if($mode !== 'view'): ?>                          
              <button type="button" class="btn btn-outline-dark btn-sm viewNoBtn add-row-screen-unapproved" style="margin-right:5px; border:0px;"> + </button>
              <button type="button" id="screen_unapprovedTableRemoveAllBtn" class="btn btn-outline-danger btn-sm viewNoBtn mx-2" style="padding:2px;"> 행전체 <i class="bi bi-trash"></i> </button>
              <!-- 변환 버튼 -->
              <button id="convertUnapprovedBtn" type="button" class="btn btn-outline-primary btn-sm viewNoBtn">작업지시서로 변환</button>
            <?php endif; ?>
        </div>
        <div class="row p-1 mb-1 justify-content-start align-items-center">
            <table id="screen_unapprovedTable" class="table table-hover table-bordered">
              <thead>
                    <tr class="table-secondary text-center">
                        <th >번호</th>
                        <th class="text-dark" style="width: 130px;">종류</th>
                        <th class="text-dark" style="width: 50px;">층</th>
                        <th class="text-dark" style="width: 100px;">부호</th>
                        <th class="text-dark" style="width: 150px;">추가메모</th>
                        <th class="text-danger" style="width: 70px;">가로(W)</th>
                        <th class="text-primary" style="width: 70px;">세로(H)</th>
                        <th class="text-dark" style="width: 40px;">수량(틀)</th>
                        <th class="text-dark" style="width: 110px;">비상문</th>
                        <th class="text-dark" style="width: 70px;">인쇄면</th>
                        <th class="text-dark" style="width: 80px;">인쇄방향</th>
                        <th class="text-dark" style="width: 80px;">좌간격</th>
                        <th class="text-dark" style="width: 80px;">우간격</th>
                        <th class="text-dark" style="width: 80px;">개구부</th>
                        <th class="text-dark" style="width: 80px;">덮개폭</th>
                        <th class="text-dark" style="width: 100px;">좌문구</th>
                        <th class="text-dark" style="width: 80px;">중앙문구</th>
                        <th class="text-dark" style="width: 100px;">우문구</th>
                        <th class="text-dark" style="width: 90px;">도면</th>
                        <th class="text-dark" style="width: 200px;">발주서 기록</th>                        
                    </tr>
                </thead>
                <tbody id="screen_unapprovedListBody">
                </tbody>
            </table>
        </div>
    </div>
</div>  <!-- end of 비인정스크린 -->

<!-- ================================================
   비인정 철재-슬랫 모듈
================================================ -->
<div id="slat-unapproved-module" class="row d-flex justify-content-start align-items-center mb-1">
  <div class="col-sm-12 rounded">
    <!-- 툴바 -->
    <div class="d-flex p-1 mb-1 justify-content-start align-items-center">
      <span class="badge bg-info-subtle border border-info-subtle text-dark fs-6 me-3">
        비인정 철재-슬랫
      </span>
      <?php if($mode !== 'view'): ?>
      <button type="button" class="btn btn-outline-dark btn-sm viewNoBtn add-row-slat-unapproved me-2" style="border:0;">+</button>
      <button type="button" id="slat_unapprovedTableRemoveAllBtn" class="btn btn-outline-danger btn-sm viewNoBtn mx-2" style="padding:2px;" >행전체 <i class="bi bi-trash"></i></button>
      <!-- 변환 버튼 -->
      <button id="convertUnapproved_slatBtn" type="button" class="btn btn-outline-primary btn-sm viewNoBtn">작업지시서로 변환</button>
      <?php endif; ?>
    </div>

    <!-- 테이블 -->
    <div class="row p-1 mb-1">
      <table id="slat_unapprovedTable" class="table table-hover table-bordered text-center">
        <thead class="table-secondary">
          <tr>            
            <th style="width:80px;">번호</th>
            <th style="width:100px;">품목</th>
            <th style="width:50px;">층</th>
            <th style="width:100px;">부호</th>
            <th style="width:80px;">재질</th>
            <th style="width:60px;" class="text-danger">가로(W)</th>
            <th style="width:60px;" class="text-primary">세로(H)</th>
            <th style="width:30px;">수량<br>(EA)</th>
            <th style="width:60px;">비상문</th>
            <th style="width:50px;">띄울<br>치수</th>
            <th style="width:60px;">힌지<br>종류</th>
            <th style="width:70px;">힌지<br>띄울치수</th>
            <th style="width:70px;">힌지<br>방향</th>
            <th style="width:530px;">발주서 기록</th>            
          </tr>
        </thead>
        <tbody id="slat_unapprovedListBody">
          <!-- addRowUA_slat로 동적 추가 -->
        </tbody>
      </table>
    </div>
  </div>
</div>
<!-- end of 비인정 철재-슬랫 모듈 -->


<!-- 전동 개폐기 & 베어링부(브라켓트) -->
<div class="row d-flex justify-content-start align-items-center mb-1">
	<div class="col-sm-11 rounded">
		<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
			<span class="text-center badge bg-success-subtle border border-success-subtle text-dark fs-6 me-3"> 전동 개폐기 & 베어링부(브라켓트) </span>
      <?php if($mode !== 'view'): ?>            
        <button type='button' class='btn btn-outline-dark  btn-sm viewNoBtn add-row-motor me-2' data-table='motor_table' style='margin-right: 5px; border:0px;'>+</button>
        <button type='button' id="motor_tableRemoveAllBtn" class='btn btn-outline-danger  btn-sm viewNoBtn mx-2'  style='padding:2px;'> 행전체 <i class='bi bi-trash'></i>  </button>
      <?php endif; ?>
		</div>
		<div class="row p-1 mb-1 justify-content-start align-items-center">
			<table id="motor_table" class="table table-hover table-bordered">
				<thead style="display: none;">
					<tr class="table-secondary text-center">
						<th rowspan="2">일련번호</th>
						<th rowspan="2">품명</th>
						<th rowspan="2">모터 용량</th>
						<th colspan="2">사이즈</th>
						<th rowspan="2" class="text-center w-10">수량</th>
						<th rowspan="2">구형/신형</th>
						<th rowspan="2">안전리미트</th>
						<th rowspan="2">비고</th>
					</tr>
					<tr class="table-secondary text-center">
						<th>브라켓(mm)</th>
						<th>샤프트(인치)</th>
					</tr>
				</thead>
				<tbody id="motor_listBody">
					<!-- JavaScript로 동적으로 행 추가 -->
				</tbody>
			</table>
		</div>
	</div>
</div>

<!-- 연동 폐쇄기구(제어기) & 방범스위치 -->
<div class="row d-flex justify-content-start align-items-center mb-1">
	<div class="col-sm-8 rounded">
		<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
			<span class="text-center badge bg-success-subtle border border-success-subtle text-dark fs-6 me-3"> 연동 폐쇄기구(제어기) & 방범스위치 </span>
      <?php if($mode !== 'view'): ?>            
        <button type='button' class='btn btn-outline-dark  btn-sm viewNoBtn add-row-controller me-2' data-table='controller_table' style='margin-right: 5px; border:0px;'>+</button>
        <button type='button' id="controller_tableRemoveAllBtn" class='btn btn-outline-danger  btn-sm viewNoBtn mx-2'  style='padding:2px;'> 행전체 <i class='bi bi-trash'></i>  </button>
      <?php endif; ?>
		</div>
		<div class="row p-1 mb-1 justify-content-start align-items-center">
			<table id="controller_table" class="table table-hover table-bordered">
				<thead style="display: none;">
					<tr class="table-secondary text-center">
						<th rowspan="2">일련번호</th>
						<th rowspan="2">품명</th>
						<th rowspan="2" class="w-10" >수량</th>
						<th rowspan="2" class="w-15" >구형/신형</th>						
						<th rowspan="2">비고</th>
					</tr>					
				</thead>
				<tbody id="controller_listBody">
					<!-- JavaScript로 동적으로 행 추가 -->
				</tbody>
			</table>
		</div>
	</div>
</div>

<!-- 절곡품 – 규격 및 타입은 도면 참조 -->
<div class="row d-flex justify-content-start align-items-center mb-1">
    <div class="col-sm-9 rounded">
        <div class="d-flex p-1 mb-1 justify-content-start align-items-center">
            <span class="text-center badge bg-danger-subtle border border-danger-subtle text-dark fs-6 me-3"> 절곡품 - 규격 및 타입은 도면 참조 </span>
            <?php if($mode !== 'view'): ?>            
              <button type='button' class='btn btn-outline-dark  btn-sm viewNoBtn add-row-bend me-2' data-table='bend_table' style='margin-right: 5px; border:0px;'>+</button>
              <button type='button' id="bendRowRemoveAllBtn" class='btn btn-outline-danger  btn-sm viewNoBtn mx-2' data-table='bend_table' style='padding:2px;'> 행전체 <i class='bi bi-trash'></i>  </button>
              <input type="checkbox" id="requestBendingASSY" name="requestBendingASSY" class="mx-2" value="1" <?= $requestBendingASSY == '1' ? 'checked' : '' ?>>
              <label for="requestBendingASSY" class="me-5">절곡 바라시 요청</label>                    
              <span class='text-danger fw-bold mx-5'> 풀세트 불러오기 </span>
              <button type='button' id="loadScreenOutBtn" class='btn btn-outline-primary btn-sm viewNoBtn mx-2' data-table='bend_table'> 스크린 노출형 </button>
              <button type='button' id="loadScreenInBtn" class='btn btn-outline-primary btn-sm viewNoBtn mx-2' data-table='bend_table'> 스크린 매립형 </button>
              <button type='button' id="loadSlatOutBtn" class='btn btn-outline-success btn-sm viewNoBtn mx-2' data-table='bend_table'> 철재스라트 노출형 </button>
              <button type='button' id="loadSlatInBtn" class='btn btn-outline-success btn-sm viewNoBtn mx-2' data-table='bend_table'> 철재스라트 매립형 </button>            
            <?php endif; ?>
        </div>
        <div class="row p-1 mb-1 justify-content-start align-items-center">
            <table id="bend_table" class="table table-hover table-bordered">
				<thead style="display: none;">
                    <tr class="table-secondary text-center">
                        <th class="text-center w-10">일련번호</th>
                        <th class="text-center w-20">품명</th>
                        <th class="text-center w-15">두께</th>
                        <th class="text-center w-10">길이(mm)</th>
                        <th class="text-center w-5">검색</th>
                        <th class="text-center w-10">폭합(mm)</th>
                        <th class="text-center w-10">이미지</th>
                        <th class="text-center w-10">수량</th>
                        <th>비고</th>
                    </tr>
                </thead>
                <tbody id="bend_listBody">
                    <!-- JavaScript로 동적으로 행 추가 -->
                </tbody>
            </table>
        </div>
    </div>
</div>
<!-- 비인정제품/ 부자재 -->
	<div class="row d-flex justify-content-start align-items-center mb-1">	        
		<div class="col-sm-9 rounded"  > 	
			<div class="d-flex p-1 mb-1 justify-content-start align-items-center">
				<span class="text-center badge bg-secondary-subtle border border-secondary-subtle text-dark fs-6 me-3"> 부자재 </span>
        <?php if($mode !== 'view'): ?>            
          <button type='button' class='btn btn-outline-dark  btn-sm viewNoBtn add-row-etc me-2' data-table='etc_table' style='margin-right: 5px; border:0px;'>+</button>
          <button type='button' id="etc_tableRemoveAllBtn" class='btn btn-outline-danger  btn-sm viewNoBtn mx-2'  style='padding:2px;' > 행전체 <i class='bi bi-trash'></i>  </button>
        <?php endif; ?>
			</div>
			<div class="row p-1 mb-1 justify-content-start align-items-center">
				<table id="etc_table" class="table table-hover table-bordered">
					<thead style="display: none;">
					   <tr class="table-secondary text-center">
							<th class="text-center w-10" >일련번호</th>
							<th class="text-center w-20" >품명</th>
							<th class="text-center w-15" >규격</th>
							<th class="text-center w-10" >길이(mm)</th>
							<th class="text-center w-10" >수량</th>
							<th class="text-center w-25" >비고</th>
						</tr>
					</thead>
					<tbody id="etc_listBody">
						<!-- JavaScript에서 동적으로 생성된 행이 여기에 추가됩니다 -->
					</tbody>
					</table>
			</div>
		</div>
	  </div>	
	</div>
	</div>
	</div>	
	</div> <!-- end of card-body -->
	</div> <!-- end of card -->

</div>

<div class="container-fluid mt-5"> 
	<!-- 스크린견적서 기준으로 여러가지 응용버튼 만들기 -->
<div id="screenWindow" >		 	
	<div class="card align-middle " style="padding:2;">	
	<div class="card-body text-center"  style="padding:2;" >							
		<div class="row d-flex justify-content-center align-items-center" >					
			<div class="col-sm-12" >			
				<div class="d-flex p-1 justify-content-start align-items-center ">				
					<!-- 견적서 작성 -->
					<div id="estimate" class="container-fluid">    
					  <div class="row justify-content-center align-items-center mt-1 mb-1">   
					  	<div class="d-flex justify-content-start align-items-center">
							<button  type="button" id="estimate_view" class="btn btn-dark btn-sm ms-2 me-3 mt-1"> <i class="bi bi-chevron-down" id="estimate_viewIcon"></i> </button> 							
							<h5> <span class="text-primary me-5"> 스크린  </span>  </h5>
						     <?php if($mode!=='view') { ?>    
								  <button type='button' id="loadEstimateBtn" class='btn btn-primary btn-sm me-2' ><i class="bi bi-pencil-square"></i> 견적서 불러오기  </button>
								  <button type='button' id="editOrderBtn" class='btn btn-dark btn-sm me-2' ><i class="bi bi-pencil-square"></i> 발주서 수정 </button>
							  <?php } else { ?>															
									<button type='button' id="ViewEstimateBtn" class='btn btn-primary btn-sm me-2' ><i class="bi bi-card-text"></i> 견적서 </button>
									<button type='button' id="loadOrderBtn" class='btn btn-warning btn-sm me-2' ><i class="bi bi-card-text"></i> 발주서 </button>
									<button type='button' id="loadScreenWorkBtn" class='btn btn-primary btn-sm me-2' ><i class="bi bi-card-text"></i> 스크린 작업일지 </button>
									<button type='button' id="loadBendingWorkBtn" class='btn btn-success btn-sm me-2' ><i class="bi bi-card-text"></i> 절곡 작업일지 </button>
									<button type='button' id="loadOutputWorkBtn" class='btn btn-secondary btn-sm me-2' ><i class="bi bi-card-text"></i> 출고증 </button>
									<button type='button' id="loadConfirmBtn" class='btn btn-secondary btn-sm me-2' ><i class="bi bi-card-text"></i> 납품확인서 </button>
									<button type='button' id="loadmidInspectScreenBtn" class='btn btn-danger btn-sm me-2' ><i class="bi bi-card-text"></i> 스크린-중간검사 </button>
									<button type='button' id="loadmidInspectBendingBtn" class='btn btn-danger btn-sm me-2' ><i class="bi bi-card-text"></i> 절곡-중간검사 </button>
							  	  <?php } ?>	
						</div>						
						</div>
					</div>
				   
			   </div>
			</div>					
		   </div>	
		</div>
	</div>	   
</div>	   

<div class="row d-flex justify-content-center align-items-center  mt-1 mb-1 rounded" >	
	<div id="estimate_screenDiv"> 
	</div>
</div>
<!-- screen작업지시서 자료 추가 삭제 -->
<div class="row d-flex justify-content-center align-items-center  mt-1 mb-1 rounded" >	
<div class="card align-middle " >
<div class="card-body text-center" >
<div id="screen_order" >	  
  <div class="row justify-content-start align-items-center mt-1 mb-1 p-2" >
     <div class="col-sm-1"> 		
	 </div>
	 <div class="col-sm-11">  
			<h4 class="text-center">
				<div class="d-flex justify-content-center align-items-center">    
					<span class="badge bg-primary"> 스크린  </span> &nbsp; 발주서 &nbsp;&nbsp;&nbsp;&nbsp;
					<span id="total_screen" class="badge bg-dark me-2"></span>
					<span id="total_screen_m2" class="badge bg-dark me-5"></span>
					<?php  if(!empty($mode)) { ?>
						<button type='button' id="viewscreenBtn" class='btn btn-primary btn-sm' > <i class="bi bi-person-workspace"></i> 작업지시서 보기</button>
					<?php  } ?>					
				</div>
			</h4> 
		</div>
    </div>
    <div class="row" id="screen-view">   	
        <table class="table table-bordered"  style="padding:2;">
            <thead>
                <tr>
                    <th class="text-dark w50px">
                        번호
                      <?php if($mode!=='view') { ?>    
                        <span class='text-success fs-6 hover-pointer' onclick='addRow(null)'>+</span>
                      <?php } ?>
                    </th>
                    <th class="text-dark w50px">층</th>					
                    <th class="text-dark w80px">부호</th>
                    <th class="text-dark w100px">추가메모</th>
                    <th class="text-danger w70px">가로(W)</th>
                    <th class="text-primary w70px">세로(H)</th>
                    <th class="text-dark w50px">수량(틀)</th>
                    <th class="text-dark w110px">비상문</th>
                    <th class="text-dark w70px">인쇄면</th>
                    <th class="text-dark w80px">인쇄방향</th>                    
                    <th class="text-dark w80px">좌간격</th>
                    <th class="text-dark w80px">우간격</th>
                    <th class="text-dark w80px">개구부</th>
                    <th class="text-dark w80px">덮개폭</th>
                    <th class="text-dark w80px">좌문구</th>
                    <th class="text-dark w80px">중앙문구</th>
                    <th class="text-dark w80px">우문구</th>
                    <th class="text-dark w80px">도면</th>                    
                    <th class="text-dark w120px">발주서 기록</th>
                  <?php if($mode!=='view') { ?>    
                    <th class="text-dark w110px">작업</th>
                  <?php } ?>    
                </tr>
            </thead>
            <tbody id="screenTable">
                <?php
                $counter = 0;
                // screenlist 컬럼의 요소
                $screenlist = isset($row['screenlist']) ? json_decode($row['screenlist'], true) : [];
				
                foreach ($screenlist as $screenlist_item) {
					// echo '<pre>';
					// print_r($screenlist_item);	
					// echo '</pre>';
                    $counter++;
                    $screenlist_item['num'] = $counter; // 고유 번호 부여

					$floors = isset($screenlist_item['floors']) ? trim($screenlist_item['floors']) : '';
					$text1 = isset($screenlist_item['text1']) ? trim($screenlist_item['text1']) : '';
					$cutwidth = isset($screenlist_item['cutwidth']) ? trim($screenlist_item['cutwidth']) : '';
					$cutheight = isset($screenlist_item['cutheight']) ? trim($screenlist_item['cutheight']) : '';
					$number = isset($screenlist_item['number']) ? trim($screenlist_item['number']) : '';
					$printside = isset($screenlist_item['printside']) ? trim($screenlist_item['printside']) : '';
					$direction = isset($screenlist_item['direction']) ? trim($screenlist_item['direction']) : '';
					$exititem = isset($screenlist_item['exititem']) ? trim($screenlist_item['exititem']) : '';

					if ($exititem == '0') {
						$intervalnum = '';
						$intervalnumsecond = '';
						$exitinterval = '';
						$cover = '';
					} else {
						$intervalnum = isset($screenlist_item['intervalnum']) ? trim($screenlist_item['intervalnum']) : '';
						$intervalnumsecond = isset($screenlist_item['intervalnumsecond']) ? trim($screenlist_item['intervalnumsecond']) : '';
						$exitinterval = isset($screenlist_item['exitinterval']) ? trim($screenlist_item['exitinterval']) : '';
						$cover = isset($screenlist_item['cover']) ? trim($screenlist_item['cover']) : '';
					}

					$memo = isset($screenlist_item['memo']) ? trim($screenlist_item['memo']) : '';
					$text2 = isset($screenlist_item['text2']) ? trim($screenlist_item['text2']) : '';
					$drawbottom1 = isset($screenlist_item['drawbottom1']) ? trim($screenlist_item['drawbottom1']) : '';
					$drawbottom2 = isset($screenlist_item['drawbottom2']) ? trim($screenlist_item['drawbottom2']) : '';
					$drawbottom3 = isset($screenlist_item['drawbottom3']) ? trim($screenlist_item['drawbottom3']) : '';
					$remain_check = isset($screenlist_item['remain_check']) ? trim($screenlist_item['remain_check']) : '';
					$done_check = isset($screenlist_item['done_check']) ? trim($screenlist_item['done_check']) : '';
					$mid_check = isset($screenlist_item['mid_check']) ? trim($screenlist_item['mid_check']) : '';
					$left_check = isset($screenlist_item['left_check']) ? trim($screenlist_item['left_check']) : '';
					$right_check = isset($screenlist_item['right_check']) ? trim($screenlist_item['right_check']) : '';
					$draw = isset($screenlist_item['draw']) ? trim($screenlist_item['draw']) : '';

          if($draw != 'screen0.jpg' && !empty($draw) && $draw != 'screennull.jpg')
                $imagePath = '../img/screen/' . $draw;
              else
                  $imagePath = '';                  
              ?>
              <tr>
                  <td><?=$counter?></td>
              <td><input type="text" class="form-control" name="floors[]" value="<?=$floors?>" placeholder="층" oninput="calculateRow(this)" autocomplete="off"></td>						
                  <td><input type="text" class="form-control" name="text1[]" value="<?=$text1?>" placeholder="부호" oninput="calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control" name="memo[]" value="<?=$memo?>" placeholder="추가메모" oninput="calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control" name="cutwidth[]" value="<?=$cutwidth?>" placeholder="가로(W)" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control" name="cutheight[]" value="<?=$cutheight?>" placeholder="세로(H)" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control" name="number[]" value="<?=$number?>" placeholder="수량(EA)" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td>
                      <select class="form-control exititem text-center" name='exititem[]' <?php if($mode=='view') echo 'data-readonly="true"'; ?> onchange='calculateRow(this)'>
                          <option value='0' <?= $exititem == '0' ? 'selected' : '' ?>>없음</option>
                          <option value='1' <?= $exititem == '1' ? 'selected' : '' ?>>중앙</option>
                          <option value='2' <?= $exititem == '2' ? 'selected' : '' ?>>좌측</option>
                          <option value='3' <?= $exititem == '3' ? 'selected' : '' ?>>우측</option>
                          <option value='4' <?= $exititem == '4' ? 'selected' : '' ?>>문2개</option>
                          <option value='5' <?= $exititem == '5' ? 'selected' : '' ?>>문2개 지그재그</option>
                      </select>
                  </td>
                  <td>
                      <select class="form-control printside text-center" name='printside[]' <?php if($mode=='view') echo 'data-readonly="true"'; ?> onchange='calculateRow(this)'>
                          <option value='' <?= $exititem == '0' ? 'selected' : '' ?>></option>
                          <option value='0' <?= $printside == '0' && $exititem != '0' ? 'selected' : '' ?>>양면</option>
                          <option value='1' <?= $printside == '1' && $exititem != '0' ? 'selected' : '' ?>>한면</option>
                      </select>
                  </td>
                  <td>
                      <select class="form-control direction text-center" name='direction[]'  <?php if($mode=='view') echo 'data-readonly="true"'; ?>  onchange='calculateRow(this)'>
                          <option value='' <?= $exititem == '0' ? 'selected' : '' ?>></option>
                          <option value='0' <?= $direction == '0' && $exititem != '0' ? 'selected' : '' ?>>정방향</option>
                          <option value='1' <?= $direction == '1' && $exititem != '0' ? 'selected' : '' ?>>역방향</option>
                      </select>
                  </td>
                  <td><input type="text" class="form-control intervalnum" name="intervalnum[]" value="<?=$intervalnum?>" placeholder="좌간격" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control intervalnumsecond" name="intervalnumsecond[]" value="<?=$intervalnumsecond?>" placeholder="우간격" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control exitinterval" name="exitinterval[]" value="<?=$exitinterval?>" placeholder="개구부" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control cover" name="cover[]" value="<?=$cover?>" placeholder="덮개" oninput="inputNumbers(this); calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control drawbottom1" name="drawbottom1[]" value="<?=$drawbottom1?>" placeholder="좌" oninput="calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control drawbottom3" name="drawbottom3[]" value="<?=$drawbottom3?>" placeholder="중앙" oninput="calculateRow(this)" autocomplete="off"></td>
                  <td><input type="text" class="form-control drawbottom2" name="drawbottom2[]" value="<?=$drawbottom2?>" placeholder="우" oninput="calculateRow(this)" autocomplete="off"></td>
						<td class="draw">
							<img src="<?=$imagePath?>" 
								 <?php if (!empty($imagePath)) echo 'style="width: 150px; height: auto; display: inline-block;"'; else echo 'style="width: 150px; height: auto;  display: none;"'; ?> 
								 onclick="showLargeImage(this)">
							<input type="hidden" name="draw[]" value="<?=$draw?>">
						</td>       
                <td><input type="text" class="form-control text2" name="text2[]" value="<?=$text2?>" readonly></td>
                <?php if($mode!=='view') { ?>                        
						<td>
							<span class="text-primary fs-6 hover-pointer ms-1 me-2" onclick="copyRow(this)">
								<i class="bi bi-copy"></i>
							</span>
							<span class="text-success fs-6 hover-pointer ms-1 me-2" onclick="addRow(this)">+</span>
							<span class="text-danger fs-6 hover-pointer ms-1" onclick="removeRow(this)">-</span>
						</td>
              <?php } ?>                                                    
                 <td style="display:none;" >
							<input type="text" class="form-control done_check" name="done_check[]" value="<?=$done_check?>" style="display:none;" >
							<input type="text" class="form-control remain_check" name="remain_check[]" value="<?=$remain_check?>" style="display:none;" >
							<input type="text" class="form-control mid_check" name="mid_check[]" value="<?=$mid_check?>" style="display:none;" >
							<input type="text" class="form-control left_check" name="left_check[]" value="<?=$left_check?>" style="display:none;" >
							<input type="text" class="form-control right_check" name="right_check[]" value="<?=$right_check?>" style="display:none;" >
						</td>                        
                </tr>
                <?php
                }
                ?>
            </tbody>
        </table>
		</div>  <!-- end of screen-view table -->


	</div>
</div>
</div>
</div>

<!-- 철재(스라트) slat 견적서불러오기, 작업일지 등  -->
<div id="slatWindow" >	
	<!-- 견적서 등 여러가기 불러오기 만들기 버튼그룹 -->
	<div class="card align-middle " style="padding:2;">	
	<div class="card-body text-center"  style="padding:2;" >							
		<div class="row d-flex justify-content-center align-items-center" >					
			<div class="col-sm-12" >			
				<div class="d-flex p-1 justify-content-start align-items-center ">				
					<!-- 견적서 작성 -->
					<div id="estimate_slat" class="container-fluid">    
					  <div class="row justify-content-center align-items-center mt-1 mb-1">   
					  	<div class="d-flex justify-content-start align-items-center">
							<button  type="button" id="estimate_slat_view" class="btn btn-dark btn-sm ms-2 me-3 mt-1"> <i class="bi bi-chevron-down" id="estimate_slat_viewIcon"></i> </button> 
							<h5> <span class="text-success me-5"> 철재스라트  </span>  </h5>
						     <?php if($mode!=='view') { ?>    
								  <button type='button' id="loadEstimateBtn_slat" class='btn btn-success btn-sm me-2' ><i class="bi bi-pencil-square"></i> 견적서 불러오기  </button>
								  <button type='button' id="editOrderBtn_slat" class='btn btn-dark btn-sm me-2' ><i class="bi bi-pencil-square"></i> 발주서 수정 </button>
							  <?php } else { ?>															
									<button type='button' id="ViewEstimateBtn_slat" class='btn btn-success-emphasis bg-success-subtle border border-success-subtle rounded-pill btn-sm fw-bold me-2' ><i class="bi bi-card-text"></i> 견적서 </button>
									<button type='button' id="loadOrderBtn_slat" class='btn btn-warning-emphasis bg-warning-subtle border border-warning-subtle rounded-pill btn-sm fw-bold   me-2' ><i class="bi bi-card-text"></i> 발주서 </button>
									<button type='button' id="loadSlatWorkBtn" class='btn btn-info-emphasis bg-info-subtle border border-info-subtle rounded-pill btn-sm fw-bold me-2' ><i class="bi bi-card-text"></i> 철재스라트 작업일지 </button>
									<button type='button' id="loadBendingWorkBtn_slat" class='btn btn-success-emphasis bg-success-subtle border border-success-subtle rounded-pill btn-sm  fw-bold me-2' ><i class="bi bi-card-text"></i> 절곡 작업일지 </button>
									<button type='button' id="loadOutputWorkBtn_slat" class='btn btn-secondary-emphasis bg-secondary-subtle border border-secondary-subtle rounded-pill btn-sm fw-bold  me-2' ><i class="bi bi-card-text"></i> 출고증 </button>
									<button type='button' id="loadConfirmBtn_slat" class='btn btn-secondary-emphasis bg-secondary-subtle border border-secondary-subtle rounded-pill btn-sm fw-bold  me-2' ><i class="bi bi-card-text"></i> 납품확인서 </button>
									<button type='button' id="loadmidInspectSlatBtn" class='btn btn-danger-emphasis bg-danger-subtle border border-danger-subtle rounded-pill btn-sm  fw-bold me-2' ><i class="bi bi-card-text"></i> 철재스라트-중간검사 </button>
									<button type='button' id="loadmidInspectJointbarBtn" class='btn btn-danger-emphasis bg-danger-subtle border border-danger-subtle rounded-pill btn-sm  fw-bold me-2' ><i class="bi bi-card-text"></i> 조인트바-중간검사 </button>
									<button type='button' id="loadmidInspectBendingBtn_slat" class='btn btn-danger-emphasis bg-danger-subtle border border-danger-subtle rounded-pill btn-sm  fw-bold me-2' ><i class="bi bi-card-text"></i> 절곡-중간검사 </button>
							  	  <?php } ?>	
						</div>						
						</div>
					</div>
				   
			   </div>
			</div>					
		   </div>	
		</div>
	</div>	   
</div>	   

<!-- 철재(스라트) slat 자료 발주서화면 -->
<div class="row d-flex justify-content-center align-items-center mt-1 mb-1 rounded" >	
	<div id="estimate_slatDiv"> 
	</div>
</div>

<!-- 철재(스라트) slat 자료 추가 삭제 -->
<div class="row d-flex justify-content-center align-items-center mt-1 mb-1 rounded" >	
<div class="card align-middle " >
<div class="card-body text-center" >
<div id="slat_order" >	  
  <div class="row justify-content-start align-items-center mt-1 mb-1 p-2" >
     <div class="col-sm-1">
	 </div>
	 <div class="col-sm-11">
			<h4 class="text-center">
				<div class="d-flex justify-content-center align-items-center">    
						<span class="badge bg-info"> 철재(스라트) </span>&nbsp; 발주서 &nbsp;&nbsp;&nbsp;&nbsp;
					<span id="total_slat" class="badge bg-dark me-2"></span>
					<span id="total_slat_m2" class="badge bg-dark me-5"></span>
					<?php  if(!empty($mode)) { ?>
						<button type='button' id="viewslatBtn" class='btn btn-info btn-sm' > <i class="bi bi-person-workspace"></i> 작업지시서 보기</button>
					<?php  } ?>	
				</div>
			</h4> 
		</div>
    </div>
    <div class="row" id="slat-view">    
        <table class="table table-bordered">
      <thead>
      <tr>
          <th class="text-dark w40px">
              번호
            <?php if($mode!=='view') { ?>  
              <span class='text-success fs-6 hover-pointer' onclick='addRow_slat(null)'>+</span>		
            <?php } ?>
          </th>
          <th class="text-dark w50px">층</th>
          <th class="text-dark w130px">부호</th>
          <th class="text-dark w80px">재질</th>
          <th class="text-danger w70px">가로(W)</th>
          <th class="text-primary w70px">세로(H)</th>
          <th class="text-dark w50px">수량(틀)</th>
          <th class="text-dark w80px">비상문</th>                    
          <th class="text-dark w80px">띄울치수</th>
          <th class="text-dark w80px">힌지<br>종류</th>                 
          <th class="text-dark w80px">힌지<br>띄울치수</th>                 
          <th class="text-dark w70px">힌지<br>방향</th>                 
          <th class="text-dark w500px">발주서 기록</th>
        <?php if($mode!=='view') { ?>    
          <th class="text-dark w80px">작업</th>
        <?php } ?>    
      </tr>
      </thead>
      <tbody id="slatTable">
      <?php
        $counter = 0;
        // slatlist 컬럼의 요소
        $slatlist = isset($row['slatlist']) ? json_decode($row['slatlist'], true) : [];

          foreach ($slatlist as $slatlist_item) {
            $counter++;
            $slatlist_item['num'] = $counter; // 고유 번호 부여
            $text1 = isset($slatlist_item['text1']) ? trim($slatlist_item['text1']) : '';
            $floors = isset($slatlist_item['floors']) ? trim($slatlist_item['floors']) : '';
            $cutwidth = isset($slatlist_item['cutwidth']) ? trim($slatlist_item['cutwidth']) : '';
            $cutheight = isset($slatlist_item['cutheight']) ? trim($slatlist_item['cutheight']) : '';
            $number = isset($slatlist_item['number']) ? trim($slatlist_item['number']) : '';                    
            $exititem = isset($slatlist_item['exititem']) ? trim($slatlist_item['exititem']) : '';
            $hinge = isset($slatlist_item['hinge']) ? trim($slatlist_item['hinge']) : '';         
            $hingenum = isset($slatlist_item['hingenum']) ? trim($slatlist_item['hingenum']) : '';				
            $intervalnum = isset($slatlist_item['intervalnum']) ? trim($slatlist_item['intervalnum']) : '';                                                                    
            $memo = isset($slatlist_item['memo']) ? trim($slatlist_item['memo']) : ''; // EGI 1.6, EGI 1.2
            $text2 = isset($slatlist_item['text2']) ? trim($slatlist_item['text2']) : '';                                        
            $done_check = isset($slatlist_item['done_check']) ? trim($slatlist_item['done_check']) : '';                    
            $hinge_direction = isset($slatlist_item['hinge_direction']) ? trim($slatlist_item['hinge_direction']) : '(없음)';          // 힌지 방향 추가 (정방향/역방향)          
          ?>                
          <tr>
              <td><?=$counter?></td>
              <td><input type="text" class="form-control" name="floors[]" value="<?=$floors?>" placeholder="층" oninput="slat_calculateRow(this)" autocomplete="off"></td>
              <td><input type="text" class="form-control" name="text1[]" value="<?=$text1?>" placeholder="부호" oninput="slat_calculateRow(this)" autocomplete="off"></td>
              <td>
          <select class="form-control " name="memo[]"  <?php if($mode=='view') echo 'data-readonly="true"'; ?>  onchange="slat_calculateRow(this)">
            <option value="EGI 1.6T" <?= $memo == 'EGI 1.6T' ? 'selected' : '' ?>>EGI 1.6T</option>
            <option value="EGI 1.2T" <?= $memo == 'EGI 1.2T' ? 'selected' : '' ?>>EGI 1.2T</option>
          </select>
        </td>						
          <td><input type="text" class="form-control" name="cutwidth[]" value="<?=$cutwidth?>" placeholder="가로(W)" oninput="inputNumbers(this); slat_calculateRow(this)" autocomplete="off"></td>
          <td><input type="text" class="form-control" name="cutheight[]" value="<?=$cutheight?>" placeholder="세로(H)" oninput="inputNumbers(this); slat_calculateRow(this)" autocomplete="off"></td>
          <td><input type="text" class="form-control" name="number[]" value="<?=$number?>" placeholder="수량(EA)" oninput="inputNumbers(this); slat_calculateRow(this)" autocomplete="off"></td>
          <td>
              <select class="form-control exititem text-center " name='exititem[]' <?php if($mode=='view') echo 'data-readonly="true"'; ?> onchange='slat_calculateRow(this)'>
                  <option value='0' <?= $exititem == '0' ? 'selected' : '' ?>>없음</option>
                  <option value='1' <?= $exititem == '1' ? 'selected' : '' ?>>중앙</option>
                  <option value='2' <?= $exititem == '2' ? 'selected' : '' ?>>좌측</option>
                  <option value='3' <?= $exititem == '3' ? 'selected' : '' ?>>우측</option>
              </select>
          </td>
        <td><input type="text" class="form-control intervalnum" name="intervalnum[]" value="<?=$intervalnum?>" placeholder="띄울치수" oninput="inputNumbers(this); slat_calculateRow(this)" autocomplete="off"></td>
        <td>
          <select class="form-control hinge text-center" name="hinge[]"  <?php if($mode=='view') echo 'data-readonly="true"'; ?>  >
            <?php
            $hingeOptions = ['', '승리', '태영', '굴비', '대신'];
            foreach ($hingeOptions as $option) {
              $selected = ($hinge == $option) ? 'selected' : '';
              echo "<option value='{$option}' {$selected}>{$option}</option>";
            }
            ?>
          </select> 
        </td>
        <td>
          <input type="text" class="form-control hingenum" name="hingenum[]" value="<?=$hingenum?>"  readonly>
        </td>    
        <td>
          <select class="form-control hinge_direction text-center" name="hinge_direction[]"  <?php if($mode=='view') echo 'data-readonly="true"'; ?>  >
            <?php
              $hingeOptions = ['(없음)', '정방향', '역방향'];
              foreach ($hingeOptions as $option) {
                $selected = ($hinge_direction == $option) ? 'selected' : '';
                echo "<option value='{$option}' {$selected}>{$option}</option>";
              }
            ?>
          </select> 
        </td>        
        <td>
          <input
            type="text" class="form-control text2 text-start" name="text2[]" value="<?=$text2?>" style="font-size: 11px!important;"  title="<?=$text2?>" readonly >
        </td>
              <?php if($mode!=='view') { ?>                        
        <td>
          <span class="text-primary fs-6 hover-pointer ms-1 me-2" onclick="slat_copyRow(this)">
            <i class="bi bi-copy"></i>
          </span>
          <span class="text-success fs-6 hover-pointer ms-1 me-2" onclick="addRow_slat(this)">+</span>
          <span class="text-danger fs-6 hover-pointer ms-1" onclick="slat_removeRow(this)">-</span>
        </td>

              <?php } ?>                                                    
                    <td style="display:none;" >
          <input type="text" class="form-control done_check" name="done_check[]" value="<?=$done_check?>" style="display:none;" >							
        </td>                        
                </tr>
                <?php
            }
            ?>
        </tbody>
    </table>
</div>
</div>
</div>
</div>
</div>  <!-- end of 철재(스라트) slat 자료 추가 삭제 -->

</div>
</form>

<!-- 수주입력/수정에 필요한 자바스크립트 모음 (개발자용 화면 뒤에 1을 붙임 -->
<!-- 개발자전용 수정위치 -->
<?php require_once($_SERVER['DOCUMENT_ROOT'] . "/output/write_form_script.php"); ?>

</body>
</html>