<?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 = '절곡 작업지시서'; 

$mode = isset($_['mode']) ? $_REQUEST['mode'] : '';
$num = isset($_REQUEST['num']) ? $_REQUEST['num'] : '';
$tablename = isset($_REQUEST['tablename']) ? $_REQUEST['tablename'] : '';

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

$today = date("Y-m-d");

if(!isset($DB))
	$DB = 'chandj';

    try {
        $sql = "SELECT * FROM {$DB}.$tablename WHERE num=? ";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_INT);      
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);

        include '_row.php';
    } catch (PDOException $Exception) {
        echo "오류: ".$Exception->getMessage();
        exit;
}

// echo '<pre>';
// print_r($row);
// echo '</pre>';

// 기존에 저장된 값이 있는 경우 해당 값을 설정
$selected_exit_directionFlat = isset($row['exit_direction']) ? $row['exit_direction'] : '양면 점검구';

?>

<style>

.table-container {
    width: 100%;    
}

#dynamicTable {
    table-layout: fixed;
    width: 1000px; 
}

#dynamicTable th:first-child,
#dynamicTable td:first-child {
    width: 100px;
    min-width: 100px;
    max-width: 100px;
}

#dynamicTable th:nth-child(2),
#dynamicTable td:nth-child(2) {
    width: 900px;
    min-width: 900px;
    max-width: 900px;
} 

.input-container {
    width: 100%;    
    white-space: nowrap;
    display: flex;
    align-items: center;	
}

.input-container input,
.input-container span {
    display: inline-block;
    margin-right: 5px;
}

.input-container input[type="text"] {
    width: 30px;	
	height:30px;
}	

</style>

<div class="container-fluid">    
        <div class="card justify-content-center">
            <div class="card-header text-center">
				<div class="row">
					<div class="col-sm-2">
					</div>
					<div class="col-sm-8">
						<div class="d-flex align-items-center justify-content-center">
							<span class="text-center fs-5"><?=$title_message?></span>
							<button class="btn btn-dark btn-sm ms-5 me-2" onclick="generatePDF()"> PDF 저장 </button>								
						</div>
					</div>
					<div class="col-sm-2">
					<div class="d-flex align-items-center justify-content-end">
						<button type="button" class="btn btn-outline-dark btn-sm me-2" onclick="self.close();" > <ion-icon name="close-circle-outline"></ion-icon> 닫기 </button>				
					</div>
					</div>
					</div>
            </div>
            <div class="card-body">			   
				<div class="row mb-3">
					<div class="col text-center">
						<span class="badge fs-5 
							<?php 
								if($selected_exit_directionFlat === '양면 점검구') {
									echo 'bg-primary';
								} elseif($selected_exit_directionFlat === '밑면 점검구') {
									echo 'bg-success';
								} elseif($selected_exit_directionFlat === '후면 점검구') {
									echo 'bg-danger';
								}
							?>">
							<?php echo $selected_exit_directionFlat; ?>
						</span>
					</div>
				</div>

<div id="content-to-print">    
    <div class="row justify-content-center text-center">
        <div class="d-flex align-items-center justify-content-center m-2">
            <table class="table ">
                <tbody>
                    <tr>
                        <td class="text-center fs-6 fw-bold" colspan="6" >
                            <div class="d-flex align-items-center justify-content-center">
                                <span class="text-center fs-6 ms-1 me-1"> (<?= $selected_exit_directionFlat?>) 셔터박스 &nbsp;&nbsp;
                                <span class="text-center fs-6 ms-1 me-1"> 전면 밑 : <?=$front_bottom_width?> &nbsp;&nbsp;  레일폭 : <?=$rail_width?> &nbsp;&nbsp;&nbsp;&nbsp; </span> 
                                <span class="text-center fs-6 ms-1 me-1 text-primary"> 가로(폭): </span> 
                                <span class="text-primary ms-1 me-1"><?=$box_width?></span>
                                <span class="text-center fs-6 ms-1 me-1"> x </span> 
                                <span class="text-center fs-6 ms-1 me-1 text-danger"> 세로(높이): </span> 
                                <span class="text-danger"><?=$box_height?></span>
                            </div>
                        </td>
                    </tr>                           
                </tbody>
            </table>
        </div>
    </div>				
                <div class="row justify-content-center text-center">
								   

<?php

// 공통인 것

$box_height = isset($row['box_height']) ? $row['box_height'] : 0;
$front_bottom_width = isset($row['front_bottom_width']) ? $row['front_bottom_width'] : 0;

// 케이스 전개도 함수
require_once($_SERVER['DOCUMENT_ROOT'] . "/shutterbox/fun_case.php");
$productData = getCasePlate($selected_exit_directionFlat, $box_width, $box_height, $rail_width, $front_bottom_width);
?>

<div class="table-container">
    <table class="table">
        <thead class="table-secondary">
            <tr>
                <th class="w170px">번호</th>                
                <th class="w100px">재질</th>                
                <th>절곡치수</th>
                <th>길이</th>
                <th>수량</th>
                <th>면적</th>
            </tr>
        </thead>
<tbody id="tableBody">
    <?php foreach ($productData as $productIndex => $product): ?>
        <?php 

		// 합계 행
		echo '<tr>';
		echo '<td rowspan="2" >' . $product['label'] . '</td>';        		
		echo '<td rowspan="2" > EGI 1.55T</td>';
		echo '<td class="input-container" >';

		// sums와 colors를 함께 사용하여 배경색을 설정
		foreach ($product['sums'] as $index => $sum) {
			$backgroundColor = $product['colors'][$index] ? 'background-color: gray;' : '';
			$foreColor = $product['colors'][$index] ? 'text-white ' : '';
			echo '<span class="text-center ' . $foreColor . '" style="width: 30px; ' . $backgroundColor . '">' . $sum . '</span>';
		}
		echo '</td>';
		echo '<td></td>';
		echo '<td></td>';
		echo '<td></td>';
		echo '</tr>';

        // A각 표시 행
        echo '<tr>';        
        echo '<td class="input-container" >';
        foreach ($product['aAngles'] as $angle) {
            echo '<span style="width: 10px; margin-left:10px; margin-right:15px;">' . ($angle ? 'A"' : '&nbsp;') . '</span>';
        }
		echo '</td>';
		echo '<td></td>';
		echo '<td></td>';
		echo '<td></td>';
		echo '</tr>';
        ?>
    <?php endforeach; ?>
</tbody>
	  
    </table>
</div>
					   
                </div>
                </div>

        </div>    
        </div>    
</div>


<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();
    });		
		
});

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;
});		


function generatePDF() {	
    // 이벤트의 기본 동작을 방지 (모달창 닫힘 방지)
    event.preventDefault();

	var deadline = '<?php echo $today; ?>';
	var deadlineDate = new Date(deadline);
	var formattedDate = "(" + String(deadlineDate.getFullYear()).slice(-2) + "." + ("0" + (deadlineDate.getMonth() + 1)).slice(-2) + "." + ("0" + deadlineDate.getDate()).slice(-2) + ")";
	var result = 'KD_셔터박스_' + formattedDate + '.pdf';
    
    var element = document.getElementById('content-to-print');
    var opt = {
        margin: [10, 3, 12, 3], // Top, right, bottom, left margins
        filename: result,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 1 },
        jsPDF: { unit: 'mm', format: 'a4', orientation: 'portrait' },
        pagebreak: { mode: [''] }
    };
    html2pdf().from(element).set(opt).save();
}


</script>

