<?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 = '제품 단가 설정'; 

$QCadmin = (intval($level) == 1) ? 1 : 0;

?>

<link href="css/style.css" rel="stylesheet">   
<!-- jQuery UI -->
<link href="https://code.jquery.com/ui/1.13.2/themes/base/jquery-ui.css" rel="stylesheet">
<script src="https://code.jquery.com/ui/1.13.2/jquery-ui.min.js"></script>
<!-- DataTables 기본 CSS -->
<link href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap5.min.css" rel="stylesheet">
<!-- DataTables 기본 스크립트 -->
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap5.min.js"></script>
<!-- colResize 플러그인 -->
<script src="https://cdn.datatables.net/colresize/1.6.2/js/dataTables.colResize.min.js"></script>
<link href="https://cdn.datatables.net/colresize/1.6.2/css/colResize.dataTables.min.css" rel="stylesheet">


<style>
th.sorting:before, th.sorting:after,
th.sorting_asc:before, th.sorting_asc:after,
th.sorting_desc:before, th.sorting_desc:after {
    display: none !important;
}
</style>
<title> <?=$title_message?> </title> 

</head>  
<body>         
<?php
$header = $_REQUEST['header'] ?? '';  

// 세무사아이디면 다른 메뉴 연결
if($_SESSION["userid"] == '0266771300') {
	include $_SERVER['DOCUMENT_ROOT'] . '/myheader_accountant.php'; 
}
else {
	include $_SERVER['DOCUMENT_ROOT'] . '/myheader.php'; 
}

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

$search = $_REQUEST['search'] ?? '';  
$mode = $_REQUEST['mode'] ?? '';
$tablename = 'KDunitprice';

$sql = "SELECT * FROM {$DB}.{$tablename} WHERE is_deleted IS NULL";

if (!empty($search)) {
    $sql .= " AND searchtag LIKE '%$search%'";
}

$sql .= " ORDER BY CAST(REPLACE(unitprice, ',', '') AS UNSIGNED) DESC";  // 단가 내림차순 정렬(숫자화로 처리)

try {
    $stmh = $pdo->query($sql);
    $total_row = $stmh->rowCount();
?>

<form id="board_form" name="board_form" method="post">
    <input type="hidden" id="mode" name="mode" value="<?=$mode?>">
    <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="QCadmin" name="QCadmin" value="<?=$QCadmin?>">

<?php 
if ($header == 'header') {
    print '<div class="container">';
    print '<div class="card justify-content-center text-center mt-1">';
} else {
    print '<div class="container">';
    print '<div class="card justify-content-center text-center mt-5">';
}
?>     
    <div class="card-header">        
		<div class="d-flex  p-1 m-1 mt-1 justify-content-center align-items-center"> 		
		   <h5><?=$title_message?></h5> &nbsp;&nbsp;&nbsp;&nbsp;    
		   <button type="button" class="btn btn-dark btn-sm" onclick='location.reload();'> <i class="bi bi-arrow-clockwise"></i> </button>
		   <?php if($user_name=='개발자') { ?>
		   <button id="uploadBtn" type="button" class="btn btn-dark btn-sm ms-2"> <i class="bi bi-box-arrow-up"></i> 업로드 </button> 
		   <?php } ?>
		</div>
	</div>
	<div class="card-body">
		<div class="row justify-content-center mb-3">
			<div class="col-auto">
			<div class="inputWrap">
				<input type="text" id="search" name="search" value="<?=$search?>" onkeydown="JavaScript:SearchEnter();" autocomplete="off"  class="form-control" style="width:200px;height:30px;" > &nbsp;			
				<button class="btnClear"></button>
			</div>						
			</div>
			<div class="col-auto">
				<button id="searchBtn" type="submit" class="btn btn-dark btn-sm"><i class="bi bi-search"></i> 검색</button>
			</div>
			<div class="col-auto">
				<button type="button" id="newBtn" class="btn btn-dark btn-sm">신규</button>
			</div>
		</div>
		<div class="table-responsive">
			<table class="table table-hover" id="myTable">
				<thead class="table-primary text-center">
					<tr>
						<th>번호</th>
						<th>품목코드</th>
						<th>품목명</th>
						<th>구분</th>
						<th>규격</th>
						<th>단위</th>
						<th>단가</th>						
						<th class="text-start w-25">수정로그</th>
					</tr>
				</thead>
				<tbody>
				<?php
					$start_num = 1;
					while ($row = $stmh->fetch(PDO::FETCH_ASSOC)) {
						include '_row.php';
				?>
					<tr onclick="loadForm('update', '<?=$row['num']?>')">
						<td class="text-center"><?=$start_num++?></td>
						<td class="text-center"><?=htmlspecialchars($prodcode)?></td>
						<td class="text-start"><?=htmlspecialchars($item_name)?></td>
						<td class="text-center"><?=htmlspecialchars($item_div)?></td>
						<td class="text-center"><?=htmlspecialchars($spec)?></td>
						<td class="text-center"><?=htmlspecialchars($unit)?></td>
						<td class="text-end"><?=is_numeric($unitprice) ? number_format($unitprice) : ''?></td>						
						<td class="text-start">
							<?php
								$log = $update_log;
								if (mb_strlen($log, 'UTF-8') > 30) {
									$log = mb_substr($log, 0, 30, 'UTF-8') . '…';
								}
							?>
							<?= htmlspecialchars($log, ENT_QUOTES, 'UTF-8') ?>
						</td>
					</tr>
				<?php } ?>
				</tbody>
			</table>
		</div>
	</div>
</div>
</form>

<!-- 모달 구조 -->
<div id="myModal" class="modal" style="display:none;">
	<div class="modal-content" style="width:600px;">
		<div class="modal-header">
			<span class="modal-title">단가 상세</span>
			<span class="close" onclick="$('#myModal').hide();">&times;</span>
		</div>
		<div class="modal-body">
			<div class="custom-card"></div>
			<div class="text-center mt-3">
				<button type="button" class="btn btn-dark btn-sm mx-2" id="saveBtn"> <i class="bi bi-floppy-fill"></i> 저장 </button>
				<button type="button" class="btn btn-primary btn-sm mx-2" id="copyBtn"> <i class="bi bi-copy-fill"></i> 복사 </button>
				<button type="button" id="deleteBtn" class="btn btn-danger btn-sm me-3"> <i class="bi bi-trash"></i>  삭제 
                    </button>
				<button type="button" class="btn btn-secondary btn-sm" onclick="$('#myModal').hide();"> &times; 닫기</button>
			</div>
		</div>
	</div>
</div>

<?php } catch (PDOException $e) {
    echo "오류: " . $e->getMessage();
} ?>

<script>
$(document).ready(function(){    
    var loader = document.getElementById('loadingOverlay');
	if(loader) loader.style.display = 'none';

    $('#newBtn').on('click', function() {
        loadForm('insert');
    });

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

    $('#uploadBtn').on('click', function() {
        popupCenter('uploadgrid.php', '업로드', 1800, 800);
    });

    // 복사 버튼 클릭 이벤트
    $(document).on('click', '#copyBtn', function(e) {
        e.stopPropagation(); // 이벤트 버블링 방지
        const currentNum = $('.custom-card #num').val();
        if (!currentNum) {
            Swal.fire('오류', '복사할 데이터를 선택해주세요.', 'error');
            return;
        }
        loadForm('copy', currentNum);
    });

	// 저장 처리
	$(document).on('click', '#saveBtn', function() {
		const formData = $('#board_form').serialize();
		$.ajax({
			type: 'POST',
			url: 'insert.php',
			data: formData,
			success: function(res) {
				Swal.fire('저장 완료', '', 'success');
				$('#myModal').hide();
				location.reload();
			},
			error: function(err) {
				console.error(err);
				Swal.fire('저장 실패', '오류가 발생했습니다.', 'error');
			}
		});
	});
});

var dataTable; // DataTables 인스턴스 전역 변수
var KDunitpriceNumber; // 현재 페이지 번호 저장을 위한 전역 변수

$(document).ready(function() {			
    // DataTables 초기 설정
    dataTable = $('#myTable').DataTable({
        "paging": true,
        "ordering": true,
        "searching": false,
        "pageLength": 1000,
        "lengthMenu": [100, 200, 500, 10000],
        "language": {
            "lengthMenu": "Show _MENU_ entries"
        },
        "order": [[0, 'asc']],
        "drawCallback": function() {
            // 각 열 헤더에 resizable 클래스 추가 (수정로그 열 제외)
            $('#myTable th:not(:last-child)').addClass('resizable-column');
            
            // jQuery UI resizable 적용 
            $('#myTable th:not(:last-child)').resizable({
                handles: 'e',
                minWidth: 50,
                start: function(event, ui) {
                    $(this).addClass('resizing');
                },
                resize: function(event, ui) {
                    // 현재 열의 너비를 모든 행의 셀에 적용
                    const columnIndex = $(this).index();
                    $('#myTable td:nth-child(' + (columnIndex + 1) + ')').width(ui.size.width);
                },
                stop: function(event, ui) {
                    $(this).removeClass('resizing');
                }
            });
   
        }
    });

    // 페이지 번호 복원 (초기 로드 시)
    var savedPageNumber = getCookie('KDunitpriceNumber');
    if (savedPageNumber) {
        dataTable.page(parseInt(savedPageNumber) - 1).draw(false);
    }

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

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

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

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

function loadForm(mode, num = null) {
	const postData = { 
        mode: mode,
        num: num
    };

	$.ajax({
		type: "POST",
		url: "fetch_modal.php",
		data: postData,
		success: function(response) {
			$(".modal-body .custom-card").html(response);
			$("#myModal").show();
		},
		error: function(xhr, status, error) {
			console.error("불러오기 오류:", status, error);
		}
	});
}


$(document).on('click', '#deleteBtn', function() {
    Swal.fire({
        title: '정말 삭제하시겠습니까?',
        text: "삭제된 데이터는 복구할 수 없습니다.",
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#d33',
        cancelButtonColor: '#aaa',
        confirmButtonText: '삭제',
        cancelButtonText: '취소'
    }).then((result) => {
        if (result.isConfirmed) {
            const formData = $('#board_form').serialize() + '&mode=delete';

            $.ajax({
                url: 'insert.php',
                type: 'POST',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    Swal.fire('삭제완료', '데이터가 삭제되었습니다.', 'success').then(() => {
                        $('#myModal').hide();
                        location.reload();
                    });
                },
                error: function(jqXHR, status, error) {
                    console.error('삭제 오류:', error);
                    Swal.fire('오류', '삭제 중 문제가 발생했습니다.', 'error');
                }
            });
        }
    });
});

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

</script>


</body>
</html>