<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");

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

require_once($_SERVER['DOCUMENT_ROOT'] . "/common.php");  // 초기파일 로드
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

// --- 변수 초기화 ---
$bending_components = '';
$registration_date = date('Y-m-d');
$author = isset($user_name) ? $user_name : '';
$num_display = $num;

if (($mode === 'modify' || $mode === 'copy' || $mode === 'view') && $num) {
    try {
        $sql = "SELECT * FROM {$DB}.{$tablename} WHERE num=? ";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        // _row.php를 통해 $row의 모든 컬럼이 변수로 할당됩니다.
        // (사용자가 제공한 _row.php에는 $bending_components가 포함되어 있습니다)
        if ($row) {
            include '_row.php';
        }

        if ($mode === 'copy') {
            $registration_date = date('Y-m-d');
            $num_display = ''; // 복사 모드에서는 번호 비움
			$author = isset($user_name) ? $user_name : '';
        }
    } catch (PDOException $Exception) {
        echo "오류: " . $Exception->getMessage();
        exit;
    }
} else {
    // 신규(insert) 모드
    include '_request.php'; // 혹시 모를 파라미터 처리
    $mode = 'insert';
	$registration_date = date('Y-m-d');
	$author = isset($user_name) ? $user_name : '';
}

$title_message = ($mode === 'view') ? "레일 조회 (#{$num_display})" : '레일 등록';
$title_message = ($mode === 'modify') ? "레일 수정 (#{$num_display})" : $title_message;
$title_message = ($mode === 'copy') ? '레일 (데이터 복사)' : $title_message;

// 기존에 저장된 값이 있는 경우 해당 값을 설정, 없으면 기본값
if(empty($firstitem)) {
    $firstitem = '스크린';
}
if(empty($model_UA)) {
    $model_UA = '비인정';
}

$check_type = isset($row['check_type']) ? $row['check_type'] : '벽면형';
$finishing_type = isset($row['finishing_type']) ? $row['finishing_type'] : 'SUS마감';
$is_assembly_model = !empty($bending_components); // 조립 모델 여부 판단
?>
<link href="../css/bending.css?v=<?php echo time(); ?>" rel="stylesheet">   <!-- 절곡관련 (가이드레일,케이스,하단마감재) -->
<input type="hidden" id="update_log" name="update_log" value="<?= isset($update_log) ? htmlspecialchars($update_log, ENT_QUOTES, 'UTF-8') : '' ?>">
<input type="hidden" id="bending_components_data" name="bending_components" value="<?= htmlspecialchars($bending_components, ENT_QUOTES, 'UTF-8') ?>">
<input type="hidden" id="material_summary" name="material_summary" value="<?= isset($material_summary) ? htmlspecialchars($material_summary, ENT_QUOTES, 'UTF-8') : '' ?>">

<div class="container-fluid">            
        <div class="card">
            <div class="card-header text-center">
                <div class="row">
                    <div class="col-sm-10">
                        <div class="d-flex align-items-center justify-content-center">
                            <span class="text-center mx-5"><?= $mode ?></span>
                            <span class="text-center fs-6 me-5"><?= $title_message ?></span>
                            <?php if ($mode == 'view') { ?>
                                <button type="button" id="modifyBtn" data-num="<?= $num ?>" class="btn btn-dark btn-sm mx-1"><i class="bi bi-pencil-square"></i> 수정</button>
                                <button id="copyBtn" data-num="<?= $num ?>" class="btn btn-primary btn-sm mx-1" type="button"><i class="bi bi-copy"></i> 복사</button>
                            <?php } ?>
                            <?php if ($mode == 'insert' || $mode == 'modify' || $mode == 'copy') { ?>
                                <button type="button" id="saveBtn" class="btn btn-dark btn-sm mx-1"> <i class="bi bi-save"></i> 저장</button>                                
                                <button type="button" class="btn btn-dark btn-sm mx-1 registImageBtn"> <i class="bi bi-list"></i> 결합형태 이미지 등록 </button>                                                                
                            <?php } ?>
                            <?php if ($mode == 'view') { ?>
                                <button type="button" id="deleteBtn" class="btn btn-danger btn-sm mx-1"><i class="bi bi-trash"></i> 삭제</button>
                                <!-- <button type="button" id="viewBtn" data-num="<?= $num ?>" class="btn btn-success btn-sm mx-1"><i class="bi bi-menu-up"></i> 전개도</button> -->
                            <?php } ?>
                        </div>
                    </div>
                    <div class="col-sm-2">
                        <div class="d-flex align-items-center justify-content-end">
                            <button type="button" class="btn btn-outline-dark btn-sm me-2 closeBtn"> &times; 닫기</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-sm-8">                    
                        <div class="table-responsive" style="padding : 4px;">
                        <table class="table table-bordered" id="guiderailTable">
                            <tbody>
                                <tr>
                                    <td class="text-center fw-bold" style="width:100px;">등록일</td>
                                    <td class="text-center" style="width:110px;">
                                        <input type="date" class="viewmode form-control noborder-input" id="registration_date" name="registration_date" value="<?= $registration_date ?>">
                                    </td>
                                    <td class="text-center fw-bold" style="width:100px;">작성자</td>
                                    <td class="text-center" style="width:100px;">
                                        <input class="viewmode form-control noborder-input" id="author" name="author" value="<?= $author ?>" autocomplete="off">
                                    </td>
                                    <td class="text-center fw-bold" style="width:80px;">비고</td>
                                    <td class="text-center">
                                        <input type="text" class="viewmode form-control text-start noborder-input" id="remark" name="remark" value="<?= isset($remark) ? htmlspecialchars($remark, ENT_QUOTES, 'UTF-8') : '' ?>" autocomplete="off">
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-center fw-bold" colspan="1">외형치수</td>
                                    <td class="text-center" colspan="5">
                                        <div class="d-flex align-items-center justify-content-start">
                                            <span class="text-center ms-1 me-1 text-primary">가로(너비)</span>
                                            <input type="text" class="viewmode form-control w-auto text-primary ms-1 me-1" style="max-width: 80px;" id="rail_length" name="rail_length" value="<?= isset($rail_length) ? htmlspecialchars($rail_length, ENT_QUOTES, 'UTF-8') : '' ?>" autocomplete="off">
                                            <span class="text-center ms-1 me-1">X</span>
                                            <span class="text-center ms-1 me-1 text-danger">세로(폭)</span>
                                            <input type="text" class="viewmode form-control w-auto text-danger" style="max-width: 80px;" id="rail_width" name="rail_width" value="<?= isset($rail_width) ? htmlspecialchars($rail_width, ENT_QUOTES, 'UTF-8') : '' ?>" autocomplete="off">
                                        </div>
                                    </td>
                                </tr>
                                <tr>                                    
                                    <td colspan="6">
                                        <div class="col text-center my-2">
											<strong>대분류:</strong>
											<?php if ($mode == 'view') : ?>
												<label class="ms-3 me-3" >
													<span class="text-primary fw-bold viewmode mx-2">  <?= htmlspecialchars($firstitem, ENT_QUOTES, 'UTF-8') ?> </span>
												</label>
												<input type="radio" name="firstitem"  value="스크린" style="display:none;" class="viewmode" data-readonly="true" <?= isset($firstitem) && $firstitem === '스크린' ? 'checked' : '' ?>>
												<input type="radio" name="firstitem"  value="철재"   style="display:none;" class="viewmode" data-readonly="true" <?= isset($firstitem) && $firstitem === '철재' ? 'checked' : '' ?>>
											<?php else : ?>
												<label class="ms-3 me-3" >
	                                                <input type="radio" name="firstitem"  value="스크린" class="viewmode" data-readonly="true" <?= isset($firstitem) && $firstitem === '스크린' ? 'checked' : '' ?>> 스크린
												</label>
												<label class="me-3">
													<input type="radio" name="firstitem"  value="철재" class="viewmode" data-readonly="true" <?= isset($firstitem) && $firstitem === '철재' ? 'checked' : '' ?>> 철재
												</label>		
											<?php endif; ?>

											<strong>모델 유형:</strong>
											<?php if ($mode == 'view') : ?>												
													<span class="text-primary fw-bold viewmode mx-2">  <?= htmlspecialchars($model_UA, ENT_QUOTES, 'UTF-8') ?> </span>													
													<input type="radio" name="model_UA"  value="인정" class="viewmode"  style="display:none;" <?= isset($model_UA) && $model_UA === '인정' ? 'checked' : '' ?>>
													<input type="radio" name="model_UA"  value="비인정" class="viewmode"  style="display:none;" <?= isset($model_UA) && $model_UA === '비인정' ? 'checked' : '' ?>> 
											<?php else : ?>
                                            <label class="ms-3 me-3">
                                                <input type="radio" name="model_UA"  value="인정" class="viewmode" data-readonly="true" <?= isset($model_UA) && $model_UA === '인정' ? 'checked' : '' ?>> 인정
                                            </label>
                                            <label class="me-3">
                                                <input type="radio" name="model_UA"  value="비인정" class="viewmode" data-readonly="true" <?= isset($model_UA) && $model_UA === '비인정' ? 'checked' : '' ?>> 비인정
                                            </label>		
											<?php endif; ?>
											<strong>형태 :</strong>
														<?php if ($mode == 'view') : ?>
															<span class="text-primary fw-bold viewmode mx-2">  <?= htmlspecialchars($check_type, ENT_QUOTES, 'UTF-8') ?> </span>													
															<input type="radio" name="check_type"  value="벽면형" class="viewmode"  style="display:none;" <?= isset($check_type) && $check_type === '벽면형' ? 'checked' : '' ?>>
															<input type="radio" name="check_type"  value="측면형" class="viewmode"  style="display:none;" <?= isset($check_type) && $check_type === '측면형' ? 'checked' : '' ?>> 														
															</label>
														<?php else : ?>
														<label class="ms-1 me-3">
															<input type="radio" name="check_type" class="viewmode" data-readonly="true" value="벽면형" <?= ($check_type === '벽면형') ? 'checked' : '' ?>> 벽면형
														</label>
														<label class="me-3">
															<input type="radio" name="check_type" class="viewmode" data-readonly="true" value="측면형" <?= ($check_type === '측면형') ? 'checked' : '' ?>> 측면형
														</label>
													<?php endif; ?>											
											<hr>									
											<div id="standardModelArea">
												<div class="d-flex justify-content-center align-items-center">
													<strong>모델</strong>
													<label class="ms-1 me-1">
														<?php selectModel('model_name', isset($model_name) ? $model_name : ''); ?>
													</label>													
													<strong>마감</strong>
													<label class="ms-1 me-1">
														<?php $finishList = ['SUS마감', 'EGI마감']; ?>
														<select id="finishing_type" name="finishing_type" data-readonly="true" class="viewmode form-select mx-1 d-inline" style="width: 80px; font-size: 0.7rem; height: 30px; padding: 4px;">
															<?php foreach ($finishList as $finish) : ?>
																<option value="<?= htmlspecialchars($finish, ENT_QUOTES, 'UTF-8') ?>" <?= ($finishing_type === $finish) ? 'selected' : '' ?>>
																	<?= htmlspecialchars($finish, ENT_QUOTES, 'UTF-8') ?>
																</option>
																<?php endforeach; ?>
															</select>
														</label>
														<strong>품목검색어:</strong>
														<label class="ms-1 me-3">
															<div class="d-flex align-items-center">
																<input type="text" id="search_keyword" name="search_keyword" class="form-control text-start noborder-input viewmode" value="<?= isset($search_keyword) ? htmlspecialchars($search_keyword, ENT_QUOTES, 'UTF-8') : '' ?>" placeholder="품목검색어 입력" autocomplete="off" style="width: 200px;">
																<button type="button" id="searchGuiderailBtn" class="btn btn-outline-primary btn-sm ms-2 viewmode" title="가이드레일 검색" style="height: 30px; ">
																	<i class="bi bi-search"></i>
																</button>
															</div>
														</label>
												</div>
											</div>
                                        </div>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
					</div>
                    </div>
                <div class="col-sm-4" style="padding : 4px;">
                    <!-- 그리기 컨트롤 -->
                    <div class="d-flex align-items-center mb-2" style="width:260px;">
                        <?php if($mode!=='view') : ?>
                            <button id="openEditorBtn" type="button" class="btn btn-outline-dark btn-sm me-2 viewNoBtn">그리기</button>                            
                        <?php else: ?>
                            <div class="text-muted">
                                <i class="bi bi-info-circle"></i> 조회 모드, 그리기 기능 불가
                            </div>
                        <?php endif; ?>
                    </div>

                <!-- 이미지 표시 영역 (수정된) -->
                <div class="card mb-3">
                    <div class="card-body">
                        <div class="image-container mb-3">
                        <?php
                            $jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
                            $imgUrl = '';

                            // 이미지 찾기 함수                               
                            function findImageByConditions($items, $conditions) {
                            foreach ($items as $item) {
                                $matched = true;
                                foreach ($conditions as $key => $value) {
                                if (empty($item[$key]) || $item[$key] !== $value) {
                                    $matched = false;
                                    break;
                                }
                                }
                                if ($matched && !empty($item['image'])) {
                                return $item['image'];
                                }
                            }
                            return '';
                            }

                            if (file_exists($jsonFile)) {
                            $jsonData = file_get_contents($jsonFile);
                            $guiderailImages = json_decode($jsonData, true);

                            if (is_array($guiderailImages)) {
                                // 검색 조건 우선순위대로 정렬
                                $searchCases = [];

                                if (!empty($row['search_keyword'])) {
                                // 1순위: 검색 키워드
                                $searchCases[] = ['search_keyword' => $row['search_keyword']];
                                }
                                // 2순위: 모든 조건 일치
                                $searchCases[] = [
                                'model_name'    => $row['model_name'],
                                'check_type'    => $row['check_type'],
                                'finishing_type'=> $row['finishing_type'],
                                'firstitem'     => $row['firstitem'],
                                'UA'            => $row['model_UA'],
                                ];
                                // 3순위: 모델명+형태+마감
                                $searchCases[] = [
                                'model_name'    => $row['model_name'],
                                'check_type'    => $row['check_type'],
                                'finishing_type'=> $row['finishing_type'],
                                ];
                                // 4순위: 모델명+형태
                                $searchCases[] = [
                                'model_name' => $row['model_name'],
                                'check_type' => $row['check_type'],
                                ];
                                // 5순위: 모델명만
                                $searchCases[] = ['model_name' => $row['model_name']];

                                foreach ($searchCases as $case) {
                                $found = findImageByConditions($guiderailImages, $case);
                                if ($found) {
                                    $imgUrl = $found;
                                    break;
                                }
                                else{
                                    $imgUrl = '../img/empty.png';
                                }

                                }
                            }
                        }
                        ?>

                        <?php if (!empty($imgUrl)): ?>
                            <img 
                            id="targetImage" 
                            src="<?= htmlspecialchars($imgUrl) ?>" 
                            class="img-thumbnail img-fluid" 
                            alt="편집할 이미지" 
                            style="max-width:350px; cursor:pointer;"
                            >
                        <?php else: ?>
                            <p class="text-muted">이미지가 없습니다.</p>
                        <?php endif; ?>

                        <div class="paste-overlay" style="display: none;">
                            <i class="bi bi-clipboard-plus"></i>
                            <span>Ctrl+V로 이미지 붙여넣기</span>
                        </div>
                        </div>
                    </div>
                </div>

                </div>
				</div>	
				<div class="row">
                <!-- 재질별 폭합 테이블 -->
                <div id="materialSummaryArea" class="assembly-area" style="<?= !$is_assembly_model ? 'display:none;' : '' ?>">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h5 class="mb-0 me-5">재질별 폭합</h5>
                        <small class="text-muted">※ 각 부품의 합계 마지막 값을 재질별로 집계</small>
                    </div>
                    <div class="d-flex justify-content-start align-items-center mb-2">
                    <div class="table-responsive">
                        <table class="table table-bordered table-sm w-auto" id="materialSummaryTable">
                            <thead class="table-secondary">
                                <tr>
                                    <th class="text-center" style="width: 50%;">재질</th>
                                    <th class="text-center" style="width: 50%;">폭합계</th>
                                </tr>
                            </thead>
                            <tbody>
                                <!-- JavaScript로 동적으로 생성됨 -->
                            </tbody>
                        </table>
                    </div>
                    </div>
                </div>
                <div id="assemblyModelArea" class="assembly-area" style="<?= !$is_assembly_model ? 'display:none;' : '' ?>">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <h5 class="mb-0">절곡 부품 조립</h5>
                        <div class="d-flex gap-2">
                            <button type="button" id="addPartBtn" class="btn btn-sm btn-info viewmode"><i class="bi bi-plus-lg"></i> 부품 추가</button>
                            <button type="button" id="removeAllPartBtn" class="btn btn-sm btn-danger viewmode"><i class="bi bi-trash"></i> 전체 삭제</button>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <div class="d-flex gap-2">
                            <button type="button" id="resetOrderBtn" class="btn btn-sm btn-outline-secondary viewmode"><i class="bi bi-arrow-clockwise"></i> 순서 초기화</button>
                            <button type="button" id="moveUpBtn" class="btn btn-sm btn-outline-primary viewmode"><i class="bi bi-arrow-up"></i> 위로</button>
                            <button type="button" id="moveDownBtn" class="btn btn-sm btn-outline-primary viewmode"><i class="bi bi-arrow-down"></i> 아래로</button>
                        </div>
                        <small class="text-muted">※ 순서변경은 위/아래 버튼을 사용하세요</small>
                    </div>
                    <div class="table-container d-flex">
                        <table class="table table-bordered" id="assemblyTable">
                            <tbody>
                                <!-- JavaScript로 동적으로 생성됨 -->
                            </tbody>
                        </table>
                    </div>
                  </div>
				</div>
				</div>
            </div>
        </div>
</div>

