<?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>
</head>
<body>
<?php
// 메뉴 표시 여부
$header = isset($_REQUEST['header']) ? $_REQUEST['header'] : '';
$searchItem = isset($_REQUEST['searchItem']) ? $_REQUEST['searchItem'] : '';   // 제품검사요청서의 searchItem 설정 distributor 인 경우 return 변수 바꿈

if($header == 'header')
	require_once($_SERVER['DOCUMENT_ROOT'] . '/myheader.php');

// 검색어 (searchtag 컬럼 기준 검색)
$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';

$tablename = 'acigroup';

require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$orderBy = " ORDER BY num DESC";

if (trim($search) !== '') {
    $sql = "SELECT * FROM " . $DB . "." . $tablename . " WHERE groupName LIKE :search  and is_deleted IS NULL  " . $orderBy;
} else {
    $sql = "SELECT * FROM " . $DB . "." . $tablename . " WHERE  is_deleted IS NULL  " . $orderBy;
}

try {
    $stmt = $pdo->prepare($sql);
    if (trim($search) !== '') {
        $stmt->bindValue(':search', '%' . $search . '%', PDO::PARAM_STR);
    }
    $stmt->execute();
    $total_row = $stmt->rowCount();
} catch (PDOException $Exception) {
    print "오류: " . $Exception->getMessage();
}
?>	

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">
    <input type="hidden" id="mode" name="mode" value="">
    <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 ?>">
	<input type="hidden" id="searchItem" name="searchItem" value="<?=$searchItem?>" > 	
	
<!-- 모달 HTML (현장명 조회 Modal) -->
<div class="container-fluid justify-content-center align-items-center">  
	<div id="outworkplaceModal" class="modal fade" tabindex="-1">
		<div class="modal-dialog modal-full" role="document">
			<div class="modal-content">
				<div class="modal-header">
					<h2 class="modal-title">품질관리서 그룹 조회</h2>
					<button type="button" class="btn btn-outline-dark Modalclose" data-dismiss="modal">
						<i class="bi bi-x-lg"></i>
					</button>
				</div>
				<div class="modal-body">
					<table class="table table-hover">
						<thead class="table-primary">
							<tr>
								<th class="text-center" style="width:5%;">No</th>
								<th class="text-center" style="width:10%;">품질관리서번호</th>								
								<th class="text-center" style="width:5%;">수주No</th>								
								<th class="text-center" style="width:30%;">현장명</th>								
								<th class="text-center" style="width:10%;">수신처</th>
							</tr>                                          
						</thead>
						<tbody class="ModalBody">
						</tbody>
					</table>
				</div>
				<div class="modal-footer">					
					<button type="button" class="btn btn-outline-dark btn-sm Modalclose" data-dismiss="modal">
						<i class="bi bi-x-lg"></i> 닫기
					</button>
				</div>			
			</div>
		</div>
	</div>
</div>	
    
    <?php 
    if ($header !== 'header') {
        echo '<div class="container-fluid">';
        echo '<div class="card justify-content-center text-center mt-1">';
    } else {
        echo '<div class="container">';
        echo '<div class="card justify-content-center text-center mt-5">';
    }
    ?>
    
    <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="d-flex justify-content-center align-items-center mb-2">
            ▷ <?= $total_row ?> &nbsp; 
            <div class="inputWrap30">
                <input type="text" id="search" class="form-control" style="width:150px;" name="search" value="<?= $search ?>" autocomplete="off" onKeyPress="if (event.keyCode==13){ enter(); }">
                <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>
            <?php 
            if ($header !== 'header') {
                echo '<button id="closeBtn" type="button" class="btn btn-outline-dark btn-sm"><i class="bi bi-x-lg"></i> 창닫기</button>';
            }
            ?>
        </div>
        
        <div class="table-responsive">
            <table class="table table-hover" id="myTable">
                <thead class="table-primary">
                    <tr>
                        <th class="text-center">등록일</th>
                        <th class="text-center">품질관리서번호</th>
                        <th class="text-center">품질관리서 그룹명</th>
                        <th class="text-center">연결된 수주Num </th>
                        <th class="text-center">제품검사 요청서 생성 </th>
                        <th class="text-center w100px">삭제</th>
                    </tr>
                </thead>
                <tbody>
                <?php 
                while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                      include '_row.php';
                ?>
                    <tr >
                        <td class="text-center " onclick="updateFn('<?= $num ?>','<?= $groupCode ?>','<?= $groupName ?>');"><?= htmlspecialchars($registdate) ?></td>
						<!-- 예시: 그룹 리스트 테이블 내 그룹코드 열 -->
						<td class="text-center text-secondary">
							<?= htmlspecialchars($groupCode) ?>
							<button type="button" class="btn btn-primary fetch_loadgroupBtn btn-sm" data-groupcode="<?= $groupCode ?>"> 
								<i class="bi bi-search"></i>
							</button> 	 	 
						</td>

                        <td class="text-start text-dark fw-bold" title="<?= htmlspecialchars($groupName) ?>" onclick="updateFn('<?= $num ?>','<?= $groupCode ?>','<?= $groupName ?>');"><?= htmlspecialchars($groupName) ?></td>                        
                        <td class="text-start" onclick="updateFn('<?= $num ?>','<?= $groupCode ?>','<?= $groupName ?>');" ><?= htmlspecialchars($connectedNum) ?></td>                        
                        <td class="text-center" > 
                            <button type="button" class="btn btn-primary btn-sm" onclick="makeArray('<?= $groupCode ?>', '<?= $connectedNum ?>' , '<?= $groupCode ?>' ); event.stopPropagation();">
                                생성
                            </button>						
						</td>                        
                        <td class="text-center">
                            <button type="button" class="btn btn-danger btn-sm" onclick="delFn('<?= $num ?>'); event.stopPropagation();">
                                <i class="bi bi-x-circle"></i>
                            </button>
                        </td>
                    </tr>
                <?php 
                }
                ?>
                </tbody>
            </table>
        </div>
    </div>
    
    </div>
    </div>
</form>
</body>
</html>

<script>
// 페이지 로딩 시 로딩창 숨김
$(document).ready(function(){	
    var loader = document.getElementById('loadingOverlay');
    if(loader) loader.style.display = 'none';
});

// DataTables 초기 설정
$(document).ready(function() {
    var dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": false,
        "pageLength": 20,
        "lengthMenu": [20, 50, 100, 200, 500, 1000, 2000],
        "language": {
            "lengthMenu": "Show _MENU_ entries"
        },
        "order": [[0, 'desc']]
    });
    
    // 페이지 번호 저장 및 복원
    dataTable.on('page.dt', function() {
        var pageNumber = dataTable.page.info().page + 1;
        setCookie('acipageNumber', pageNumber, 10);
    });
    
    var savedPageNumber = getCookie('acipageNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
    }
    
    $('#myTable_length select').on('change', function() {
        dataTable.page.len($(this).val()).draw();
        var savedPageNumber = getCookie('acipageNumber');
        if (savedPageNumber) {
            dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
        }
    });
});

// 엔터키 입력 시 폼 제출
function enter() {
    $("#board_form").submit();	       		
}

// ESC 키 누르면 창 닫기
$(document).keydown(function(e){
    var code = e.keyCode || e.which;
    if (code == 27) {
        self.close();
    }
});

function updateFn(num, groupCode, groupName) {
   var header = $("#header").val();	
   var searchItem = $("#searchItem").val();
		
	if(searchItem == 'group') // group이라고 지정하면 부모창으로 전달함
	{				
		if (opener && opener.document) {				
			$("#ACIgroupCode", opener.document).val(groupCode); 							
			$("#ACIgroupName", opener.document).val(groupName); 				
			setTimeout(function() {                
				self.close();
			}, 500);				
		}
		
	} else {						
		popupCenter('./write.php?num=' + num + '&header=' + header, '수정', 1400, 800);
	}
}

// 제품검사 요청서 생성
function makeArray(num, groupListCode, groupCode ) {        
    // URL 인코딩 적용 (콤마 등 특수 문자 처리)
    var encodedGroupListCode = encodeURIComponent(groupListCode);
    
    // 올바른 URL 형식으로 수정 (쿼리 스트링에 '=' 추가)
    popupCenter('../output/view_requestACIgroup.php?groupCode=' + groupCode + '&groupListCode=' + encodedGroupListCode , '', 800, 900);
}


// 삭제 버튼 동작
function delFn(num) {
    $("#mode").val("delete");
    $("#num").val(num);
    
    Swal.fire({
        title: '해당 그룹 삭제',
        text: "삭제 시 복구할 수 없습니다. 정말 삭제하시겠습니까?",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#d33',
        confirmButtonText: '삭제',
        cancelButtonText: '취소'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: "process.php",
                type: "post",
                data: $("#board_form").serialize(),
                success: function(data) {
                    console.log(data);
                    Toastify({
                        text: "그룹 삭제 완료!",
                        duration: 3000,
                        close: true,
                        gravity: "top",
                        position: "center",
                        backgroundColor: "#4fbe87",
                    }).showToast();
                    setTimeout(function() {
                        location.reload();
                    }, 1500);
                },
                error: function(jqxhr, status, error) {
                    console.log(jqxhr, status, error);
                }
            });
        }
    });
}

// 신규 및 창닫기 버튼 클릭 이벤트
$("#newBtn").on("click", function() {	
    popupCenter('./write.php', '그룹 신규등록', 1400, 800);
});
$("#closeBtn").on("click", function() {
    self.close();
});

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

</script>

<!-- JavaScript 코드 -->
<script>
// 전역 변수: AJAX 요청 객체 (중복 요청 방지를 위함)
var ajaxRequest_outworkplace = null;

// 모달에 현장명 리스트를 채워 넣는 함수
function call_outworkplace(groupCode) {
    // 기존 AJAX 요청이 있을 경우 중단
    if (ajaxRequest_outworkplace !== null) {
        ajaxRequest_outworkplace.abort();
    }
    
    ajaxRequest_outworkplace = $.ajax({
        url: 'fetch_outworkplace.php', // PHP 파일 경로
        type: 'POST',
        data: { search : groupCode }, // 그룹코드만 전달
        dataType: 'json',
        success: function(data) {
            var tbody = $('.ModalBody');
            tbody.empty(); // 기존 데이터 삭제
			console.log(data);
            if (Array.isArray(data) && data.length > 0) {
                // 결과 데이터가 있을 경우 각 행을 생성
				data.forEach(function(row, index) {
					var tr = $('<tr>')
						.attr('data-num', row.num)  // row.num을 data-num 속성에 저장
						.on('click', function() {   // tr 클릭 시 이벤트 발생
							redirectToView($(this).data('num'));
						})
						.append(
							$('<td>').addClass('text-center').text(index + 1),
							$('<td>').addClass('text-start').html(row.ACIgroupCode),
							$('<td>').addClass('text-start').html(row.num),
							$('<td>').addClass('text-start').html(row.outworkplace),
							$('<td>').addClass('text-start').html(row.receiver)
						);
					tbody.append(tr);
				});

            } else {
                // 데이터가 없으면 안내 메시지 표시
                var tr = $('<tr>').append(
                    $('<td>').attr('colspan', '5').addClass('text-center').text('데이터가 없습니다.')
                );
                tbody.append(tr);
            }
            // 모달창 표시
            $('#outworkplaceModal').modal('show');

            // 모달 닫기 버튼 이벤트 (필요 시)
            $(document).on('click', '.Modalclose', function() {
                $('#outworkplaceModal').modal('hide');
            });
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.error('AJAX 요청 실패:', textStatus, errorThrown);
            var tbody = $('.ModalBody');
            tbody.empty();
            var tr = $('<tr>').append(
                $('<td>').attr('colspan', '5').addClass('text-center').text('데이터 로드 중 오류 발생')
            );
            tbody.append(tr);
        }
    });
}

function redirectToView(num) {	
    var tablename = 'output';
    var url = "/output/write_form.php?mode=view&num=" + num + "&tablename=" + tablename;          
	customPopup(url, '수주 내역', 1900, 920); 		    
}


// 그룹의 "검색" 버튼 클릭 시 해당 그룹코드를 가져와 모달창 호출
$(document).on('click', '.fetch_loadgroupBtn', function() {
    var groupCode = $(this).data('groupcode');  // 버튼에 저장된 그룹코드 값 가져오기
    call_outworkplace(groupCode);
});

</script>