<?php
// shutterboxlist.php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  
if (!isset($_SESSION["level"]) || $_SESSION["level"] > 5) {
    sleep(1);
    header("Location: /login/login_form.php");
    exit;
}

$title_message = '케이스 결합형태 이미지 관리';
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';

$jsonFile = $_SERVER['DOCUMENT_ROOT'] . '/shutterbox/shutterbox.json';

$search_keyword = $_REQUEST['search_keyword'] ?? '';

// JSON 파일이 존재하면 읽어오고, 없으면 빈 배열 생성
$shutterboxData = [];
if (file_exists($jsonFile)) {
	$jsonContent = file_get_contents($jsonFile);
	$shutterboxData = json_decode($jsonContent, true);
	if (!is_array($shutterboxData)) {
		$shutterboxData = [];
	}
}

// POST 요청 처리: 추가, 수정, 삭제
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$action = isset($_POST['action']) ? $_POST['action'] : '';
	$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
	$box_width = isset($_POST['box_width']) ? trim($_POST['box_width']) : '';
	$box_height = isset($_POST['box_height']) ? trim($_POST['box_height']) : '';	
	$exit_direction = isset($_POST['exit_direction']) ? trim($_POST['exit_direction']) : '';
	$rail_width = isset($_POST['rail_width']) ? trim($_POST['rail_width']) : '';
	$front_bottom_width = isset($_POST['front_bottom_width']) ? trim($_POST['front_bottom_width']) : '';
	$search_keyword = isset($_POST['search_keyword']) ? trim($_POST['search_keyword']) : '';

	// 이미지 파일 업로드 처리 (drop 영역 및 일반 파일 input 모두 지원)
	$imagePath = '';
	// 1. drop 영역 처리
	if (isset($_FILES['upfile']) && isset($_FILES['upfile']['size'][0]) && $_FILES['upfile']['size'][0] > 0) {
		$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/shutterbox/images/';
		if (!file_exists($uploadDir)) {
			mkdir($uploadDir, 0777, true);
		}
		$originalName = $_FILES['upfile']['name'][0];
		$tmpName = $_FILES['upfile']['tmp_name'][0];
		$pathInfo = pathinfo($originalName);
		$fileName = $pathInfo['filename'];
		$fileExt = isset($pathInfo['extension']) ? $pathInfo['extension'] : '';
		$fileNameSanitized = preg_replace('/[^A-Za-z0-9_\-]/', '_', $fileName);
		$newFileName = date("Y_m_d_H_i_s") . "_" . $fileNameSanitized;
		if (!empty($fileExt)) {
			$newFileName .= "." . $fileExt;
		}
		$targetFile = $uploadDir . $newFileName;
		if (!move_uploaded_file($tmpName, $targetFile)) {
			echo json_encode(['error' => '파일 업로드 실패']);
			exit;
		}
		$imagePath = '/shutterbox/images/' . $newFileName;
	// 2. 일반 파일 input 처리
	} elseif (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
		$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/shutterbox/images/';
		if (!file_exists($uploadDir)) {
			mkdir($uploadDir, 0777, true);
		}
		$originalName = $_FILES['image']['name'];
		$tmpName = $_FILES['image']['tmp_name'];
		$pathInfo = pathinfo($originalName);
		$fileName = $pathInfo['filename'];
		$fileExt = isset($pathInfo['extension']) ? $pathInfo['extension'] : '';
		$fileNameSanitized = preg_replace('/[^A-Za-z0-9_\-]/', '_', $fileName);
		$newFileName = date("Y_m_d_H_i_s") . "_" . $fileNameSanitized;
		if (!empty($fileExt)) {
			$newFileName .= "." . $fileExt;
		}
		$targetFile = $uploadDir . $newFileName;
		if (!move_uploaded_file($tmpName, $targetFile)) {
			echo json_encode(['error' => '파일 업로드 실패']);
			exit;
		}
		$imagePath = '/shutterbox/images/' . $newFileName;
	}
	// 3. 기존 이미지 사용
	if (empty($imagePath) && isset($_POST['existing_image'])) {
		$imagePath = trim($_POST['existing_image']);
	}
	
	if ($action === 'insert' && !empty($exit_direction)) {
		// 신규 추가
		$shutterboxData[] = array(
			"box_width"      => $box_width ?? '',
			"box_height"     => $box_height ?? '',			
			"search_keyword" => $search_keyword ?? '',
			"exit_direction"       => $exit_direction ?? '',
			"rail_width"  => $rail_width ?? '',
			"front_bottom_width" => $front_bottom_width ?? '',
			"image"          => $imagePath ?? ''
		);
	} elseif ($action === 'update' && !empty($exit_direction) && $index >= 0 && $index < count($shutterboxData)) {
		// 수정
		$shutterboxData[$index]["box_width"]      = $box_width ?? '';
		$shutterboxData[$index]["box_height"]     = $box_height ?? '';			
		$shutterboxData[$index]["search_keyword"] = $search_keyword ?? '';
		$shutterboxData[$index]["exit_direction"]       = $exit_direction ?? '';
		$shutterboxData[$index]["rail_width"]  = $rail_width ?? '';
		$shutterboxData[$index]["front_bottom_width"] = $front_bottom_width ?? '';
		if (!empty($imagePath)) {
			$shutterboxData[$index]["image"] = $imagePath;
		}
	} elseif ($action === 'copy' && $index >= 0 && $index < count($shutterboxData)) {
		// 복사
		$originalItem = $shutterboxData[$index];
		$newImagePath = '';
		
		// 이미지가 있는 경우 복사
		if (!empty($originalItem['image'])) {
			$originalImagePath = $_SERVER['DOCUMENT_ROOT'] . $originalItem['image'];
			if (file_exists($originalImagePath)) {
				$pathInfo = pathinfo($originalImagePath);
				$fileName = $pathInfo['filename'];
				$fileExt = isset($pathInfo['extension']) ? $pathInfo['extension'] : '';
				$newFileName = $fileName . '_copy';
				if (!empty($fileExt)) {
					$newFileName .= "." . $fileExt;
				}
				$newImagePath = $pathInfo['dirname'] . '/' . $newFileName;
				
				// 파일 복사
				if (copy($originalImagePath, $newImagePath)) {
					$newImagePath = str_replace($_SERVER['DOCUMENT_ROOT'], '', $newImagePath);
				} else {
					$newImagePath = $originalItem['image']; // 복사 실패 시 원본 경로 사용
				}
			} else {
				$newImagePath = $originalItem['image']; // 원본 파일이 없으면 원본 경로 사용
			}
		}
		
		// 새로운 항목 추가
		$shutterboxData[] = array(
			"box_width"      => $originalItem['box_width'] ?? '',
			"box_height"     => $originalItem['box_height'] ?? '',			
			"search_keyword" => $originalItem['search_keyword'] ?? '',
			"exit_direction"       => $originalItem['exit_direction'] ?? '',
			"rail_width"  => $originalItem['rail_width'] ?? '',
			"front_bottom_width" => $originalItem['front_bottom_width'] ?? '',
			"image"          => $newImagePath
		);
		
		// 복사된 데이터를 폼에 설정하기 위한 변수들
		$box_width = $originalItem['box_width'] ?? '';
		$box_height = $originalItem['box_height'] ?? '';
		$exit_direction = $originalItem['exit_direction'] ?? '';
		$rail_width = $originalItem['rail_width'] ?? '';
		$front_bottom_width = $originalItem['front_bottom_width'] ?? '';
		$search_keyword = $originalItem['search_keyword'] ?? '';
	} elseif ($action === 'delete' && $index >= 0 && $index < count($shutterboxData)) {
		// 삭제
		array_splice($shutterboxData, $index, 1);
	}
	
	// JSON 파일에 저장
	file_put_contents($jsonFile, json_encode($shutterboxData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));    
}
?>
<style>
/* 편집할때 보여지는 이미지 크기 */
#previewContainer {
    width: 700px !important;
    height: auto !important;
}
</style>

</head>
<body>
<div class="container-fluid	mt-3">
    <div class="card">
        <div class="card-header d-flex justify-content-center align-items-center text-center">
            <h3><?= $title_message ?></h3>            
            <button type="button" class="btn btn-dark btn-sm mx-5" onclick="window.close();">
                <i class="bi bi-x-square"></i> 닫기
            </button>
        </div>
        <div class="card-body">
            <!-- 신규/수정 폼 -->
            <form id="shutterboxForm" method="post" action="shutterboxlist.php" enctype="multipart/form-data" class="row g-1">
                <input type="hidden" name="action" id="action" value="insert">
                <input type="hidden" name="index" id="index" value="-1">
                <input type="hidden" name="existing_image" id="existing_image" value="">
				<div class="d-flex justify-content-center">
				<div class="col-sm-5">
                <table class="table table-bordered table-sm ">								
					<thead class="table-secondary">
                    <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>
                    </tr>
					</thead>
					<tbody></tbody>
                    <tr>
                        <td>
                            <input type="text" name="box_width" id="box_width" value="<?= isset($box_width) ? htmlspecialchars($box_width, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center  " style="font-size: 0.7rem; height: 28px;" placeholder="크기(가로)" autocomplete="off">
                        </td>
                        <td>
                            <input type="text" name="box_height" id="box_height" value="<?= isset($box_height) ? htmlspecialchars($box_height, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center " style="font-size: 0.7rem;  height: 28px;" placeholder="크기(세로)" autocomplete="off">
                        </td>
						<td>
							<select name="exit_direction" id="exit_direction" class="form-select text-start" style="font-size: 0.7rem; height: 28px; width: 120px;">
								<option value="">점검구형태</option>
								<option value="양면 점검구">양면 점검구</option>
								<option value="밑면 점검구">밑면 점검구</option>
								<option value="후면 점검구">후면 점검구</option>
							</select>
						</td>						
						<td>
							<input type="text" name="front_bottom_width" id="front_bottom_width" value="<?= isset($front_bottom_width) ? htmlspecialchars($front_bottom_width, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center " style="font-size: 0.7rem;  height: 28px;" placeholder="전면부 밑" autocomplete="off">
						</td>
						<td>
							<input type="text" name="rail_width" id="rail_width" value="<?= isset($rail_width) ? htmlspecialchars($rail_width, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center " style="font-size: 0.7rem; height: 28px;" placeholder="레일폭" autocomplete="off">
						</td>
                        <td>
                            <input type="text" name="search_keyword" id="search_keyword" value="<?= isset($search_keyword) ? htmlspecialchars($search_keyword, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-start " style="font-size: 0.7rem; width: 200px; height: 28px;" placeholder="품목검색어 등록" autocomplete="off">
                        </td>
                    </tr>
					</tbody>
                </table>
				</div>
				
              <!-- 이미지 파일 선택 및 드롭 영역 -->
			<div class="col-auto">
				<!-- 이미지 파일 선택 (숨김 처리, drop 영역에서 사용) -->
				<input type="file" id="upfile" name="upfile[]" multiple style="display:none;">
				<button class="btn btn-dark btn-sm ms-1 me-4" type="button" onclick="document.getElementById('upfile').click();">
					<i class="bi bi-image"></i>
				</button>
				
				<div class="d-flex justify-content-center">
					<!-- 드롭 영역 -->
					<div id="dropArea" style="border: 1px dashed #ccc; padding: 5px; width:95%; height:100px; text-align: center;">
						여기로 사진을 drop or 캡쳐 붙여넣기(ctrl+v)
					</div>
				</div>
				<!-- 파일 목록 및 미리보기 영역 -->
				<div class="d-flex mt-2 justify-content-center">
					<div id="previewContainer">
						<?php if (!empty($imgdata)): ?>
							<img src="<?= htmlspecialchars($upload_dir . $imgdata, ENT_QUOTES, 'UTF-8') ?>" alt="Image" id="currentImage" class="img-fluid">
						<?php else: ?>
							<span class="text-danger mx-5">No image!</span>
						<?php endif; ?>
					</div>
				</div>
			</div>
				<!-- JavaScript for Drag & Drop, 파일 선택, 그리고 클립보드 붙여넣기 -->
				<script>
				document.getElementById('dropArea').addEventListener('dragover', function(event) {
					event.preventDefault();
					event.stopPropagation();
					this.style.borderColor = '#000';
				});
				document.getElementById('dropArea').addEventListener('dragleave', function(event) {
					event.preventDefault();
					event.stopPropagation();
					this.style.borderColor = '#ccc';
				});
				document.getElementById('dropArea').addEventListener('drop', function(event) {
					event.preventDefault();
					event.stopPropagation();
					const files = event.dataTransfer.files;
					if (files.length > 0) {
						handleFiles(files);
					}
				});
				document.getElementById('upfile').addEventListener('change', function(event) {
					const files = event.target.files;
					if (files.length > 0) {
						handleFiles(files);
					}
				});
				// 클립보드 붙여넣기 (윈도우키+Shift+S 등)
				document.addEventListener('paste', function(event) {
					let items = (event.clipboardData || event.originalEvent.clipboardData).items;
					for (let index in items) {
						let item = items[index];
						if (item.kind === 'file' && item.type.startsWith('image/')) {
							let blob = item.getAsFile();
							let reader = new FileReader();
							reader.onload = function(event) {
								const previewContainer = document.getElementById('previewContainer');
								previewContainer.innerHTML = '';
								let img = document.createElement('img');
								img.src = event.target.result;
								img.className = 'img-fluid';
								previewContainer.appendChild(img);
								
								// 파일을 upfile input에 추가
								const fileInput = document.getElementById('upfile');
								const dataTransfer = new DataTransfer();
								dataTransfer.items.add(blob);
								fileInput.files = dataTransfer.files;
							};
							reader.readAsDataURL(blob);
						}
					}
				});
				
				function handleFiles(files) {
					const file = files[0]; // 첫 번째 파일만 처리 (필요에 따라 확장 가능)
					const reader = new FileReader();
					reader.onload = function(event) {
						const previewContainer = document.getElementById('previewContainer');
						previewContainer.innerHTML = '';
						let img = document.createElement('img');
						img.src = event.target.result;
						img.className = 'img-fluid';
						previewContainer.appendChild(img);
						
						// 파일을 upfile input에 설정
						const fileInput = document.getElementById('upfile');
						const dataTransfer = new DataTransfer();
						dataTransfer.items.add(file);
						fileInput.files = dataTransfer.files;
					};
					reader.readAsDataURL(file);
				}
				</script>														
					<div class="col-auto">
						<button type="submit" class="btn btn-primary btn-sm" id="submitBtn">등록</button>
					</div>
                </div>
            </form>
            <hr>
           <!-- 저장된 케이스 이미지 목록 테이블 -->
            <div class="table-responsive">
                <table class="table table-bordered" id="mainTable">
				<style>
                        .hover-image-modal {
                            display: none;
                            position: fixed;
                            z-index: 1000;
                            pointer-events: none;
                        }
                        .hover-image-modal img {
                            max-width: none;
                            max-height: none;
                        }
                    </style>
                    <script>
                        document.addEventListener('DOMContentLoaded', function() {
                            // 모달 div 생성
                            const modal = document.createElement('div');
                            modal.className = 'hover-image-modal';
                            document.body.appendChild(modal);

                            // 테이블의 이미지에 호버 이벤트 추가
                            document.querySelectorAll('#mainTable td img').forEach(img => {
                                img.addEventListener('mouseenter', function(e) {
                                    const fullImg = new Image();
                                    fullImg.src = this.src;
                                    modal.innerHTML = '';
                                    modal.appendChild(fullImg);
                                    modal.style.display = 'block';
                                });

                                img.addEventListener('mousemove', function(e) {
                                    modal.style.left = (e.pageX - modal.offsetWidth - 10) + 'px';
                                    modal.style.top = e.clientY + 10 + 'px';
                                });

                                img.addEventListener('mouseleave', function() {
                                    modal.style.display = 'none';
                                });
                            });
                        });
                    </script>	
                    <thead class="table-secondary">
                        <tr>
                            <th class="sortable" data-sort="index">순번 <i class="bi bi-arrow-down-up"></i></th>
                            <th class="sortable" data-sort="box_width">크기(가로) <i class="bi bi-arrow-down-up"></i></th>
                            <th class="sortable" data-sort="box_height">크기(세로) <i class="bi bi-arrow-down-up"></i></th>
							<th class="sortable text-center" data-sort="exit_direction">점검구형태 <i class="bi bi-arrow-down-up"></i></th>
							<th class="sortable text-center" data-sort="front_bottom_width">전면부 밑치수 <i class="bi bi-arrow-down-up"></i></th>
							<th class="sortable text-center" data-sort="rail_width">레일폭 <i class="bi bi-arrow-down-up"></i></th>
							<th class="sortable text-center" data-sort="search_keyword">품목검색어 <i class="bi bi-arrow-down-up"></i></th>
                            <th>이미지</th>
                            <th>수정/삭제</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($shutterboxData)): ?>
                            <?php // foreach ($shutterboxData as $i => $item): // 역순으로 돌리는 코드는 아래와 같다. ?>
							<?php foreach (array_reverse($shutterboxData, true) as $i => $item): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>                                    
									<td><?= isset($item["box_width"]) ? htmlspecialchars($item["box_width"], ENT_QUOTES, 'UTF-8') : '' ?></td>
									<td><?= isset($item["box_height"]) ? htmlspecialchars($item["box_height"], ENT_QUOTES, 'UTF-8') : '' ?></td>
									<td><?= isset($item["exit_direction"]) ? htmlspecialchars($item["exit_direction"], ENT_QUOTES, 'UTF-8') : '' ?></td>
									<td><?= isset($item["front_bottom_width"]) ? htmlspecialchars($item["front_bottom_width"], ENT_QUOTES, 'UTF-8') : '' ?></td>
									<td><?= isset($item["rail_width"]) ? htmlspecialchars($item["rail_width"], ENT_QUOTES, 'UTF-8') : '' ?></td>
									<td><?= isset($item["search_keyword"]) ? htmlspecialchars($item["search_keyword"], ENT_QUOTES, 'UTF-8') : '' ?></td>
                                    <td>
                                        <?php if (!empty($item["image"])): ?>
                                            <img src="<?= htmlspecialchars($item["image"], ENT_QUOTES, 'UTF-8') ?>" alt="이미지" style="max-width:100px;">
                                        <?php else: ?>
                                            없음
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <button type="button" class="btn btn-sm btn-outline-primary editBtn" data-index="<?= $i ?>">수정</button>
                                        <button type="button" class="btn btn-sm btn-outline-success copyBtn" data-index="<?= $i ?>">복사</button>
                                        <button type="button" class="btn btn-sm btn-outline-danger deleteBtn" data-index="<?= $i ?>">삭제</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="6">등록된 케이스 이미지 정보가 없습니다.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div><!-- table-responsive -->
        <div style="height: 400px;"></div>
        </div><!-- card-body -->
    </div><!-- card -->
</div><!-- container -->
 
<script>
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
    if(loader)
        loader.style.display = 'none';
});

$(document).ready(function(){
    // 테이블 정렬 기능
    let currentSort = { column: null, direction: 'asc' };
    
    // 정렬 가능한 헤더 클릭 이벤트
    $('.sortable').on('click', function() {
        const column = $(this).data('sort');
        const tbody = $('#mainTable tbody');
        const rows = tbody.find('tr').toArray();
        
        // 정렬 방향 결정
        if (currentSort.column === column) {
            currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
        } else {
            currentSort.column = column;
            currentSort.direction = 'asc';
        }
        
        // 정렬 실행
        rows.sort(function(a, b) {
            let aValue, bValue;
            
            // 컬럼 인덱스 결정
            let columnIndex;
            switch(column) {
                case 'index': columnIndex = 0; break;
                case 'box_width': columnIndex = 1; break;
                case 'box_height': columnIndex = 2; break;
                case 'exit_direction': columnIndex = 3; break;
                case 'front_bottom_width': columnIndex = 4; break;
                case 'rail_width': columnIndex = 5; break;
                case 'search_keyword': columnIndex = 6; break;
                default: columnIndex = 0;
            }
            
            aValue = $(a).find('td').eq(columnIndex).text().trim();
            bValue = $(b).find('td').eq(columnIndex).text().trim();
            
            // 숫자 정렬 (순번, 크기, 레일폭, 전면부 밑치수)
            if (['index', 'box_width', 'box_height', 'rail_width', 'front_bottom_width'].includes(column)) {
                aValue = parseFloat(aValue) || 0;
                bValue = parseFloat(bValue) || 0;
            }
            
            // 정렬 방향에 따른 비교
            if (currentSort.direction === 'asc') {
                return aValue > bValue ? 1 : -1;
            } else {
                return aValue < bValue ? 1 : -1;
            }
        });
        
        // 정렬된 행을 테이블에 다시 추가
        tbody.empty();
        rows.forEach(function(row) {
            tbody.append(row);
        });
        
        // 정렬 아이콘 업데이트
        $('.sortable i').removeClass('bi-arrow-up bi-arrow-down').addClass('bi-arrow-down-up');
        const currentHeader = $(`.sortable[data-sort="${column}"]`);
        const icon = currentHeader.find('i');
        icon.removeClass('bi-arrow-down-up');
        icon.addClass(currentSort.direction === 'asc' ? 'bi-arrow-up' : 'bi-arrow-down');
        
        // 순번 재정렬 (정렬 후 순번을 1부터 다시 매김)
        tbody.find('tr').each(function(index) {
            $(this).find('td').eq(0).text(index + 1);
        });
    });
    
    // 정렬 가능한 헤더에 커서 스타일 적용
    $('.sortable').css('cursor', 'pointer');
    
    // 수정 버튼 클릭 시: 해당 행의 데이터를 폼에 채워 수정 모드로 전환
	$('.editBtn').on('click', function(){
		var index = $(this).data('index');
		var row = $(this).closest('tr');
		var box_width = row.find('td:eq(1)').text().trim();
		var box_height = row.find('td:eq(2)').text().trim();
		var exit_direction = row.find('td:eq(3)').text().trim();
		var front_bottom_width = row.find('td:eq(4)').text().trim();
		var rail_width = row.find('td:eq(5)').text().trim();
		var search_keyword = row.find('td:eq(6)').text().trim();
		var imageSrc = row.find('td:eq(7) img').attr('src') || ''; // 7번째 이미지
		
		$('#box_width').val(box_width);
		$('#box_height').val(box_height);
		$('#exit_direction').val(exit_direction);
		$('#front_bottom_width').val(front_bottom_width);
		$('#rail_width').val(rail_width);
		$('#search_keyword').val(search_keyword);
		$('#existing_image').val(imageSrc);
		$('#index').val(index);
		$('#action').val('update');
		$('#submitBtn').text('수정');

		// 기존 이미지 미리보기 업데이트
		if(imageSrc) {
			$('#previewContainer').html('<img src="' + imageSrc + '" alt="이미지" class="img-fluid">');
		} else {
			$('#previewContainer').html('아직 등록된 이미지가 없습니다.');
		}
	});
    // 복사 버튼 클릭 시: 확인 후 폼 제출하여 복사 처리
    $('.copyBtn').on('click', function(){
        var index = $(this).data('index');
        
        Swal.fire({
            title: '복사 확인',
            text: "이 항목을 복사하시겠습니까?",
            icon: 'question',
            showCancelButton: true,
            confirmButtonColor: '#3085d6', 
            cancelButtonColor: '#d33',
            confirmButtonText: '확인',
            cancelButtonText: '취소'
        }).then((result) => {
            if (result.isConfirmed) {
                // 복사할 데이터 가져오기
                var row = $(this).closest('tr');
                var box_width = row.find('td:eq(1)').text().trim();
                var box_height = row.find('td:eq(2)').text().trim();
                var exit_direction = row.find('td:eq(3)').text().trim();
                var front_bottom_width = row.find('td:eq(4)').text().trim();
                var rail_width = row.find('td:eq(5)').text().trim();
                var search_keyword = row.find('td:eq(6)').text().trim();
                var imageSrc = row.find('td:eq(7) img').attr('src') || '';
                
                // 폼에 데이터 설정
                $('#box_width').val(box_width);
                $('#box_height').val(box_height);
                $('#exit_direction').val(exit_direction);
                $('#front_bottom_width').val(front_bottom_width);
                $('#rail_width').val(rail_width);
                $('#search_keyword').val(search_keyword);
                $('#existing_image').val(imageSrc);
                
                // 수정 모드로 설정 (새로운 항목이므로 index는 -1)
                $('#index').val(-1);
                $('#action').val('insert');
                $('#submitBtn').text('등록');
                
                // 이미지 미리보기 업데이트
                if(imageSrc) {
                    $('#previewContainer').html('<img src="' + imageSrc + '" alt="이미지" class="img-fluid">');
                } else {
                    $('#previewContainer').html('아직 등록된 이미지가 없습니다.');
                }
                
                // // 페이지 상단으로 스크롤하여 폼이 보이도록 함
                // $('html, body').animate({
                //     scrollTop: $('#shutterboxForm').offset().top - 20
                // }, 500);
                
                // 성공 메시지 표시
                setTimeout(function() {
                    Swal.fire({
                        text: '복사된 데이터가 폼에 로드되었습니다. 필요에 따라 수정 후 등록하세요.',
                        timer: 1500,
                        showConfirmButton: false,
                        icon: 'success'
                    });
                }, 100);
            }
        });
    });

    // 삭제 버튼 클릭 시: 확인 후 폼 제출하여 삭제 처리
    $('.deleteBtn').on('click', function(){
        var index = $(this).data('index');
        if(confirm("정말 삭제하시겠습니까?")){
            $('#index').val(index);
            $('#action').val('delete');
            $('#shutterboxForm').submit();
        }
    });
});
</script>

</body>
</html>