<?php
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");  

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

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

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

$title_message = '기타절곡품 절곡 전개';

// echo '<pre>';
// print_r($row);
// echo '</pre>';
// 기존에 저장된 값이 있는 경우 해당 값을 설정

$selected_prod_model = isset($row['prod_model']) ? $row['prod_model'] : '연기차단재(짜부가스켓)80*20';

?>

<style>
.image-container {
	position: relative;
	display: inline-block;
}
.image-container img {
	display: block;
}
	.input-overlay {
		position: absolute;
		background: rgba(255, 255, 255, 0.5);
		border: 1px solid blue;
		width: 50px;
		color: blue;
		/* font-weight: bold; */
	}
	
.modal-body {
    max-height: 750px; /* 원하는 높이 설정 */
    max-width: 1200px; /* 원하는 너비 설정 */
    overflow-x: auto; /* 가로 스크롤 가능 */
    overflow-y: auto; /* 세로 스크롤 가능 */
}

.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;
	border : none;
}

.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>	
							<button class="btn btn-dark btn-sm " onclick="viewWork('<?=$num?>');return false"> 절곡 작업지시서 </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 closeBtn"> <ion-icon name="close-circle-outline"></ion-icon> 닫기 </button>				
					</div>
					</div>
					</div>
            </div>
                
            <div class="card-body">
				<div class="row justify-content-center text-center">
                    <div class="d-flex align-items-center justify-content-center m-2">
                        <table class="table table-bordered">
                            <tbody>
                                <tr>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">등록일</td>
                                    <td class="text-center w100px" >
                                        <input type="date" class="form-control fs-6 " id="reg_date" readonly name="reg_date" value="<?=$reg_date?>">
                                    </td>
                                    <td class="text-center fs-6 fw-bold" >작성자</td>
                                    <td class="text-center" style="width:100px;">
                                       <div class="d-flex">
                                            <input class="form-control fs-6" id="author" name="author" readonly value="<?=$author?>" autocomplete="off">
                                        </div>
                                    </td>                                
                                    <td class="text-center fs-6 fw-bold" >비고</td>
                                    <td colspan="3" class="text-center">
                                        <input type="text" class="form-control fs-6 text-start" id="remark" name="remark" readonly value="<?=$remark?>" autocomplete="off">
                                    </td>
                                </tr>                                           
								<tr>
				<td class="text-center fs-6 fw-bold" colspan="6" >
					<div class="col text-center">
						<label class="me-3">
							제품명 : <?=$selected_prod_model?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						</label>
					</div>
				</td>


                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>		

				<!-- 이미지 표시 부분 -->
				<div class="d-flex align-items-center justify-content-center mb-5 mt-2 m-2">
					<div class="image-container mb-5">						
			<img id="checkImage"  src="<?php 						
				switch ($selected_prod_model) {
					case '연기차단재(짜부가스켓)80*20':
						echo '../img/somkeban/80x20.png';
						break;
					case '연기차단재(짜부가스켓)40*10':
						echo '../img/somkeban/40x10.png';
						break;					
				}							
		?>" alt="Image">				

					</div>
				</div>				
               <br>

		</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_prod_model?>)                                 
                            </div>
                        </td>
                    </tr>                           
                </tbody>
            </table>
        </div>
    </div>					
<div class="row justify-content-center text-center">

<?php
// 공통인 것
$rail_length = isset($row['rail_length']) ? $row['rail_length'] : 0;
$rail_width = isset($row['rail_width']) ? $row['rail_width'] : 0;
$prod_model = isset($row['prod_model']) ? $row['prod_model'] : 0;

if( $prod_model === '연기차단재(짜부가스켓)40*10')
{
	// 1번 
	$proditem1 = [
		'label' => '1번',		
		'material' => 'EGI 1.15T',
		'inputValues' => [40, 10 ],
		'bendingRates' => [0, 0],
		'sums' => [], // 나중에 계산됨
		'colors' => [false, false],
		'aAngles' => [false, false]
	];	

	
	// 테이블에 출력할 데이터를 배열로 정리
	$productData = [$proditem1];	
}

if($prod_model === '연기차단재(짜부가스켓)80*20' )
{
	// 1번 
	$proditem1 = [
		'label' => '1번',		
		'material' => 'EGI 1.15T',
		'inputValues' => [80, 20 ],
		'bendingRates' => [0, 0],
		'sums' => [], // 나중에 계산됨
		'colors' => [false, false],
		'aAngles' => [false, false]
	];	

	
	// 테이블에 출력할 데이터를 배열로 정리
	$productData = [$proditem1];	
}


// sums 계산 함수
function calculateSums($product) {
    $accumulatedSum = 0;
    $sums = [];
    foreach ($product['inputValues'] as $index => $inputVal) {
        $bendingRateVal = $product['bendingRates'][$index];
        $result = $inputVal - $bendingRateVal;
        $accumulatedSum += $result;
        $sums[] = $accumulatedSum;
    }
    return $sums;
}

// 각 제품에 대해 sums 계산 - 참조로 각 제품의 sums 업데이트
foreach ($productData as &$product) {
    $product['sums'] = calculateSums($product);
}

// 참조 해제 (필수는 아님, 안전하게 하기 위해)
unset($product);
?>

<div class="table-container">
    <table class="table">
        <thead>
            <tr>
                <th class="w100px">번호</th>
                <th class="w100px">재질</th>
                <th class="w80px">구분</th>
                <th>상세내역</th>
            </tr>
        </thead>
<tbody id="tableBody">
    <?php foreach ($productData as $productIndex => $product): ?>
        <?php 
        // 첫 번째 행에 번호를 표시 (1, 2, 3... inputValues의 길이만큼)
        echo '<tr>';
        echo '<td rowspan="6" >' . $product['label'] . '</td>';
        echo '<td rowspan="6" >' . $product['material'] . '</td>';
        echo '<td class="lightgray">번호</td>';
        echo '<td class="input-container" style="border:none!important; border-bottom: 1px solid black!important;">';
        foreach ($product['inputValues'] as $index => $value) {
            echo '<span class="form-control text-center" style="width: 30px;">' . ($index + 1) . '</span>';
        }
        echo '</td>';
        echo '</tr>';

        // 입력 값 행
        echo '<tr>';
        echo '<td class="lightgray">입력</td>';
        echo '<td class="input-container" style="border:none!important; border-bottom: 1px solid black!important;">';
        foreach ($product['inputValues'] as $value) {
            echo '<span class="yellowBold text-center" style="width: 30px;">' . $value . '</span>';
        }
        echo '</td>';
        echo '</tr>';

        // 연신율 행
        echo '<tr>';
        echo '<td class="lightgray">연신율 (-)</td>';
        echo '<td class="input-container" style="border:none!important; border-bottom: 1px solid black!important;">';
        foreach ($product['bendingRates'] as $rate) {
            echo '<span class="text-center" style="width: 30px;">' . $rate . '</span>';
        }
        echo '</td>';
        echo '</tr>';

        // 합계 행
        echo '<tr>';
        echo '<td class="lightgray">합계</td>';
        echo '<td class="input-container" style="border:none!important; border-bottom: 1px solid black!important;">';
        foreach ($product['sums'] as $sum) {
            echo '<span class="orangeBlackBold text-center" style="width: 30px;">' . $sum . '</span>';
        }
        echo '</td>';
        echo '</tr>';

        // 음영 행
        echo '<tr>';
        echo '<td class="lightgray">음영</td>';
        echo '<td class="input-container" style="border:none!important; border-bottom: 1px solid black!important;">';
        foreach ($product['colors'] as $color) {
            echo '<span  style="width: 10px; margin-left:10px; margin-right:15px;">' . ($color ? 'O' : '&nbsp;') . '</span>';
        }
        echo '</td>';
        echo '</tr>';

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


