<?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'] : '';  

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

function checkNull($strtmp) {
    return ($strtmp !== null && trim($strtmp) !== '');
}

$search = isset($_REQUEST['search']) ? $_REQUEST['search'] : '';  
$mode = isset($_REQUEST["mode"]) ? $_REQUEST["mode"] : '';

$tablename = 'bendingmap';

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

$order = " ORDER BY num DESC ";

if (checkNull($search)) {
    $sql = "SELECT * FROM ".$DB.".".$tablename." 
            WHERE search_tag LIKE '%$search%' AND is_deleted IS NULL " . $order;    
} else {
    $sql = "SELECT * FROM ".$DB.".".$tablename . " WHERE is_deleted IS NULL " . $order;   
}

// 서버에 저장된 로트번호 불러오기
$filepath = $_SERVER['DOCUMENT_ROOT'] . '/output/lotnum.txt';

if (file_exists($filepath)) {
    // 파일에서 로트번호 읽기
    $receivedlotNum = file_get_contents($filepath);
} else {
    $receivedlotNum = '로트번호가 없습니다.'; // 파일이 없을 경우 기본 메시지
}

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

<form id="board_form" name="board_form" method="post" enctype="multipart/form-data">             
    <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?>">      

<div class="container-fluid">
    <!-- Modal -->
    <div id="myModal" class="modal">
        <div class="modal-content"  style="width:700px;">
            <div class="modal-header">
                <span class="modal-title">절곡품 매핑</span>
                <span class="close">&times;</span>
            </div>
            <div class="modal-body">
                <div class="custom-card"></div>
            </div>
        </div>
    </div>
</div>

<div class="container">
<div class="card justify-content-center text-center mt-1 mb-5">   
    <div class="card-header">
        <span class="text-center fs-5">  <?=$title_message?>   </span>                                        
    </div>
    <div class="card-body">  
    <div class="container mt-2 mb-2">   
    <div class="d-flex justify-content-center align-items-center mt-2 mb-2">   
            ▷ <?= $total_row ?> &nbsp; 
        <div class="inputWrap30">            
            <input type="text" id="search" class="form-control text-start" style="width:200px;" 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($level=='1') { ?>
            <!-- <button id="uploadBtn" type="button" class="btn btn-dark btn-sm me-2"> <i class="bi bi-box-arrow-up"></i> 업로드 </button>    -->
        <?php } ?>       
    </div>        
        
    <div class="table-responsive">   
       <table class="table table-hover" id="myTable">         
            <thead class="table-primary">
                 <th class="text-center" style="width:60px;" >번호</th>
                 <th class="text-center" style="width:120px;" >등록일</th>
                 <th class="text-center" style="width:150px;" >제품코드</th>
                 <th class="text-center" style="width:100px;" >레일형태</th>
                 <th class="text-center" style="width:100px;" >박스크기</th>
                 <th class="text-center" style="width:100px;" >박스점검구</th>
                 <th class="text-center" style="width:120px;" >전면부 밑면치수</th> <!-- 추가 -->
                 <th class="text-center" style="width:100px;" >레일(폭)</th>        <!-- 추가 -->
                 <th class="text-center" style="width:100px;" >작성자</th>
                 <th class="text-center" style="width:300px;" >비고</th>                 
            </thead>
            <tbody>                  
            <?php          
            $start_num = $total_row;                  
            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"><?= $row['reg_date'] ?></td>
                <td class="text-center"><?= $row['prodcode'] ?></td>
                <td class="text-center"><?= $row['railtype'] ?></td>
                <td class="text-center"><?= $row['boxsize'] ?></td>
                <td class="text-center"><?= $row['boxexit'] ?></td>
                <td class="text-center"><?= $row['frontbottom'] ?></td> <!-- 전면부 밑면치수 표시 -->
                <td class="text-center"><?= $row['railwidth'] ?></td>   <!-- 레일(폭) 표시 -->
                <td class="text-center"><?= $row['author'] ?></td>
                <td class="text-start"><?= $row['remark'] ?></td>               
            </tr>
        <?php
            $start_num--;
                 } 
              } catch (PDOException $Exception) {
                  print "오류: ".$Exception->getMessage();
              }  
        ?>         
      </tbody>
     </table>
    </div>
    </div>
    </div>        
</form>

</body>
</html>

<script>

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

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

function loadForm(mode, num = null) {
    if (num == null) {
        $("#mode").val('insert');
    } else {
        $("#mode").val('modify');
        $("#num").val(num);
    }       

    $.ajax({
        type: "POST",
        url: "fetch_modal.php",
        data: { mode: mode, num: num },
        dataType: "html",
        success: function(response) {
            $(".modal-body .custom-card").html(response);
            $("#myModal").show();

            $("#closeBtn").on("click", function() {
                $("#myModal").hide();
            });

            let isSaving = false;
            
            $("#saveBtn").on("click", function() {
                if (isSaving) return;
                isSaving = true;

                var header = $("#header").val();
                var formData = $("#board_form").serialize(); // 파일전송은 안된다. serialize의 단점                

                $.ajax({
                    url: "process.php",
                    type: "post",
                    data: formData,
                    success: function(response) {
                        Toastify({
                            text: "저장완료",
                            duration: 3000,
                            close: true,
                            gravity: "top",
                            position: "center",
                            backgroundColor: "#4fbe87",
                        }).showToast();
                    setTimeout(function() {
                            $("#myModal").hide();
                            location.reload();                                                     
                            isSaving = false;
                        }, 1000);
                        
                        
                    },
                    error: function(jqxhr, status, error) {
                        console.log(jqxhr, status, error);
                        isSaving = false;
                    }
                });
            });

            $("#deleteBtn").on("click", function() {
                var level = '<?= $_SESSION["level"] ?>';

                if (level !== '1') {
                    Swal.fire({
                        title: '삭제불가',
                        text: "관리자만 삭제 가능합니다.",
                        icon: 'error',
                        confirmButtonText: '확인'
                    });
                    return;
                }

                Swal.fire({
                    title: '자료 삭제',
                    text: "삭제는 신중! 정말 삭제하시겠습니까?",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: '삭제',
                    cancelButtonText: '취소'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $("#mode").val('delete');
                        var formData = $("#board_form").serialize();

                        $.ajax({
                            url: "process.php",
                            type: "post",
                            data: formData,
                            success: function(response) {
                                Toastify({
                                    text: "파일 삭제완료",
                                    duration: 2000,
                                    close: true,
                                    gravity: "top",
                                    position: "center",
                                    style: {
                                        background: "linear-gradient(to right, #00b09b, #96c93d)"
                                    },
                                }).showToast();

                                $("#myModal").hide();
                                location.reload();
                            },
                            error: function(jqxhr, status, error) {
                                console.log(jqxhr, status, error);
                            }
                        });
                    }
                });
            });
        },
        error: function(jqxhr, status, error) {
            console.log("AJAX Error: ", status, error);
        }
    });
}

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

    var modal = document.getElementById("myModal");
    var span = document.getElementsByClassName("close")[0];

    span.onclick = function() {
        modal.style.display = "none";
    }

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

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

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

function inputNumberFormat(obj) {
    obj.value = obj.value.replace(/[^0-9]/g, '');
    
    let value = obj.value.replace(/,/g, '');
    obj.value = value.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}

$(document).on("keypress", "input", function(event) {
    return event.keyCode != 13;
});        

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