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

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

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

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

$tablename = 'output';

$title_message = "스크린 작업 ";

require_once $_SERVER['DOCUMENT_ROOT'] . '/load_GoogleDriveSecond.php'; // attached, image에 대한 정보 불러오기  

include $_SERVER['DOCUMENT_ROOT'] . '/mymodal.php';
include $_SERVER['DOCUMENT_ROOT'] . '/output/common/function.php';   // 스크린절단사이즈 함수 불러오기
  
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();    
 
$today = date("Y-m-d"); // 현재일자 변수지정

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 $_SERVER['DOCUMENT_ROOT'] . "/output/_row.php";  
    }
} catch (PDOException $Exception) {
    print "오류: ".$Exception->getMessage();
}
?>
<title><?=$title_message?></title>
<style>
textarea {
overflow: hidden;
resize: none; /* 사용자 크기 조절을 방지 */
}  
/* 기본 스타일 설정 */
input[type="checkbox"],
input[type="radio"] {
	transform: scale(1.1); /* 크기 확대 */
	margin: 3px; /* 여백 추가 */
}

/* "readonly" 상태일 때 스타일 설정 */
.readonly-checkbox,
.readonly-radio {
	pointer-events: none; /* 사용자 상호작용 비활성화 */
	opacity: 1; /* 불투명도 설정 */
	color: red;
}

/* 레이블 텍스트 크게 설정 */
label {
	font-size: 1.2em; /* 글꼴 크기 확대 */
	display: inline-block;
	margin: 3px 0;
}
.w-40{
	 width: 40%!important;
}
.w-60{
	 width: 60%!important;
}
</style>
</head>

<body>
<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">
<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="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="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 : '' ?>">

<div class="container"> 
<div class="row justify-content-center align-items-center ">	        
    <div class="card align-middle " style="width: 55rem;">	
        <div class="card-body text-center">							
            <div class="row d-flex justify-content-center align-items-center mb-2" >					
                <div class="col-sm-10" >					
                    <div class="d-flex p-1 mb-1  justify-content-center align-items-center ">	
                        <h3><?=$title_message?></h3> &nbsp; &nbsp; &nbsp; &nbsp; 				
                        <?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</button>
                    </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 class="row text-center justify-content-center">
                <span class="text-primary fs-6">
                    관리자가 아래의 라디오버튼을 클릭하면 상태가 변경됩니다.
                </span>
            </div>
            <div class="row text-center justify-content-center">
                <div class="d-flex justify-content-center align-items-center w-75">
                    <table class="table table-bordered">
                        <tbody>
                            <tr class="text-center">
                                <td class="text-center" style="width:120px;">
                                    <span class="badge bg-dark fs-6">진행상태</span>
                                </td>
                                <td colspan="2" style="width:350px;">
                                    <?php
                                    $states = ["등록", "접수", "제작중", "완료"];
                                    $is_admin = ($user_name === '김동실' || $user_name === '개발자');
                                    ?>
                                    <?php foreach ($states as $state): ?>
                                        &nbsp; <?= $state ?>
                                        <input type="radio" class="readonly-radio" name="screen_state" value="<?= $state ?>" <?= ($screen_state === $state) ? "checked" : "" ?> <?= $is_admin ? "" : "readonly" ?> style="pointer-events: <?= $is_admin ? 'auto' : 'none' ?>;">
                                    <?php endforeach; ?>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            <button id="saveBtn" type="button" style="display:none;"></button>					
        </div>
    </div>		
 </div>	
</div>	

<?php include $_SERVER['DOCUMENT_ROOT'] . '/output/common/output_write_form.php'; //  공통으로 들어가는 부분 ?>

<div class="container-fluid"> 
  <div class="row justify-content-center align-items-center p-1 mt-1 mb-1">    		
		<div class="row ">    
			<div class="col-sm-6">    
				<div class="d-flex justify-content-end align-items-center">    
					<span class="text-center fs-4">
						스크린 작업 지시서 &nbsp;&nbsp;&nbsp;&nbsp;
						<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="loadmidInspectScreenBtn" class='btn btn-danger btn-sm me-2' ><i class="bi bi-card-text"></i> 중간검사 </button>
					</span>
				</div>
			</div>
			<div class="col-sm-6">    
				<div class="d-flex justify-content-end align-items-center">    					
					<span class="text-center fs-5">
						<span id="total_screen" class="badge bg-secondary me-2"></span>
						<span id="make_screen" class="badge bg-dark me-2"></span>
						<span id="total_screen_m2" class="badge bg-dark"></span>
					</span>
				</div>
			</div>
		</div>
  </div>
<div class="row">
    <div class="col-lg-12 col-sm-12">
        <div class="card">
            <div class="card-body text-center">      
                <div class="container-fluid">    
                    <div class="row">    
		<table id="screenTable" class="table table-bordered">
			<thead>
				<tr>
					<th class="text-dark w60px">번호</th>
					<th class="text-dark">층</th>
					<th class="text-dark">부호</th>
					<th class="text-dark" style="width:250px;">제작 너비(W)x높이(H), 수량(EA)</th>
					<th colspan="3" class="text-dark" style="width:400px;"> 제작 형태 </th>
					<th class="text-dark " style="width:400px;">제단 사항</th>
					<th class="text-dark w120px">전체 공정</th>
				</tr>
		</thead>
		<tbody>
			<?php
			$counter = 0;
			$screenlist = isset($row['screenlist']) ? json_decode($row['screenlist'], true) : [];

			foreach ($screenlist as $screenlist_item) {
				$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']) : '';
				
				$readonly = ($user_name !== '김동실' && $user_name !== '개발자') ? "readonly" : "";
				
				if(!empty($exitinterval))
					$text2 .= ' 개구부:' . $exitinterval . ', ';
				if(!empty($cover))
					$text2 .= '덮개:' . $cover ;
				
				?>
				<tr data-num="<?= $counter ?>">
					<td rowspan="2"><?= $counter ?></td>
					<td rowspan="2"><?= $floors ?></td>
					<td rowspan="2" class="text-center">
						<div class="d-flex justify-content-center fs-5">
							<span class="text-dark fs-6"><?= $text1 ?></span> &nbsp;
							<span class="badge bg-success fs-6"  data-bs-toggle="tooltip" data-bs-placement="bottom" title="실리카/와이어/화이바" ><?= $memo ?></span>
						</div>
					</td>
					<td rowspan="2" class="text-center">
						<div class="d-flex justify-content-center fs-6">
							<?= $text2 ?>
						</div>
					</td>
					<td colspan="3">
						<?php if (!empty($draw) &&  $draw != 'screennull.jpg'): ?>
							<img src="../img/screen/<?= $draw ?>" style="width: 600px; height: auto;">
						<?php endif; ?>
					</td>
				
					<td rowspan="2">
						<?php
						// 제품명에 따른 절단 치수 결정 ('실리카'는 1220, '와이어'는 1180, '화이'는 1200)
						if (strpos($memo, '와이') !== false) {
							$value = 1180;
                            $valueCut = 1180;
						} elseif (strpos($memo, '화이') !== false) {
							$value = 1200;
                            $valueCut = 1200;
						} elseif (strpos($memo, '실리') !== false) {
							$value = 1220;
                            $valueCut = 1220;
						} else {
							$value = 1220;
                            $valueCut = 1220;
						}
						
						$vertical = $cutheight;

						// 시접 부분을 더한 제작 높이 계산
						$makeVertical = $vertical + 140 + floor($vertical / $value) * 40;

						// 1) 1180 또는 1220 크기 계산
						$sizefirstCut = (int)floor(($makeVertical) / $value);				
						// echo '$sizefirstCut ' . $sizefirstCut;
						
						// 2) 나머지 높이 계산				
						$remaining_height = $makeVertical - ($sizefirstCut * $value);
						$First_remaining_height = $makeVertical - ($sizefirstCut * $value);
						
						// echo '$remaining_height ' . $remaining_height;				

						// 나머지 높이가 940 이상일 때 추가 절단
						if ($remaining_height > 940) {
							$sizefirstCut += 1;
							$remaining_height -= $value;
						}

						// 3) 공차를 적용한 규격 계산
						$size_900 = ($remaining_height >= 841 && $remaining_height <= 940) ? 1 : 0;
                        $size_800 = ($remaining_height >= 541 && $remaining_height <= 840) ? 1 : 0;
						$size_600 = ($remaining_height >= 441 && $remaining_height <= 640) ? 1 : 0;
						$size_400 = ($remaining_height >= 341 && $remaining_height <= 440) ? 1 : 0;
						$size_300 = ($remaining_height >= 1 && $remaining_height <= 340) ? 1 : 0;

						// 공차 조건에 맞으면 시접부분 40을 가산
						// if ($size_900 || $size_600 || $size_400 || $size_300) {
							// $First_remaining_height += 40;
						// }

						// 추가 문구 설정
						$dis_addstring = '';
						if ($size_900) {
							$dis_addstring .= '900 1(매), ';
						}
						if ($size_800) {
							$dis_addstring .= '800 1(매), ';
						}
						if ($size_600) {
							$dis_addstring .= '600 1(매), ';
						}
						if ($size_400) {
							$dis_addstring .= '400 1(매), ';
						}
						if ($size_300) {
							$dis_addstring .= '300 1(매), ';
						}
						// 마지막에 불필요한 쉼표와 공백을 제거
						$dis_addstring = rtrim($dis_addstring, ', ');

						// 기존 형식에 맞춘 출력 값
						$dis_text = "높이 " . $value . " 절단 : " . $sizefirstCut . " (매)";
						$dis_left = "나머지 높이 : " . $First_remaining_height . " (mm)";

                        $row_count = 0;

                        // 합계를 위한 변수 선언 (위쪽)
                        $totalfirstCut = 0;
                        $total_900     = 0;
                        $total_800     = 0;   
                        $total_600     = 0;
                        $total_400     = 0;
                        $total_300     = 0;
                                
                        // 세로 값을 가져옵니다 (col9가 F13에 해당)                        
                        $vertical = $cutheight;
                        $productName = $memo;

                        $result = calculateCutSize($productName,  $vertical);

                        $size_900 = $result['900'];
                        $size_800 = $result['800'];
                        $size_600 = $result['600'];
                        $size_400 = $result['400'];
                        $size_300 = $result['300'];
                        // 제품명에 따른 절단 치수 결정 ('실리카'는 1220, '와이어'는 1180, '화이바'는 1200)            
                        $result = calculateCutSize($productName,  $vertical);
                        
                        $size_900 = $result['900'];
                        $size_800 = $result['800'];
                        $size_600 = $result['600'];
                        $size_400 = $result['400'];
                        $size_300 = $result['300'];
            			
						// echo '<span class="text-dark  fs-6">' . $dis_text . '</span> <br>';
						// echo '<span class="text-dark  fs-6">' . $dis_left . '</span> <br>';
						// echo '<span class="text-primary fs-6">' . $dis_addstring . '</span>';
                        ?>

                        <div class="d-flex align-items-center justify-content-center m-1">
                        <table id="mainTable" class="table table-bordered" >
                            <thead>
                            <tr>                            
                                <td rowspan="2" class="text-center align-middle lightgray">나머지 <br> 높이</td>
                                <td colspan="6" class="text-center align-middle lightgray"> 규격(매수) </td>    
                            </tr>            
                            <tr>                                
                                <td class="text-center lightgray"> <?=$valueCut?> </td>
                                <td class="text-center lightgray">900</td>
                                <td class="text-center lightgray">800</td>
                                <td class="text-center lightgray">600</td>
                                <td class="text-center lightgray">400</td>
                                <td class="text-center lightgray">300</td>                
                            </tr>                          
                            </thead>
                            <tbody>
                                <tr>
                                    <?php
                                        // 나머지 높이 출력
                                        echo '<td class="text-center  fw-bold ">' . ($result['remaining'] > 0 ? $result['remaining'] : '') . '</td>';
                                        // 각 규격에 따른 수량 계산
                                        echo '<td class="text-center">'. ($result['firstCut'] >0 ? $result['firstCut'] : '') .'</td>';
                                        echo '<td class="text-center">'. ($size_900    >0 ? $size_900    : '') .'</td>';
                                        echo '<td class="text-center">'. ($size_800    >0 ? $size_800    : '') .'</td>';  
                                        echo '<td class="text-center">'. ($size_600    >0 ? $size_600    : '') .'</td>';
                                        echo '<td class="text-center">'. ($size_400    >0 ? $size_400    : '') .'</td>';
                                        echo '<td class="text-center">'. ($size_300    >0 ? $size_300    : '') .'</td>';

                                        echo '</tr>';
                                        $row_count++;
                                    ?>
                                </tr>
                            </tbody>
                            </tbody>
                        </table>
                    </div>
                    </div>



                    <?php
						$checked = $remain_check == '1' ? "checked" : "";
						echo '<div><input type="checkbox" name="remain_check[]" id="remain_check' . $counter . '" class="workcheckbox" ' . $checked . ' value="1" ' . $readonly . '> <label for="remain_check' . $counter . '">절단check</label></div>';
						?>
					</td>		

					<td rowspan="2">
						<?php
						$checked = $done_check == '1' ? "checked" : "";
						echo '<div><input type="checkbox" name="done_check[]" id="done_check' . $counter . '" class="workcheckbox" ' . $checked . ' value="1" ' . $readonly . '> <label for="done_check' . $counter . '">작업완료</label></div>';
						?>
					</td>
				</tr>
				<tr data-num="<?= $counter ?>">
					<td>
						<span class="text-dark fw-bold fs-5"><?= $drawbottom1 ?></span>
						<?php
						$checked = $left_check == '1' ? "checked" : "";
						if (in_array($exititem, ['1', '2', '3', '4', '5'])) {
							echo '<div><input type="checkbox" name="left_check[]" id="left_check' . $counter . '" class="workcheckbox" ' . $checked . ' value="1" ' . $readonly . '> <label for="left_check' . $counter . '">절단check</label></div>';
						}
						?>
					</td>
					<td>
						<span class="text-dark fw-bold fs-5"><?= $drawbottom3 ?></span>
						<?php
						$checked = $mid_check == '1' ? "checked" : "";
						if (in_array($exititem, ['0', '4', '5'])) {
							echo '<div><input type="checkbox" name="mid_check[]" id="mid_check' . $counter . '" class="workcheckbox" ' . $checked . ' value="1" ' . $readonly . '> <label for="mid_check' . $counter . '">절단check</label></div>';
						}
						?>
					</td>
					<td>
						<span class="text-dark fw-bold fs-5"><?= $drawbottom2 ?></span>
						<?php
						$checked = $right_check == '1' ? "checked" : "";
						if (in_array($exititem, ['1', '2', '3', '4', '5'])) {
							echo '<div><input type="checkbox" name="right_check[]" id="right_check' . $counter . '" class="workcheckbox" ' . $checked . ' value="1" ' . $readonly . '> <label for="right_check' . $counter . '">절단check</label></div>';
						}
						?>				
					</td>
				</tr>
				<?php
			}
			?>
			</tbody>
		</table>				   
		</div>
  	   </div>
      </div>
    </div>
  </div>
</div>
</div>
</form>

<script>
function captureReturnKey(e) {
    if (e.keyCode == 13 && e.srcElement.type != 'textarea')
        return false;
}

function recaptureReturnKey(e) {
    if (e.keyCode == 13)
        exe_search();
}

function Enter_Check() {
    if (event.keyCode == 13) {
        exe_search();
    }
}

$(document).ready(function() {
    var loader = document.getElementById('loadingOverlay');
	if(loader)
		loader.style.display = 'none';
});

var mode = '<?php echo $mode; ?>';
var ajaxRequest_write = null;

$(document).ready(function() {
    $("input[name='screen_state']").change(function() {
        if ($(this).is(":checked")) {
            $("#saveBtn").click();
        }
    });

    $("#saveBtn").click(function() {
        var form = $('#board_form')[0];
        var data = new FormData(form);
        savedata();
    });

    hideOverlay();
});

function savedata() {
    var form = $('#board_form')[0];
    var data = new FormData(form);

    $("#overlay").show();
    $("button").prop("disabled", true);

    Toastify({
        text: "저장중...",
        duration: 2000,
        close: true,
        gravity: "top",
        position: "center",
        style: {
            background: "linear-gradient(to right, #00b09b, #96c93d)"
        },
    }).showToast();

    if ((typeof ajaxRequest_write !== 'undefined' && ajaxRequest_write) || ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }

    ajaxRequest_write = $.ajax({
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        url: "insert.php",
        type: "post",
        data: data,
        dataType: "json",
        success: function(data) {
            // console.log(data.num);

            setTimeout(function() {
                Toastify({
                    text: "저장완료",
                    duration: 3000,
                    close: true,
                    gravity: "top",
                    position: "center",
                    style: {
                        background: "linear-gradient(to right, #00b09b, #96c93d)"
                    },
                }).showToast();
            }, 1000);

            setTimeout(function() {
                if (window.opener && !window.opener.closed) {
                    if (typeof window.opener.restorePageNumber === 'function') {
                        window.opener.restorePageNumber();
                    }
                }
                setTimeout(function() {
                    if (data && data.num)
                        window.location.href = 'write_form.php?mode=view&tablename=' + $('#tablename').val() + '&num=' + data.num;
                }, 1000);
            }, 1500);

            hideOverlay();
        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
        }
    });
}

$(document).ready(function() {
    var mode = '<?php echo $mode; ?>';

    if (mode === 'view') {
		
		$('input, textarea').prop('readonly', true); // Disable all input, textarea, and select elements
		$('input[type=hidden]').prop('readonly', false); 
		
        $('.viewon').prop('readonly', true);
        $('.viewNoBtn').prop('readonly', true);
        $('input[type=hidden]').prop('readonly', false);

        $('.viewon').each(function() {
            $(this).addClass('readonly-checkbox readonly-radio');
        });

        $('input[type=file]').prop('disabled', true);
        $('label').css('font-size', '1.2em');
		
		// select 속성 readonly 효과 내기
		$('select[data-readonly="true"]').on('mousedown', function(event) {
			event.preventDefault();
		});		
		
		// checkbox 속성 readonly 효과 내기
		$('input[type="checkbox"][data-readonly="true"]').on('click', function(event) {
			event.preventDefault();
		});		
    }
});

function adjustTextareaHeight(textarea) {
    textarea.style.height = 'auto';
    textarea.style.height = (textarea.scrollHeight) + 'px';
}

$(document).ready(function() {
	var $comment = $('#comment');
	if ($comment.length) {
		adjustTextareaHeight($comment[0]); // 초기 높이 조정
		$comment.on('input', function() {
			adjustTextareaHeight(this);
		});
	}
	
	var $updatecomment = $('#updatecomment');
	if ($updatecomment.length) {
		adjustTextareaHeight($updatecomment[0]); // 초기 높이 조정
		$updatecomment.on('input', function() {
			adjustTextareaHeight(this);
		});
	}
	
});

$(document).ready(function() {
    $("#showlogBtn").click(function() {
        var num = '<?php echo $num; ?>';
        var workitem = 'output';
        var btn = $(this);
        popupCenter("../Showlog.php?num=" + num + "&workitem=" + workitem, '로그기록', 500, 500);
        btn.prop('disabled', false);
    });
    $(document).on('click', '.Modalclose', function(e) {
        $("#telModal").modal("hide");
    });
});
var ajaxRequest = null;

$(document).ready(function() {
    let fullScreenlist = [];

    function fetchScreenlistAndUpdateCheckboxes() {
        if (ajaxRequest !== null) {
            ajaxRequest.abort();
        }

        ajaxRequest = $.ajax({
            url: 'get_screenlist.php',
            method: 'GET',
            data: {
                num: <?= $row['num'] ?>
            },
            success: function(response) {
                console.log('get_screenlist.php 결과값 : ', response);
                if (response.success) {
                    fullScreenlist = response.screenlist || [];
                    if (Array.isArray(fullScreenlist)) {
                        updateCheckboxes(fullScreenlist);
                        updateTotals(fullScreenlist);
                    } else {
                        console.error('Invalid screenlist format', fullScreenlist);
                    }
                } else {
                    console.error('Failed to fetch screenlist:', response.message);
                }
				
            }
        });
    }

    function updateCheckboxes(screenlist) {
        $('#screenTable tbody').children('tr').each(function(index, tr) {
            const row = $(tr);
            const item = screenlist[Math.floor(index / 2)];

            if (item) {
                for (const key in item) {
                    if (item.hasOwnProperty(key) && key.endsWith('_check')) {
                        row.find(`input[name="${key}[]"]`).prop('checked', item[key] === "1");
                    }
                }
            }
        });
    }

function onlysave() {
 var form = $('#board_form')[0];
    var data = new FormData(form);
    
    $("button").prop("disabled", true);
	
	showMsgModal(2); // 파일저장중

    if ((typeof ajaxRequest_write !== 'undefined' && ajaxRequest_write) || ajaxRequest_write !== null) {
        ajaxRequest_write.abort();
    }

    ajaxRequest_write = $.ajax({
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        cache: false,
        timeout: 600000,
        url: "insert.php",
        type: "post",
        data: data,
        dataType: "json",
        success: function(data) {		           
			if (window.opener && !window.opener.closed) {
				// 부모창 새로고침
				window.opener.location.reload();

				// 1초 대기 (예: 이후 작업이 있다면 여기서 처리 가능)
				setTimeout(function() {
					hideMsgModal();
					console.log('부모창 리로드 후 1초 경과');
					// 여기에 추가 작업이 있다면 넣으세요.
				}, 1000);
			}

        },
        error: function(jqxhr, status, error) {
            console.log(jqxhr, status, error);
		    hideMsgModal();
        }
    });	
}

function updateTotals() {
    if (ajaxRequest !== null) {
        ajaxRequest.abort();
    }

    ajaxRequest = $.ajax({
        url: 'get_check_done.php',
        method: 'GET',
        data: { num: <?= $row['num'] ?> },		
        success: function(response) {
            if (response.success) {	
				
			$('#make_screen').text('완료 : ' +response.total);
			
			// console.log('response ', response);            
			// Corrected property names according to the JSON response from the server
			var completedQuantity = response['totalCompleted'];  // Corrected from response['total']
			var checkQuantity = response['checkQuantity'];     // 하나라도 체크되어있으면
			var totalQuantity = response['totalItems'];          // Corrected from response.totalQuantity

			console.log('checkQuantity ', checkQuantity);          // Should log 4
			console.log('completedQuantity ', completedQuantity);  // Should log 4
			console.log('totalQuantity ', totalQuantity);          // Should log 6

                var newState = "";
                if (completedQuantity === 0 && checkQuantity === 0) {
                    newState = "접수";
                // } else if (completedQuantity < totalQuantity) {
                } else if (checkQuantity > 0 && completedQuantity !== totalQuantity) {
                    newState = "제작중";
                } else if (completedQuantity === totalQuantity) {
                    newState = "완료";
                }

                // Update the radio buttons for screen_state
                $('input[name="screen_state"]').each(function() {
                    if ($(this).val() === newState) {
                        $(this).prop('checked', true);
                    }
                });
				
				// 진행상태 저장
				onlysave();

                // Update the UI elements with the fetched data
                $('#total_screen').text(`총 수량: ${totalQuantity}`);
                $('#make_screen').text(`완료: ${completedQuantity}`);
                $('#total_screen_m2').text(`총 면적: ${parseFloat($("#screen_m2").val()).toFixed(1)} m²`);
            } else {
                console.error('Failed to fetch total:', response.message);
            }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('AJAX call failed: ', textStatus, errorThrown);
        }
    });
}	


    $('.workcheckbox').change(function() {
        var screenlist = [];

        $('#screenTable tbody').children('tr').each(function(index, tr) {
            if (index % 2 === 0) {
                const rowData = {};
                screenlist.push(rowData);
            }
        });

        $('#screenTable tbody').children('tr').each(function(index, tr) {
            const row = $(tr);
            const rowData = screenlist[Math.floor(index / 2)];

            row.find('.workcheckbox').each(function() {
                const checkbox = $(this);
                const name = checkbox.attr('name').replace('[]', '');
                rowData[name] = checkbox.is(':checked') ? "1" : "0";
            });
        });

        // console.log('Updated screenlist before sending to server:', screenlist);

        if (ajaxRequest !== null) {
            ajaxRequest.abort();
        }

        ajaxRequest = $.ajax({
            url: 'update_checkbox.php',
            method: 'POST',
            data: {
                num: <?= $row['num'] ?>,
                screenlist: JSON.stringify(screenlist)
            },
            success: function(response) {
                // console.log('update_checkbox.php', response);
				
				updateTotals();

                if (response.success) {
                    Toastify({
                        text: "설정 저장중...",
                        duration: 1000,
                        close: true,
                        gravity: "top",
                        position: "center",
                        style: {
                            background: "linear-gradient(to right, #000000, #96c93d)",
                            marginTop: "0px"
                        },
                    }).showToast();
                } else {
                    Toastify({
                        text: "저장실패...",
                        duration: 1000,
                        close: true,
                        gravity: "top",
                        position: "center",
                        style: {
                            background: "linear-gradient(to right, #000000, #96c93d)" 
                        },
                    }).showToast();
                }
            }
        });

     
    });

    // fetchScreenlistAndUpdateCheckboxes();
	updatesummary();
});

function updatesummary() {    
    let totalScreen = '<?php echo isset($screen_su) ? $screen_su : '' ?>';
    let totalScreenM2 = <?php echo isset($screen_m2) ? $screen_m2 : '' ?>;

    document.getElementById('total_screen').textContent = `총 수량: ${totalScreen}`;    
    document.getElementById('total_screen_m2').textContent = `총 면적: ${totalScreenM2.toFixed(1)} m²`;
}

// 부트스트랩 툴팁 
$(document).ready(function() {
  var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
  var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
    return new bootstrap.Tooltip(tooltipTriggerEl);
  });    	  
});

</script>

<script>
$(document).ready(function () {
	displayFileLoad();	// 기존파일 업로드 보이기			 	
});

// 기존 파일 불러오기 (Google Drive에서 가져오기)
function displayFileLoad() {
    $('#displayFile').show();
    var data = <?php echo json_encode($savefilename_arr); ?>;

    $("#displayFile").html(''); // 기존 내용 초기화

    if (Array.isArray(data) && data.length > 0) {
        data.forEach(function (fileData, i) {
            const realName = fileData.realname || '다운로드 파일';
            const link = fileData.link || '#';
            const fileId = fileData.fileId || null;

            if (!fileId) {
                console.error("fileId가 누락되었습니다. index: " + i, fileData);
                return;
            }

			$("#displayFile").append(
				"<div class='row mb-3'>" +
					"<div class='d-flex mb-3 align-items-center justify-content-start'>" +
						"<span id='file" + i + "'>" +
							"<a href='#' onclick=\"downloadFile('" + fileId + "', '" + realName + "'); return false;\">" +
								"<span class='fw-bold text-primary'>" + realName + "</span>" +
							"</a>" +
						"</span> &nbsp;&nbsp;" +
					"</div>" +
				"</div>"
			);

        });
    } else {
        $("#displayFile").append(
            "<div class='text-center text-muted'>No files</div>"
        );
    }
}

// 스크린작업일지 버튼 클릭 시
$(document).on('click', '#loadScreenWorkBtn', function() {
    var num = $("#num").val();    
    var url = '/output/viewScreenWork.php?num=' + num ;              
    // 팝업 호출
    customPopup(url, '스크린작업일지', 800, 900); 
});

// 스크린-중간검사 버튼 클릭 시
$(document).on('click', '#loadmidInspectScreenBtn', function() {
    var num = $("#num").val();    
    var url = '/output/viewMidInspectScreen.php?num=' + num ;              
    // 팝업 호출
    customPopup(url, '스크린-중간검사', 800, 900); 
});

</script>
</body>
</html>

