Files
sam-kd/guiderail/guideraillist.php
hskwon aca1767eb9 초기 커밋: 5130 레거시 시스템
- URL 하드코딩 → .env APP_URL 기반 동적 URL로 변경
- DB 연결 하드코딩 → .env 기반으로 변경
- MySQL strict mode DATE 오류 수정
2025-12-10 20:14:31 +09:00

539 lines
24 KiB
PHP

<?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'] . '/guiderail/guiderail.json';
$model_name = $_REQUEST['model_name'] ?? '';
// JSON 파일이 존재하면 읽어오고, 없으면 빈 배열 생성
$guiderailData = [];
if (file_exists($jsonFile)) {
$jsonContent = file_get_contents($jsonFile);
$guiderailData = json_decode($jsonContent, true);
if (!is_array($guiderailData)) {
$guiderailData = [];
}
}
// 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']) : '';
$UA = isset($_POST['UA']) ? trim($_POST['UA']) : '';
$model_name = isset($_POST['model_name']) ? trim($_POST['model_name']) : '';
$check_type = isset($_POST['check_type']) ? trim($_POST['check_type']) : '';
$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'] . '/guiderail/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 = '/guiderail/images/' . $newFileName;
// 2. 일반 파일 input 처리
} elseif (isset($_FILES['image']) && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
$uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/guiderail/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 = '/guiderail/images/' . $newFileName;
}
// 3. 기존 이미지 사용
if (empty($imagePath) && isset($_POST['existing_image'])) {
$imagePath = trim($_POST['existing_image']);
}
if ($action === 'insert' && !empty($model_name)) {
// 신규 추가
$guiderailData[] = array(
"firstitem" => $firstitem ?? '',
"UA" => $UA ?? '',
"model_name" => $model_name ?? '',
"check_type" => $check_type ?? '',
"finishing_type" => $finishing_type ?? '',
"search_keyword" => $search_keyword ?? '',
"image" => $imagePath ?? ''
);
} elseif ($action === 'update' && !empty($model_name) && $index >= 0 && $index < count($guiderailData)) {
// 수정
$guiderailData[$index]["firstitem"] = $firstitem ?? '';
$guiderailData[$index]["UA"] = $UA ?? '';
$guiderailData[$index]["model_name"] = $model_name ?? '';
$guiderailData[$index]["check_type"] = $check_type ?? '';
$guiderailData[$index]["finishing_type"] = $finishing_type ?? '';
$guiderailData[$index]["search_keyword"] = $search_keyword ?? '';
if (!empty($imagePath)) {
$guiderailData[$index]["image"] = $imagePath;
}
} elseif ($action === 'delete' && $index >= 0 && $index < count($guiderailData)) {
// 삭제
array_splice($guiderailData, $index, 1);
}
// JSON 파일에 저장
file_put_contents($jsonFile, json_encode($guiderailData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
}
?>
<style>
/* 편집할때 보여지는 이미지 크기 */
#previewContainer {
width: 100px !important;
height: auto !important;
}
</style>
</head>
<body>
<div class="container 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="guiderailForm" method="post" action="guideraillist.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">
<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>
<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="UA" name="UA" class="form-select w-auto" style="font-size: 0.7rem; height: 32px;">
<option value="">(인정/비인정)</option>
<option value="인정" <?= ($UA == '인정') ? 'selected' : '' ?>>인정</option>
<option value="비인정" <?= ($UA == '비인정') ? 'selected' : '' ?>>비인정</option>
</select>
</td>
<td>
<?php selectModel('model_name', $model_name); ?>
</td>
<td>
<select name="check_type" id="check_type" class="form-select w-auto" style="font-size: 0.7rem; height: 32px;">
<option value="">(유형)</option>
<option value="벽면형" <?= (isset($check_type) && $check_type == '벽면형') ? 'selected' : '' ?>>벽면형</option>
<option value="측면형" <?= (isset($check_type) && $check_type == '측면형') ? 'selected' : '' ?>>측면형</option>
</select>
</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 noborder-input w-auto" style="font-size: 0.7rem; height: 32px;" placeholder="품목검색어 등록">
</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 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: ?>
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 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 + 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="firstitem">대분류 <i class="bi bi-arrow-down-up"></i></th>
<th class="sortable" data-sort="UA">인정/비인정 <i class="bi bi-arrow-down-up"></i></th>
<th class="sortable" data-sort="model_name">모델명 <i class="bi bi-arrow-down-up"></i></th>
<th class="sortable" data-sort="check_type">유형 <i class="bi bi-arrow-down-up"></i></th>
<th class="sortable" data-sort="finishing_type">마감 <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($guiderailData)): ?>
<?php // foreach ($guiderailData as $i => $item): // 역순으로 돌리는 코드는 아래와 같다. ?>
<?php foreach (array_reverse($guiderailData, true) as $i => $item): ?>
<tr>
<td><?= $i + 1 ?></td>
<td><?= isset($item["firstitem"]) ? htmlspecialchars($item["firstitem"], ENT_QUOTES, 'UTF-8') : '' ?></td>
<td><?= isset($item["UA"]) ? htmlspecialchars($item["UA"], ENT_QUOTES, 'UTF-8') : '' ?></td>
<td><?= isset($item["model_name"]) ? htmlspecialchars($item["model_name"], ENT_QUOTES, 'UTF-8') : '' ?></td>
<td><?= isset($item["check_type"]) ? htmlspecialchars($item["check_type"], 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="7">등록된 가이드레일 이미지 정보가 없습니다.</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(){
// 테이블 정렬 기능
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 'firstitem': columnIndex = 1; break;
case 'UA': columnIndex = 2; break;
case 'model_name': columnIndex = 3; break;
case 'check_type': columnIndex = 4; break;
case 'finishing_type': 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 (column === 'index') {
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 firstitem = row.find('td:eq(1)').text().trim();
var UA = row.find('td:eq(2)').text().trim();
var modelName = row.find('td:eq(3)').text().trim();
var checkType = row.find('td:eq(4)').text().trim();
var finishingType = row.find('td:eq(5)').text().trim();
var searchKeyword = row.find('td:eq(6)').text().trim();
var imageSrc = row.find('td:eq(7) img').attr('src') || '';
$('#firstitem').val(firstitem);
$('#UA').val(UA);
$('#model_name').val(modelName);
$('#check_type').val(checkType);
$('#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">');
} else {
$('#previewContainer').html('아직 등록된 이미지가 없습니다.');
}
});
// 삭제 버튼 클릭 시: 확인 후 폼 제출하여 삭제 처리
$('.deleteBtn').on('click', function(){
var index = $(this).data('index');
if(confirm("정말 삭제하시겠습니까?")){
$('#index').val(index);
$('#action').val('delete');
$('#guiderailForm').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>