<?php
// guideraillist.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'] . '/bottombar/bottombar.json';

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

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

// POST 요청 처리: 추가, 수정, 삭제
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	$action = isset($_POST['action']) ? $_POST['action'] : '';
	$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
	$firstitem = isset($_POST['firstitem']) ? trim($_POST['firstitem']) : '';
	$model_UA = isset($_POST['model_UA']) ? trim($_POST['model_UA']) : '';
	$model_name = isset($_POST['model_name']) ? trim($_POST['model_name']) : '';	
	$bar_width = isset($_POST['bar_width']) ? trim($_POST['bar_width']) : '';
	$bar_height = isset($_POST['bar_height']) ? trim($_POST['bar_height']) : '';
	$finishing_type = isset($_POST['finishing_type']) ? trim($_POST['finishing_type']) : '';
	$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'] . '/bottombar/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 = '/bottombar/images/' . $newFileName;
	// 2. 일반 파일 input 처리
	} elseif (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
		$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/bottombar/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 = '/bottombar/images/' . $newFileName;
	}
	// 3. 기존 이미지 사용
	if (empty($imagePath) && isset($_POST['existing_image'])) {
		$imagePath = trim($_POST['existing_image']);
	}
	
	if ($action === 'insert' && !empty($model_name)) {
		// 신규 추가
		$bottombarData[] = array(
			"firstitem"      => $firstitem ?? '',
			"model_UA"       => $model_UA ?? '',
			"model_name"     => $model_name ?? '',			
			"bar_width"      => $bar_width ?? '',
			"bar_height"     => $bar_height ?? '',
			"finishing_type" => $finishing_type ?? '',
			"search_keyword" => $search_keyword ?? '',
			"image"          => $imagePath ?? ''
		);
	} elseif ($action === 'update' && !empty($model_name) && $index >= 0 && $index < count($bottombarData)) {
		// 수정
		$bottombarData[$index]["firstitem"]      = $firstitem ?? '';
		$bottombarData[$index]["model_UA"]             = $model_UA ?? '';
		$bottombarData[$index]["model_name"]     = $model_name ?? '';		
		$bottombarData[$index]["bar_width"]      = $bar_width ?? '';
		$bottombarData[$index]["bar_height"]     = $bar_height ?? '';
		$bottombarData[$index]["finishing_type"] = $finishing_type ?? '';
		$bottombarData[$index]["search_keyword"] = $search_keyword ?? '';
		if (!empty($imagePath)) {
			$bottombarData[$index]["image"] = $imagePath;
		}
	} elseif ($action === 'delete' && $index >= 0 && $index < count($bottombarData)) {
		// 삭제
		array_splice($bottombarData, $index, 1);
	}
	
	// JSON 파일에 저장
	file_put_contents($jsonFile, json_encode($bottombarData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));    
}
?>
</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="bottombarForm" method="post" action="bottombarlist.php" enctype="multipart/form-data" class="row g-3">
                <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">
                <table class="table table-bordered table-sm w-75">
                    <tr>
                        <th class="text-center">대분류</th>
                        <th class="text-center">인정/비인정</th>
                        <th class="text-center">제품모델</th>
                        <th class="text-center" style="width:100px;">하장바 폭</th>
                        <th class="text-center" style="width:100px;">하장바 높이</th>
                        <th class="text-center">마감형태</th>
                        <th class="text-center">품목검색어 등록</th>
                    </tr>
                    <tr>
                        <td>
                            <select id="firstitem" name="firstitem" class="form-select w-auto" style="font-size: 0.7rem; height: 32px;">
                                <option value="">(대분류)</option>
                                <option value="스크린" <?= ($firstitem == '스크린') ? 'selected' : '' ?>>스크린</option>
                                <option value="철재" <?= ($firstitem == '철재') ? 'selected' : '' ?>>철재</option>
                            </select>
                        </td>
                        <td>
                            <select id="model_UA" name="model_UA" class="form-select w-auto" style="font-size: 0.7rem; height: 32px;">
                                <option value="">(인정/비인정)</option>
                                <option value="인정" <?= (isset($model_UA) && $model_UA == '인정') ? 'selected' : '' ?>>인정</option>
                                <option value="비인정" <?= (isset($model_UA) && $model_UA == '비인정') ? 'selected' : '' ?>>비인정</option>
                            </select>
                        </td>
                        <td>
                            <?php selectModel('model_name', $model_name); ?>
                        </td>
                        <td>
                            <input type="text" name="bar_width" id="bar_width" value="<?= isset($bar_width) ? htmlspecialchars($bar_width, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center " style="font-size: 0.7rem; height: 28px;" placeholder="폭(mm)" autocomplete="off">
                        </td>
                        <td>
                            <input type="text" name="bar_height" id="bar_height" value="<?= isset($bar_height) ? htmlspecialchars($bar_height, ENT_QUOTES, 'UTF-8') : '' ?>" class="form-control text-center  " style="font-size: 0.7rem; height: 28px;" placeholder="높이(mm)" autocomplete="off">
                        </td>
                        <td>
                            <select name="finishing_type" id="finishing_type" class="form-select w-auto" style="font-size: 0.7rem; height: 32px;">
                                <option value="">(마감형태)</option>
                                <option value="SUS마감" <?= (isset($finishing_type) && $finishing_type == 'SUS마감') ? 'selected' : '' ?>>SUS마감</option>
                                <option value="EGI마감" <?= (isset($finishing_type) && $finishing_type == 'EGI마감') ? 'selected' : '' ?>>EGI마감</option>
                            </select>
                        </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; height: 32px;" placeholder="품목검색어 등록" autocomplete="off">
                        </td>
                    </tr>
                </table>

              <!-- 이미지 파일 선택 및 드롭 영역 -->
			<div class="col-auto">
				<!-- 이미지 파일 선택 (숨김 처리, drop 영역에서 사용) -->
				<input type="file" id="upfile" name="upfile[]" multiple style="display:none;">
				<button class="btn btn-dark btn-sm 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:100%; height:80px; 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" style="width:200px; height:auto;" id="currentImage" class="img-fluid">
						<?php else: ?>
							No image!
						<?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" id="submitBtn">등록</button>
                </div>
				</div>
            </form>
            <hr>
           <!-- 저장된 하단마감재 이미지 목록 테이블 -->
            <div class="table-responsive">
                <table class="table table-bordered">
                    <thead class="table-secondary">
                        <tr>
                            <th>순번</th>
                            <th>대분류</th>
                            <th>인정/비인정</th>
                            <th>모델명</th>
                            <th>하장바 폭</th>
                            <th>하장바 높이</th>                            
                            <th>마감</th>
							<th class="text-center">품목검색어</th>
                            <th>이미지</th>
                            <th>수정/삭제</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (!empty($bottombarData)): ?>
                            <?php foreach ($bottombarData as $i => $item): ?>
                                <tr>
                                    <td><?= $i + 1 ?></td>
                                    <td><?= isset($item["firstitem"]) ? htmlspecialchars($item["firstitem"], ENT_QUOTES, 'UTF-8') : '' ?></td>
                                    <td><?= isset($item["model_UA"]) ? htmlspecialchars($item["model_UA"], ENT_QUOTES, 'UTF-8') : '' ?></td>
                                    <td><?= isset($item["model_name"]) ? htmlspecialchars($item["model_name"], ENT_QUOTES, 'UTF-8') : '' ?></td>
                                    <td><?= isset($item["bar_width"]) ? htmlspecialchars($item["bar_width"], ENT_QUOTES, 'UTF-8') : '' ?></td>
                                    <td><?= isset($item["bar_height"]) ? htmlspecialchars($item["bar_height"], ENT_QUOTES, 'UTF-8') : '' ?></td>                                    
                                    <td><?= isset($item["finishing_type"]) ? htmlspecialchars($item["finishing_type"], 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-danger deleteBtn" data-index="<?= $i ?>">삭제</button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <tr><td colspan="9">등록된 하단마감재 이미지 정보가 없습니다.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div><!-- table-responsive -->
        </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(){
    // 수정 버튼 클릭 시: 해당 행의 데이터를 폼에 채워 수정 모드로 전환
	$('.editBtn').on('click', function(){
		var index = $(this).data('index');
		var row = $(this).closest('tr');
		var firstitem = row.find('td:eq(1)').text().trim();
		var model_UA = row.find('td:eq(2)').text().trim();
		var modelName = row.find('td:eq(3)').text().trim();		
		var barWidth = row.find('td:eq(4)').text().trim();
		var barHeight = row.find('td:eq(5)').text().trim();
		var finishingType = row.find('td:eq(6)').text().trim();
		var searchKeyword = row.find('td:eq(7)').text().trim();
		var imageSrc = row.find('td:eq(8) img').attr('src') || '';
		
		$('#firstitem').val(firstitem);
		$('#model_UA').val(model_UA);
		$('#model_name').val(modelName);		
		$('#bar_width').val(barWidth);
		$('#bar_height').val(barHeight);
		$('#finishing_type').val(finishingType);
		$('#search_keyword').val(searchKeyword);
		$('#existing_image').val(imageSrc);
		$('#index').val(index);
		$('#action').val('update');
		$('#submitBtn').text('수정');

		// 기존 이미지 미리보기 업데이트
		if(imageSrc) {
			$('#previewContainer').html('<img src="' + imageSrc + '" alt="이미지" class="img-fluid" style="width:200px; height:auto;">');
		} else {
			$('#previewContainer').html('아직 등록된 이미지가 없습니다.');
		}
	});

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

<script>
// PHP에서 전달받은 모델 리스트를 JavaScript 변수에 저장
var modelsList = <?php echo json_encode($modelsList); ?>;

$(document).ready(function(){
	$('#firstitem').on('change', function(){
		var selectedMajor = $(this).val();
		var $modelSelect = $('#model_name');
		// 기존 옵션 초기화
		$modelSelect.empty();
		// 기본 옵션 추가
		$modelSelect.append('<option value="">(모델 선택)</option>');
		
		// 모델 리스트를 순회하며 대분류(selectedMajor)와 일치하는 경우 옵션 추가
		$.each(modelsList, function(index, model){
			if(selectedMajor === '' || model.slatitem === selectedMajor){
				var option = $('<option>')
					.val(model.model_name)
					.text(model.model_name);
				$modelSelect.append(option);
			}
		});
	});
});

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