<?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_model_name = isset($row['model_name']) ? $row['model_name'] : 'SL60';

?>

<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 type="button" class="btn btn-dark btn-sm mx-3"  onclick='location.reload();' title="새로고침"> <i class="bi bi-arrow-clockwise"></i> </button>  	 
							<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 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_model_name?> &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"><?=$bar_height?></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"><?=$bar_width?></span>
                            </div>
                        </td>
                    </tr>                           
                </tbody>
            </table>
        </div>
    </div>				
<div class="row justify-content-center text-center">

<?php
// 공통인 것
$bar_height = isset($row['bar_height']) ? $row['bar_height'] : 0;
$bar_width = isset($row['bar_width']) ? $row['bar_width'] : 0;
$model_name = isset($row['model_name']) ? $row['model_name'] : 0;

require_once($_SERVER['DOCUMENT_ROOT'] . "/bottombar/fun_bottombar.php");
$productData = getBottombarData($model_name, $finishing_type, $bar_height, $bar_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" >' .  $product['material']. '</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';		
});

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>

