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

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

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

// 첫 화면 표시 문구
$title_message = '절곡 바라시 기초자료';
?>

<link href="css/style.css" rel="stylesheet">
<title> <?=$title_message?> </title>
<style>
/* 라디오 버튼 스타일 */
.btn-check:checked + .btn-outline-primary {
    background-color: #0d6efd;
    border-color: #0d6efd;
    color: white;
}

.btn-check:checked + .btn-outline-success {
    background-color: #198754;
    border-color: #198754;
    color: white;
}

.btn-check:checked + .btn-outline-secondary {
    background-color: #6c757d;
    border-color: #6c757d;
    color: white;
}

.btn-group .btn {
    margin-right: 2px;
}

.btn-group .btn:last-child {
    margin-right: 0;
}
</style>

</head>
<body>

<?php
// 메뉴를 표현할지 판단하는 header
$header = $_REQUEST['header'] ?? '';

$selectedName = $_REQUEST['selectedName'] ?? '' ;
$selectedItem = $_REQUEST['selectedItem'] ?? '' ;
$selectedUA = $_REQUEST['selectedUA'] ?? '' ;
$selectedBendingCategory = $_REQUEST['selectedBendingCategory'] ?? '' ; 							// 절곡물 카테고리
$search = $_REQUEST['search'] ?? '' ;
  
if ($header == 'header') {
    require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php');
}

$tablename = 'bending';

// 1) itemName 배열 로드
$sqlItem = "SELECT DISTINCT itemName 
            FROM {$DB}.{$tablename}
            WHERE itemName IS NOT NULL AND itemName <> '' AND (is_deleted IS NULL OR is_deleted = '0')
            ORDER BY itemName ASC";
			
$stmhItem = $pdo->prepare($sqlItem);
$stmhItem->execute();
$myItemList = $stmhItem->fetchAll(PDO::FETCH_COLUMN);
// 조건 배열과 바인딩 배열
$conditions  = ["is_deleted IS NULL"]; 
$bindParams  = [];

// 대분류 선택값( selectedItem )이 있는 경우
if (!empty($selectedItem)) {
    $conditions[] = "item_sep = :selectedItem";
    $bindParams[":selectedItem"] = $selectedItem;
}

// 인정/비인정 선택값( selectedUA )이 있는 경우
if (!empty($selectedUA)) {
    $conditions[] = "model_UA = :selectedUA";
    $bindParams[":selectedUA"] = $selectedUA;
}

// 절곡물 분류 선택값( selectedBendingCategory )이 있는 경우
if (!empty($selectedBendingCategory)) {
    $conditions[] = "item_bending = :selectedBendingCategory";
    $bindParams[":selectedBendingCategory"] = $selectedBendingCategory;
}

// 품명 선택값( selectedName )이 있는 경우
if (!empty($selectedName)) {
    $conditions[] = "itemName = :selectedName";
    $bindParams[":selectedName"] = $selectedName;
}

// 검색어가 있는 경우 => bending 테이블 전체 컬럼을 LIKE 검색
if (!empty($search)) {
    // bending 테이블 컬럼 목록 조회
    $columns = [];
    $stmt = $pdo->query("SHOW COLUMNS FROM {$DB}.{$tablename}");
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $columns[] = $row['Field'];
    }

    $searchConditions = [];
    foreach ($columns as $index => $col) {
        $paramName = ":search{$index}";
        $searchConditions[] = "$col LIKE $paramName";
        $bindParams[$paramName] = "%{$search}%";
    }
    if (!empty($searchConditions)) {
        // (col1 LIKE :search0 OR col2 LIKE :search1 OR ...)
        $conditions[] = "(" . implode(" OR ", $searchConditions) . ")";
    }
}

// ------------------------------------------------------
// 최종 SQL 구성

$sqlWhere = implode(" AND ", $conditions);   // is_deleted IS NULL AND item_sep = :selectedItem AND ...
$sqlOrder = "ORDER BY num DESC";
$sql = "SELECT * FROM {$DB}.{$tablename} WHERE {$sqlWhere} {$sqlOrder}";

// prepare -> bind -> execute
$stmh = $pdo->prepare($sql);
$stmh->execute($bindParams);
$total_row = $stmh->rowCount();

// print $sql;

// 업로드 이미지 폴더 (절대경로 or 상대경로)
$upload_dir = '../bending/img/';
?>

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">

    <input type="hidden" id="num" name="num">
    <input type="hidden" id="tablename" name="tablename" value="<?=$tablename?>">
    <input type="hidden" id="header" name="header" value="<?=$header?>">

    <?php if($header !== 'header'): ?>
      <div class="container-fluid">
      <div class="card justify-content-center text-center mt-1">
    <?php else: ?>
      <div class="container-fluid">
      <div class="card justify-content-center text-center mt-5">
    <?php endif; ?>	
		<div class="card-header">
			<div class="d-flex justify-content-center align-items-center">   
				<span class="text-center fs-5">  <?=$title_message?>   </span>         
				<button type="button" class="btn btn-dark btn-sm mx-2"  onclick='location.reload();' > <i class="bi bi-arrow-clockwise"></i> </button>  
             <?php if(!empty($header)) : ?>				
				<button type="button" class="btn btn-dark btn-sm mx-1" onclick="gotoBendingModelBtn(); return false; " > <i class="bi bi-dpad"></i> 절곡 모델설정 이동 </button>                
				<button type="button" class="btn btn-dark btn-sm mx-1" onclick="gotoBOMBtn(); return false; " > 절곡 BOM 이동 </button>   
			<?php endif; ?>
             <?php if(empty($header)) : ?>
				<button type="button" class="btn btn-dark btn-sm mx-2"  onclick='window.close();' > &times; 닫기 </button>  	   		  		
			 <?php endif; ?>
                      				 
			</div>
		</div>	

        <div class="card-body">
			<?php include $_SERVER['DOCUMENT_ROOT'] . '/lot/lotTable.php'; ?>	
            <div class="d-flex justify-content-center text-center align-items-center mb-2">
                ▷ <?= $total_row ?>&nbsp;		
				<?php				  
				  $jsonFile = $_SERVER['DOCUMENT_ROOT'].'/models/models.json';
				  $modelsList = [];
				  if(file_exists($jsonFile)){
					  $jsonContent = file_get_contents($jsonFile);
					  $modelsList = json_decode($jsonContent, true);
					  if(!is_array($modelsList)) {
						  $modelsList = [];
					  }
				  }			 	  
			?>				

			<!-- 대분류 라디오 버튼 -->
			<div class="mx-2">                
				<div class="btn-group" role="group" aria-label="대분류 선택">
					<?php
					$l1_list = getCategoryByName(); // 1단계 전체 이름 배열을 가져옴
					
					// 전체 옵션 추가
					$checked_all = (empty($selectedItem)) ? ' checked' : '';
					echo '<input type="radio" class="btn-check" name="selectedItem" id="selectedItem_all" value=""' . $checked_all . '>';
					echo '<label class="btn btn-outline-secondary btn-sm" for="selectedItem_all">전체</label>';
					
					foreach ($l1_list as $item) {
						$checked = ($selectedItem === $item) ? ' checked' : '';
						echo '<input type="radio" class="btn-check" name="selectedItem" id="selectedItem_' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '" value="' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '"' . $checked . '>';
						echo '<label class="btn btn-outline-primary btn-sm" for="selectedItem_' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '</label>';
					}
					?>
				</div>
			</div>
			
			<!-- 인정/비인정 라디오 버튼 -->
			<div class="mx-2">                
				<div class="btn-group" role="group" aria-label="인정/비인정 선택">
					<?php
					$UA_list = ['인정', '비인정']; 
					
					// 전체 옵션 추가
					$checked_all_UA = (empty($selectedUA)) ? ' checked' : '';
					echo '<input type="radio" class="btn-check" name="selectedUA" id="selectedUA_all" value=""' . $checked_all_UA . '>';
					echo '<label class="btn btn-outline-secondary btn-sm" for="selectedUA_all">전체</label>';
					
					foreach ($UA_list as $item) {
						$checked = ($selectedUA === $item) ? ' checked' : '';
						echo '<input type="radio" class="btn-check" name="selectedUA" id="selectedUA_' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '" value="' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '"' . $checked . '>';
						echo '<label class="btn btn-outline-success btn-sm" for="selectedUA_' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '">' . htmlspecialchars($item, ENT_QUOTES, 'UTF-8') . '</label>';
					}
					?>
				</div>
			</div>
			
			<?php
			// 예: getCategoryByName($parentName) 함수가 존재하며,
			// '절곡물'이라는 2단계 카테고리의 자식(3단계) 카테고리 이름 배열을 리턴한다.
			$l3_list = getCategoryByName('스크린','절곡물');			
			?>
			<select id="selectedBendingCategory" name="selectedBendingCategory" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
				<option value="">(중분류)</option>
				<?php foreach($l3_list as $itemVal): ?>
					<option 
						value="<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>"
						<?= ($selectedBendingCategory === $itemVal) ? 'selected' : '' ?>>
						<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>
					</option>
				<?php endforeach; ?>
			</select>
				
			<select id="selectedName" name="selectedName" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
				<option value="">(품명)</option>
				<?php foreach($myItemList as $itemVal): ?>
					<option 
						value="<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>"
						<?= ($selectedName === $itemVal) ? 'selected' : '' ?>>
						<?= htmlspecialchars($itemVal, ENT_QUOTES, 'UTF-8') ?>
					</option>
				<?php endforeach; ?>
			</select>

                <!-- 검색어 입력 -->
                <div class="inputWrap30 mx-1">
                    <input type="text" id="search" class="form-control" style="width:150px;" name="search" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }" autocomplete="off">
                    <button class="btnClear"></button>
                </div>
				
                &nbsp;&nbsp;
                <button class="btn btn-outline-dark btn-sm" type="button" id="searchBtn">
                    <i class="bi bi-search"></i>
                </button>
                &nbsp;&nbsp;&nbsp;&nbsp;
				
                <button id="newBtn" type="button" class="btn btn-dark btn-sm me-2">
                    <i class="bi bi-pencil-square"></i> 신규
                </button>
            </div>

            <div class="table-responsive">
                <table class="table table-hover" id="myTable">
                    <thead class="table-primary">
                        <th class="text-center">NO</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>
                        <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>
                        <th class="text-center">A각 수</th>
                        <th class="text-center">폭합</th>
                        <th class="text-center">작성</th>
                        <th class="text-center">검색어</th>
                        <th class="text-center">비고</th>
                    </thead>
					
                    <tbody>
                    <?php
                    $start_num = $total_row;
                    while ($row = $stmh->fetch(PDO::FETCH_ASSOC)):                  
                          include '_row.php';
                    ?>
                        <tr data-num="<?= htmlspecialchars($num, ENT_QUOTES, 'UTF-8') ?>" onclick="redirectToView('<?= $num ?>','<?= $tablename ?>')">
                            <td class="text-center text-secondary"><?= htmlspecialchars($start_num) ?></td>
                            <td class="text-center text-secondary"><?= htmlspecialchars($registration_date) ?></td>
                            <td class="text-center text-secondary"><?= htmlspecialchars($item_sep) ?></td>
                            <td class="text-center text-secondary"><?= htmlspecialchars($model_UA) ?></td>
                            <td class="text-center text-dark fw-bold"><?= htmlspecialchars($item_bending) ?></td>
                            <td class="text-start text-primary"><?= htmlspecialchars($itemName) ?></td>
                            <td class="text-center text-danger"><?= htmlspecialchars($item_spec) ?></td>
                            <!-- 이미지(형상) -->
                            <td class="text-center">
                            <?php if (!empty($imgdata)): ?>
                                <img src="<?= $upload_dir . htmlspecialchars($imgdata) ?>"
                                     alt="형상 이미지"
                                     style="max-width:100px; max-height:50px; height:auto; width:auto;">
                            <?php else: ?>
                                <span class="text-secondary">이미지 없음</span>
                            <?php endif; ?>
                            </td>
                            <!-- 재질 -->
                            <td class="text-center fw-bold">
                                <?= htmlspecialchars($material) ?>
                            </td>
                            <!-- 폭의 합 -->
                            <td class="text-center text-dark">
                                <?= end($sumList) ?>
                            </td>
                            <!-- 절곡회수 -->
                            <td class="text-center text-danger fw-bold">
                            <?php
                                $nonEmptyCount = count(array_filter($sumList, function($v){return $v !== false;}));
                                echo $nonEmptyCount > 0 ? ($nonEmptyCount - 1) : '';
                            ?>
                            </td>
                            <!-- 역방향(음영) -->
                            <td class="text-center text-dark">
                            <?php
                                $nonEmptyCount = count(array_filter($colorList, function($v){return $v !== false;}));
                                echo $nonEmptyCount > 0 ? $nonEmptyCount : '';
                            ?>
                            </td>
                            <!-- A각 -->
                            <td class="text-center text-dark">
                            <?php
                                $nonEmptyCount = count(array_filter($AList, function($v){return $v !== false;}));
                                echo $nonEmptyCount > 0 ? $nonEmptyCount : '';
                            ?>
                            </td>
                            <!-- 폭합 -->
                            <td class="text-center text-dark">
                                <?= $widthsum ?>
                            </td>
                            <!-- 작성자 -->
                            <td class="text-center text-secondary">
                                <?= htmlspecialchars($author) ?>
                            </td>
                            <!-- 검색어 -->
                            <td class="text-center text-secondary">
                                <?= htmlspecialchars($search_keyword) ?>
                            </td>
                            <!-- 비고 -->
                            <td class="text-center text-secondary" title="<?= htmlspecialchars($memo) ?>">
                                <?= htmlspecialchars($memo) ?>
                            </td>
                        </tr>
                    <?php
                        $start_num--;
                    endwhile; ?>
                    </tbody>
                </table>
            </div> <!-- table-responsive end -->
        </div> <!-- card-body end -->
    </div> <!-- card end -->
</form>

<!-- 페이지로딩 -->
<script>
// 페이지 로딩
$(document).ready(function(){
	var loader = document.getElementById('loadingOverlay');
    if(loader) {
		loader.style.display = 'none';
    }
});
	
var ajaxRequest_write = null;
var dataTable; // DataTables 인스턴스 전역 변수
var bendingPageNumber; // 현재 페이지 번호 저장을 위한 전역 변수

$(document).ready(function() {
    // 포커스를 이동시킴, 강제로 포커스를 얻으면 계속 창이 뜨는 것을 방지함
    if (opener && opener.document) {
        $("#workplacename", opener.document).focus(); // 오프너 문서의 특정 요소에 포커스 설정
    }

    // DataTables 초기 설정
    dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": false,
        "pageLength": 50, // 한 페이지에 표시할 항목 수
        "lengthMenu": [ 50, 100, 200, 500, 1000, 2000], // 페이지당 표시 항목 선택 메뉴
        "language": {
            "lengthMenu": "Show _MENU_ entries"
        },
        "order": [[0, 'desc']] // 첫 번째 열을 기준으로 내림차순 정렬        
    });

    // 페이지 번호 복원 (초기 로드 시)
    var savedPageNumber = getCookie('bendingPageNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw(false); // 쿠키에 저장된 페이지 번호로 이동
    }

    // 페이지 변경 이벤트 리스너
    dataTable.on('page.dt', function() {
        var bendingPageNumber = dataTable.page.info().page + 1;
        setCookie('bendingPageNumber', bendingPageNumber, 10); // 쿠키에 현재 페이지 번호 저장
    });

    // 페이지 길이 셀렉트 박스 변경 이벤트 처리
    $('#myTable_length select').on('change', function() {
        var selectedValue = $(this).val();
        dataTable.page.len(selectedValue).draw(); // 페이지 길이 변경

        // 변경 후 현재 페이지 번호 복원
        savedPageNumber = getCookie('bendingPageNumber');
        if (savedPageNumber) {
            dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });
});

function restorePageNumber() {
    var savedPageNumber = getCookie('bendingPageNumber');
    location.reload(true); // 페이지를 새로고침하여 저장된 페이지 번호를 복원
}

// Enterkey 동작
function enter()
{
	$("#board_form").submit();
}

/* ESC 키 누를시 팝업 닫기 */
$(document).keydown(function(e){
	//keyCode 구 브라우저, which 현재 브라우저
	var code = e.keyCode || e.which;

	if (code == 27) { // 27은 ESC 키번호
		self.close();
	}
});

// 자식창에서 돌아와서 이걸 실행한다
function reloadlist() {
    const search = $("#search").val();
    $("#board_form").submit();
}

// 라디오 버튼 클릭 시 자동 폼 전송
$(document).ready(function() {
    // 대분류 라디오 버튼 클릭 이벤트
    $('input[name="selectedItem"]').on('change', function() {
        $("#board_form").submit();
    });
    
    // 인정/비인정 라디오 버튼 클릭 이벤트
    $('input[name="selectedUA"]').on('change', function() {
        $("#board_form").submit();
    });
});

$(document).ready(function() {

    $('.closemodal').click(function() {
        // Hide the modal with the id 'deliveryModal'
        $('#deliveryModal').modal('hide');
        self.close(); // Close the popup window after confirming
    });
    // upload
    $("#uploadBtn").on("click", function() {
          popupCenter('uploadgrid.php' , '업로드', 1850, 800);
    });		

	$("#searchBtn").on("click", function() {
		$("#board_form").submit();
	});

	$("#search_directinput").on("click", function() {
		$("#custreg_search").hide();
	});
	// 신규 버튼
	$("#newBtn").on("click", function() {
		  popupCenter('./write_form.php' , '자료 신규등록', 1800, 800);
	});
	// 창닫기 버튼
	$("#closeBtn").on("click", function() {
		self.close();
	});

});

function display(text) {
    Toastify({
        text: text,
        duration: 2000,
        close: true,
        gravity: "top",
        position: "center",
        style: {
            background: "linear-gradient(to right, #00b09b, #96c93d)",
            fontSize: '20px' // 글씨 크기를 20px로 설정
        },
    }).showToast();
}

function redirectToView(num, tablename) {	
    var url = "write_form.php?mode=view&num=" + num + "&tablename=" + tablename;          
    customPopup(url, '절곡바라시 자료 수정', 1800, 800); 		     
}

$(document).ready(function(){    
   // 방문기록 남김
   var title = '<?php echo $title_message; ?>';
   saveMenuLog(title);
});


// 절곡 모델 설정 이동
function gotoBendingModelBtn() {
    var title = '<?=$title_message;?>';    
	var url = '../models/list.php?header=header';
	
    location.href = url;
}
// 절곡 BOM 이동
function gotoBOMBtn() {
    var title = '<?=$title_message;?>';    
	var url = '../bendingfee/list.php?header=header';
	
    location.href = url;
}

//Lot No 부여법 (펼치고 접기)
$(document).ready(function() {         
    $("#bendTableToggle").on("click", function() {
        var showLotNo = getCookie("showLotNo");
        var bendTable = $("#item_Table");
        if (showLotNo === "show") {
            bendTable.css("display", "none");
            setCookie("showLotNo", "hide", 10);
        } else {
            bendTable.css("display", "block");
            setCookie("showLotNo", "show", 10);
        }
    });

    // Check the cookie value on page load and set the table visibility
    var showLotNo = getCookie("showLotNo");
    var bendTable = $("#item_Table");
    if (showLotNo === "show") {
        bendTable.css("display", "block");
    } else {
        bendTable.css("display", "none");
    }
});	

</script>

</body>
</html>
