<?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 = '셔터 모델 및 절곡물 품목 관리';
?>
<title> <?=$title_message?> </title>
<style>
	#myTable tbody tr.details-disabled:hover {
	  background-color: transparent !important;
	}
</style>
</head>

<body>         
<?php require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php'); ?>   
<?php
$search = $_REQUEST['search'] ?? '';
$model_name = $_REQUEST['model_name'] ?? '';
$mode = $_REQUEST['mode'] ?? '';

$tablename = 'models';

$order_by = "ORDER BY model_id DESC";

// 기본 조건
$conditions = ["is_deleted = 0"];
$bindParams = [];

if (!empty($search)) {
    $columns = [];
    $columnSql = "SHOW COLUMNS FROM {$DB}.{$tablename}";
    $colStmt = $pdo->query($columnSql);
    $allColumns = $colStmt->fetchAll(PDO::FETCH_COLUMN);

    $i = 0;
    foreach ($allColumns as $colName) {
        if (in_array($colName, ['is_deleted'])) continue;

        $paramKey = ":search_" . $i;
        $columns[] = "{$colName} LIKE {$paramKey}";
        $bindParams[$paramKey] = '%' . $search . '%';
        $i++;
    }

    if (!empty($columns)) {
        $conditions[] = '(' . implode(' OR ', $columns) . ')';
    }
}

// 선택된 model_name 필터
if (!empty($model_name)) {
    $conditions[] = "model_name = :model_name";
    $bindParams[':model_name'] = $model_name;
}

$sqlWhere = implode(" AND ", $conditions);
$sql = "SELECT * FROM {$DB}.{$tablename} WHERE {$sqlWhere} {$order_by}";

// echo $sql; // 디버깅 출력

try {
    $stmh = $pdo->prepare($sql);
    foreach ($bindParams as $key => $val) {
        $stmh->bindValue($key, $val);
    }
    $stmh->execute();
    $total_row = $stmh->rowCount();
?>

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

    <input type="hidden" id="model_id" name="model_id">
    <input type="hidden" id="mode" name="mode" value="<?=$mode?>">
    <input type="hidden" id="tablename" name="tablename" value="<?= $tablename ?>">             
	
<div class="container-fluid">
<div class="card justify-content-center text-center mt-3">
	<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>  	   		  						
		</div>
	</div>	
    <div class="card-body">    
		<div class="alert alert-success" role="alert">
			케이스는 모델별 공통으로 제외하고, 가이드레일 형태별 모델을 정의합니다.
		</div>	
	
		<?php include $_SERVER['DOCUMENT_ROOT'] . '/lot/lotTable.php'; ?>	
        <div class="d-flex justify-content-center align-items-center mb-4">                                                                           
            <button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadmodelBtn(); return false; " > <i class="bi bi-kanban"></i> 셔터 모델관리 </button>                
            <!-- <button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadQCBtn(); return false; " > <i class="bi bi-pencil-square"></i> 절곡물 품목관리 </button>  -->
            <button type="button" class="btn btn-dark btn-sm mx-1" onclick="loadTreeBtn(); return false; " > <i class="bi bi-tree"></i> 모델 Tree(절곡품목등록) </button>                
            <button type="button" class="btn btn-dark btn-sm mx-1" onclick="gotoBendingListBtn(); return false; " > <i class="bi bi-journal-text"></i> 절곡 기초자료(바라시) </button>                
			
            <button type="button" class="btn btn-primary btn-sm ms-1 me-1 " onclick="guiderailBtn(); return false; " > <i class="bi bi-door-open"></i> 가이드레일  </button>                
            <button type="button" class="btn btn-primary btn-sm mx-1" onclick="caseBtn(); return false; " > <i class="bi bi-file-break"></i> 케이스  </button>                
            <button type="button" class="btn btn-primary btn-sm mx-1" onclick="bottombarBtn(); return false; " > <i class="bi bi-input-cursor"></i> 하장바세트  </button>                
        </div>
        <div class="d-flex justify-content-center align-items-center mb-2">                                         
            ▷ <?= $total_row ?> &nbsp;  
			
			<!-- 제품모델(KSS01 등) 선택 -->
			<?php  selectModel('model_name', $model_name);  ?>			
						
            <div class="inputWrap30">           
                <input type="text" id="search" class="form-control mx-1" style="width:150px;" name="search" value="<?=$search?>" onKeyPress="if (event.keyCode==13){ enter(); }" autocomplete="off">
                <button class="btnClear"></button>
            </div>                                       
            <button class="btn btn-outline-dark btn-sm mx-1" type="button" id="searchBtn"> <i class="bi bi-search"></i> </button> 
            <button id="newBtn" type="button" class="btn btn-dark btn-sm mx-1"> <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 details-control" style="width:30px;"></th>
            <th class="text-center" style="width:50px;">번호</th>
            <th class="text-center" style="width:100px;">대분류</th>
            <th class="text-center" style="width:200px;">모델명</th>
            <th class="text-center" style="width:150px;">가이드레일</th>
            <th class="text-center" style="width:150px;">마감타입</th>
            <th class="text-center" style="width:300px;">설명</th>
            <th class="text-center" style="width:150px;">등록일</th>
            <th class="text-center" style="width:150px;">수정일</th>
        </thead>
        <tbody>                        
        <?php           
			$start_num = $total_row;              
			while($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
			?>                   
			<tr data-model_id="<?= $row['model_id'] ?>"   >
				<!-- 펼침/접힘 컨트롤 셀 -->
				<td class="details-control"><i class="bi bi-plus"></i> </td>
				<td class="text-center"><?= $start_num ?></td>
				<td onclick="redirectToView('<?=$row['model_id']?>')" class="text-center fw-bold"><?= htmlspecialchars($row['major_category'], ENT_QUOTES, 'UTF-8') ?></td>
				<td onclick="redirectToView('<?=$row['model_id']?>')" class="text-center fw-bold"><?= htmlspecialchars($row['model_name'], ENT_QUOTES, 'UTF-8') ?></td>
				<td onclick="redirectToView('<?=$row['model_id']?>')" class="text-center"><?= htmlspecialchars($row['guiderail_type'], ENT_QUOTES, 'UTF-8') ?></td>
				<td onclick="redirectToView('<?=$row['model_id']?>')" class="text-center"><?= htmlspecialchars($row['finishing_type'], ENT_QUOTES, 'UTF-8') ?></td>
				<td onclick="redirectToView('<?=$row['model_id']?>')" class="text-center"><?= htmlspecialchars($row['description'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['created_at'], ENT_QUOTES, 'UTF-8') ?></td>
				<td class="text-center"><?= htmlspecialchars($row['updated_at'], ENT_QUOTES, 'UTF-8') ?></td>
			</tr>
        <?php
				$start_num--;
			}
			} catch (PDOException $Exception) {
				print "오류: ".$Exception->getMessage();
		}  
        ?>       
        </tbody>
        </table>
        </div>
    </div>
</div>      
</form>

<!-- 페이지 로딩 및 DataTable 초기화 -->
<script>
var table;
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
    if(loader)
        loader.style.display = 'none';
});

$(document).ready(function() {
    // DataTable에 details-control 열이 첫 번째 열로 추가됨
    table = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": true,
        "pageLength": 50,
        "lengthMenu": [25, 50, 100, 200, 500, 1000],
        "language": {
            "lengthMenu": "Show _MENU_ entries",
            "search": "Live Search:"
        },
		"columnDefs": [{
			"orderable": false,
			"className": 'details-control',
			"targets": 0,
			"defaultContent": '<i class="bi bi-plus"></i>'
		}],
		
        "order": [[1, 'desc']]
    });
    
    var savedPageNumber = getCookie('modelpageNumber');
    if (savedPageNumber) {
        table.page(parseInt(savedPageNumber) - 1).draw(false);
    }

    table.on('page.dt', function() {
        var modelpageNumber = table.page.info().page + 1;
        setCookie('modelpageNumber', modelpageNumber, 10);
    });

    $('#myTable_length select').on('change', function() {
        var selectedValue = $(this).val();
        table.page.len(selectedValue).draw();
        savedPageNumber = getCookie('modelpageNumber');
        if (savedPageNumber) {
            table.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });
});

// 펼침/접힘 클릭 이벤트 수정
$('#myTable tbody').on('click', 'td.details-control', function () {
    var tr = $(this).closest('tr');
    var row = table.row(tr);
    if (row.child.isShown()) {
        row.child.hide();
        tr.removeClass('shown details-disabled');
        $(this).html('<i class="bi bi-plus"></i>');
    } else {
        $(this).html('<i class="bi bi-dash-circle-fill"></i>');
        var model_id = tr.data('model_id');
        $.ajax({
            url: "sub_table.php",
            data: { model_id: model_id },
            type: "GET",
            success: function(html) {
                row.child(html).show();
                tr.addClass('shown details-disabled'); // 여기서 hover 효과를 없애기 위해 클래스 추가
                $(tr).find('td.details-control').html('<i class="bi bi-dash-circle-fill"></i>');
            },
            error: function(jqXHR, textStatus, errorThrown) {
                row.child("Error loading details").show();
                tr.addClass('shown details-disabled');
                $(tr).find('td.details-control').html('<i class="bi bi-dash-circle-fill"></i>');
            }
        });
    }
});

function restorePageNumber() {
    var savedPageNumber = getCookie('modelpageNumber');
    if (savedPageNumber) {
        table.page(parseInt(savedPageNumber) - 1).draw('page');
    }
    location.reload(true);
}

function enter() {
    $("#board_form").submit();                   
}

$(document).keydown(function(e){
    var code = e.keyCode || e.which;
    if (code == 27) { 
        self.close();
    }
});

function redirectToView(id) {
    var title = '<?=$title_message;?>';
    var tablename = $("#tablename").val();
    // 수정 화면 열기 (모달 팝업)
    popupCenter('write_form.php?mode=modify&model_id=' + id + '&tablename=' + tablename,  title, 1100, 900);    
}

// 절곡기초 바라시 이동 -> 창 띄우기
function gotoBendingListBtn() {
    var title = '<?=$title_message;?>';    
	var url = '../bending/list.php';	
    // location.href = url;	
    popupCenter(url, title, 1500, 900);    	
}

// 절곡품 가이드레일 창 띄우기
function guiderailBtn() {    
	var url = '../guiderail/list.php';	
    popupCenter(url, '', 1500, 900);    	
}

// 절곡품 케이스 창 띄우기
function caseBtn() {    
	var url = '../shutterbox/list.php';	
    popupCenter(url, '', 1500, 900);    	
}
// 절곡품 하단마감재 창 띄우기
function bottombarBtn() {    
	var url = '../bottombar/list.php';	
    popupCenter(url, '', 1500, 900);    	
}
// 모델관리
function loadmodelBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('modelslist.php',  title, 1100, 900);    
}
// 품목관리
function loadQCBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('itemlist.php',  title, 1100, 900);    
}
// 모델트리 호출
function loadTreeBtn() {
    var title = '<?=$title_message;?>';    
    popupCenter('../modelsTree/modelsTree.php',  title, 1100, 900);    
}

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

$("#newBtn").on("click", function() {      
    var title = '<?=$title_message;?>';
    var tablename = $("#tablename").val();
    popupCenter('write_form.php?tablename=' + tablename,  title + ' 신규등록', 1100, 900);    
});

$("#closeBtn").on("click", function() {
    self.close();
});
        
function reloadlist() {
    $("#board_form").submit();                
}

$(document).ready(function(){    
   var title = '<?=$title_message;?>';
   saveMenuLog(title);
});

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

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