<?php
include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php';
$title_message = '절곡 바라시 작업지시서'; 

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

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

		// output_extra 테이블에서 데이터 불러오기
		require_once $_SERVER['DOCUMENT_ROOT'] . '/output/load_output_extraTable.php';	

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

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

// echo '<pre>';
// echo 'eList_slat <br>';
// print_r($row['eList_slat']);
// echo '</pre>';

// 데이터 처리: eList_screen과 eList_slat를 모두 반영
$dataLists = [];
$screenorslat = '';

if(!empty($eList_screen) and $eList_screen !=='[]' and $eList_screen !=='{}' and $eList_screen !==null )
{
	$eList = json_decode($eList_screen, true);
	foreach ($eList as $row) {
		$railtype = $row['col6'];
		$boxsize = $row['col36'];
		if($boxsize == 'custom' )
			$boxsize = $row['col36_custom'];
		$boxfrontbottom = $row['col36_frontbottom'];
		$boxrailwidth = $row['col36_railwidth'];
		$boxexitdirection = $row['col36_boxdirection'];	   			
	}	
	$surang = count($eList);	
	$screenorslat = 'screen';
}
else if(!empty($eList_slat) and $eList_slat !=='[]'  and $eList_slat !=='{}'  and $eList_slat !==null )
{
	$eList = json_decode($eList_slat, true);	
	$screenorslat = 'slat';
	foreach ($eList as $row) {
		$railtype = $row['col6'];
		$boxsize = $row['col37'];
		if($boxsize == 'custom' )
			$boxsize = $row['col37_custom'];
		$boxfrontbottom = $row['col37_frontbottom'];
		$boxrailwidth = $row['col37_railwidth'];
		$boxexitdirection = $row['col37_boxdirection'];	   	  
	}
 $surang = count($eList);	
}

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

// 가이드레일 및 셔터박스 형태를 배열로 관리
$railConfigs = [
    'screen' => [
        'defaultRailType' => '벽면형',
        'validSizes' => ['120*70', '120*120'],
    ],
    'slat' => [
        'defaultRailType' => '측면형',
        'validSizes' => ['130*75', '130*125'],
    ],
];

// 데이터 출력
foreach ($dataLists as $type => $eList) {
    if (!empty($eList)) {
        echo "<h5 class='text-center mt-4 mb-2'>" . strtoupper($type) . " 데이터</h5>";

        foreach ($eList as $item) {
            $railType = $item['col6'] ?? $railConfigs[$type]['defaultRailType'];
            $boxSize = $item['col36'] ?? ($type === 'slat' ? $item['col37'] : '');

            if ($boxSize === 'custom') {
                $boxSize = $item['col36_custom'] ?? $item['col37_custom'] ?? '';
            }
			
            // echo "<div class='row'>";
            // echo "<div class='col-sm-4'>";
            // echo "<p>레일 유형: $railType</p>";
            // echo "<p>박스 크기: $boxSize</p>";
            // echo "</div>";
            // echo "</div>";
        }
    }
}

// 행의 수는 배열의 크기와 동일하므로, count() 함수를 사용하여 구합니다.
function getSLengthCode($length, $category) {
    switch ($category) {
        case '연기차단재':
            switch ($length) {
                case 'W50 × 3000':
                    return '53';
                case 'W50 × 4000':
                    return '54';
                case 'W80 × 3000':
                    return '83';
                case 'W80 × 4000':
                    return '84';
                default:
                    return null; // 해당하는 값이 없을 경우
            }
        case '기타':
            switch ($length) {
                case '1219':
                    return '12';
                case '2438':
                    return '24';
                case '3000':
                    return '30';
                case '3500':
                    return '35';
                case '4000':
                    return '40';
                case '4150':
                    return '41';
                case '4200':
                    return '42';
                case '4300':
                    return '43';
                default:
                    return null; // 해당하는 값이 없을 경우
            }
        default:
            return null; // 카테고리가 없는 경우
    }
}

// 기존에 저장된 값이 있는 경우 해당 값을 설정

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

foreach ($eList as $row) {
   	  $railtype = $row['col6'];
	}

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

try {
    // railtype에서 첫 3글자 추출 (한글이 포함될 수 있으므로 mb_substr 사용)    
    $railtype_prefix = mb_substr($railtype, 0, 3, 'UTF-8'); // 벽면형, 측면형, 혼합형

    // SQL 쿼리 작성 (check_type, prodCode, model_name 조건 추가)
    $sql = "SELECT * FROM {$DB}.guiderail WHERE check_type=? AND model_name=?";
    $stmh = $pdo->prepare($sql);    
    $stmh->bindValue(1, $railtype_prefix, PDO::PARAM_STR);  // railtype에서 추출한 세 글자
    $stmh->bindValue(2, $prodCode, PDO::PARAM_STR);         // prodCode와 일치하는 값
    $stmh->execute();
	
    $row  = $stmh->fetch(PDO::FETCH_ASSOC);
	
	// print_r($row);
	
    include '../guiderail/_row.php';
} catch (PDOException $Exception) {
    echo "오류: " . $Exception->getMessage();
    exit;
}

?>
<style>
#dynamicTable {
    table-layout: fixed;    
    margin: 0;
    padding: 1px;	
    text-align: left; /* 테이블 전체 좌측 정렬 */
}

#dynamicTable th:first-child,
#dynamicTable td:first-child {
    width: 100px;
    margin: 0;
    padding: 1px;
    text-align: left; /* 첫 번째 열 좌측 정렬 */
}

#dynamicTable th:nth-child(2),
#dynamicTable td:nth-child(2) {
    margin: 0;
    padding: 1px;
    text-align: left; /* 두 번째 열 좌측 정렬 */
} 

.input-container {    
    align-items: flex-start; /* 입력 컨테이너 좌측 정렬 */
    margin: 0;
    padding: 0px;		
}

.input-container input,
.input-container span {
    display: inline-block;    
    margin: 0;
    padding: 1px;		
    text-align: left; /* 입력 요소 좌측 정렬 */
}

.table {
    border-collapse: collapse !important;
    margin: 0;
    padding: 1px;	
    text-align: left; /* 테이블 전체 좌측 정렬 */
}
.table th, 
.table td {    
    margin: 0;
    padding: 1px;
    text-align: left; /* 모든 셀 좌측 정렬 */
}

.tcell {
	width:30px!important;
	text-align:center!important;
}

</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 id="content-to-print">    
<?php
// 기존에 저장된 값이 있는 경우 해당 값을 설정
$selected_check_type = $railtype;
$selected_model_name = $prodCode;

// print ' $railtype ' .  $railtype ;

if(!empty($rail_length))
	$railsize = $rail_length . 'x' . $rail_width ;
else
	$railsize = '';
// 정규식을 이용해 길이와 폭 값을 추출
if (preg_match('/혼합형\((\d+)\*(\d+)\)\((\d+)\*(\d+)\)/', $railtype, $matches)) {
    $rail_length1 = $matches[1];
    $rail_width1 = $matches[2];
    $rail_length2 = $matches[3];
    $rail_width2 = $matches[4];
  } 
?>						

<div class="row justify-content-center text-center mt-1 mb-1">      
	<div class="d-flex align-items-center justify-content-center">
		<span class="text-center fs-6 mx-1"> 현장명 : <?= $outworkplace ?> </span>
		<span class="text-dark text-center fs-6 ms-4 me-1" > 가이드레일  모델 : </span>							                           
		<span class="text-danger text-center fs-6 ms-1 me-4 " > <?= $prodCode ?> </span>							                           
		<span class="text-center fs-6 "> 형태 : <span class='text-primary'> <?=$selected_check_type ?> </span>	</span>	
	</div>
</div>

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

// 혼합형인지 확인
$isMixedType = strpos($railtype, '혼합형') !== false;

// 혼합형일 경우 두 번 반복하면서 각각 벽면형과 측면형으로 설정
$typesToProcess = $isMixedType ? ['벽면형', '측면형'] : [$check_type];

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

// 혼합형일 경우는 2개를 순회한다.
foreach ($typesToProcess as $currentType) {
	if($isMixedType) {  // 혼합형일때는 분류해준다.
		if ($currentType === '벽면형') {
			$rail_length = $rail_length1;
			$rail_width = $rail_width1;
		} elseif ($currentType === '측면형') {
			$rail_length = $rail_length2;
			$rail_width = $rail_width2;
		}
	}
	
include $_SERVER['DOCUMENT_ROOT'] . "/guiderail/fun_guiderail.php" ;
$productData = getProductData($model_name, $finishing_type, $rail_length, $rail_width, $check_type);

?>

<div class="row">
	<div class="d-flex justify-content-center">
    <table class="table">
		<thead class="table-secondary">
			<tr style="margin:0; padding:0px;">
				<th class="w100px">번호</th>                
				<th class="w100px">재질</th>                
				<th class="text-center" >절곡치수</th>
				<th class="text-start w140px"> &nbsp;&nbsp;길이 &nbsp;&nbsp; 수량 &nbsp;&nbsp; 면적 </th>
			</tr>
		</thead>
<tbody >

<?php
foreach ($productData as $productIndex => $product) 
{ 		
   $length_data = [
		['length' => 2438, 'sum' => 0],
		['length' => 3000, 'sum' => 0],
		['length' => 3500, 'sum' => 0],
		['length' => 4000, 'sum' => 0],
		['length' => 4300, 'sum' => 0]
	];

		foreach ($eList as $item) {
			$railvalidLength = floatval($item['col23']); // 셔터의 유효 길이
			$railType = trim($item['col6']); // 벽부형, 측면형, 혼합형 여부 판단

			// 혼합형일 경우 1개씩 계산, 나머지는 2개씩 계산
			for ($i = 0; $i < count($length_data); $i++) {
				$length = $length_data[$i]['length'];
				if ($railvalidLength <= $length) {
					$length_data[$i]['sum'] += ($railType == '혼합형(120*70)(120*120)') ? 1 : 2;
					break;
				}
			}
		}
		// 벽면형과 측면형을 혼합형일 때는 두 개씩, 나머지는 하나씩 출력
		$wall_rows = [];
		$side_rows = [];

     if($screenorslat == 'screen') {
		foreach ($length_data as $row) {
			if ($row['sum'] > 0) {
				if ($railType == '혼합형(120*70)(120*120)') {
					$wall_rows[] = [
						'length' => $row['length'],
						'sum' => $row['sum']
					];
					$side_rows[] = [
						'length' => $row['length'],
						'sum' => $row['sum']
					];
				} elseif ($railType == '벽면형(120*70)') {
					$wall_rows[] = [
						'length' => $row['length'],
						'sum' => $row['sum']
					];
				} elseif ($railType == '측면형(120*120)') {
					$side_rows[] = [
						'length' => $row['length'],
						'sum' => $row['sum']
					];
				}
			}
		}		
	 }
	 else {   // slat인 경우
			foreach ($length_data as $row) {
				if ($row['sum'] > 0) {
					if ($railType == '혼합형(130*75)(130*125)') {
						$wall_rows[] = [
							'length' => $row['length'],
							'sum' => $row['sum']
						];
						$side_rows[] = [
							'length' => $row['length'],
							'sum' => $row['sum']
						];
					} elseif ($railType == '벽면형(130*75)') {
						$wall_rows[] = [
							'length' => $row['length'],
							'sum' => $row['sum']
						];
					} elseif ($railType == '측면형(135*125)') {
						$side_rows[] = [
							'length' => $row['length'],
							'sum' => $row['sum']
						];
					}
				}
			}	
		 }

		// 합계 행
		echo '<tr>';
		echo '<td rowspan="2" >' . $product['label'] . '</td>';        		
		echo '<td rowspan="2" >' . $product['material'] . ' </td>';
		echo '<td class="input-container" >';
		$lastSum = 0;
		// 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>';	
			$lastSum = $sum;
			}			
		echo '</td>';										
		echo '<td rowspan="2" >' ;  		
			echo '<table class="table table-bordered" style="width:120px;">';
				echo '<tbody>';   		
				foreach ($length_data as $row) {
				  if($row['sum']>0) {			  
					$length =  $row['length'];
					echo '<tr>';
					$surang = $row['sum'];			
					echo '<td class="text-center w40px">' . $length . '</td>';
					$area =  intval($length) * $surang * $lastSum / 1000000 ;
					echo '<td class="text-center w30px">' . $surang . '</td>';						
					echo '<td class="text-center w40px"> '. number_format($area,2) . ' </td>';
					echo '</tr>';					
				  }  
				}			
				echo '</tbody>';
			echo '</table>';		
		echo '</td>';	
		echo '</tr>';

        // A각 표시 행
        echo '<tr>';        
        echo '<td class="input-container" >';
        foreach ($product['aAngles'] as $angle) {
            echo '<span class="tcell" >' . ($angle ? 'A"' : '&nbsp;') . '</span>';
        }
		echo '</td>';		
		echo '</tr>';
}
?>
	</tbody>	  
    </table>
	</div>					   
</div>

<?php } ?>

<!-- 셔터박스 -->
<?php
// 스크린과 철재스라트 데이터를 통합하여 처리
$productData = [];
$shutterData = [];

foreach ($eList as $item) {
        if ($screenorslat === 'screen') {
            // 스크린 데이터
			$finMaterial = $item['col7'] ; // SUS마감/EGI마감
            $boxSize = $item['col36'] === 'custom' ? $item['col36_custom'] : $item['col36'];
            $frontBottom = $item['col36_frontbottom'];
            $railWidth = $item['col36_railwidth'];
            $exitDirection = $item['col36_boxdirection'];
            $boxtopcover_sum = $item['col44'];
            $sideFinSu = $item['col46'];
			$screenorslat = 'screen';			
            $boxLengths = [
                ['length' => '1219', 'quantity' => intval($item['col38'])],
                ['length' => '2438', 'quantity' => intval($item['col39'])],
                ['length' => '3000', 'quantity' => intval($item['col40'])],
                ['length' => '3500', 'quantity' => intval($item['col41'])],
                ['length' => '4000', 'quantity' => intval($item['col42'])],
                ['length' => '4150', 'quantity' => intval($item['col43'])],
            ];
        } elseif ($screenorslat === 'slat') {
            // 철재스라트 데이터
			$finMaterial = $item['col7']; // SUS마감/EGI마감
            $boxSize = $item['col37'] === 'custom' ? $item['col37_custom'] : $item['col37'];
            $frontBottom = $item['col37_frontbottom'];
            $railWidth = $item['col37_railwidth'];
            $exitDirection = $item['col37_boxdirection'];
            $boxtopcover_sum = $item['col45'];
            $sideFinSu = $item['col47'];			
            $screenorslat = 'slat';
            $boxLengths = [
                ['length' => '1219', 'quantity' => intval($item['col39'])],
                ['length' => '2438', 'quantity' => intval($item['col40'])],
                ['length' => '3000', 'quantity' => intval($item['col41'])],
                ['length' => '3500', 'quantity' => intval($item['col42'])],
                ['length' => '4000', 'quantity' => intval($item['col43'])],
                ['length' => '4150', 'quantity' => intval($item['col44'])],
            ];
        }

        // 동일한 형태의 셔터박스를 그룹화
        $key = "{$boxSize}|{$frontBottom}|{$railWidth}|{$exitDirection}";
        if (!isset($shutterData[$key])) {
            $shutterData[$key] = [
                'boxSize' => $boxSize,
                'frontBottom' => $frontBottom,
                'railWidth' => $railWidth,
                'exitDirection' => $exitDirection,
				'boxtopcover_sum' => $boxtopcover_sum,
				'sideFinSu' => $sideFinSu,
                'count' => 0,
                'type' => $screenorslat,
                'screenorslat' => $screenorslat,
                // 'boxLengths' => array_fill(0, count($boxLengths), 0), // 길이별 누적 수량
                'boxsum' => array_fill(0, count($boxLengths), 0), // 길이별 누적 수량
                'boxLengths' => $boxLengths , 
            ];
        }

        // 그룹화된 셔터박스 정보 업데이트
        $shutterData[$key]['count']++;
        foreach ($boxLengths as $index => $lengthData) {
            $shutterData[$key]['boxsum'][$index] += $lengthData['quantity'];
        }
}

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

// 셔터박스 데이터를 화면에 표시
?>

<?php foreach ($shutterData as $key => $shutter): ?>
    <?php
    // 셔터박스 기본 정보 추출
    $boxSize = $shutter['boxSize'];
    list($boxWidth, $boxHeight) = explode('*', $boxSize);
    $frontBottom = $shutter['frontBottom'];
    $railWidth = $shutter['railWidth'];
    $exitDirection = $shutter['exitDirection'];
	$boxtopcover_sum = $shutter['boxtopcover_sum'];
	$sideFinSu = $shutter['sideFinSu'];
    ?>
    <div class="row justify-content-center text-center mt-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">
                                    셔터박스 &nbsp; (점검구방향: <?= $exitDirection; ?>) &nbsp;&nbsp;
                                </span>
                                <span class="text-center fs-6 ms-1 me-1">
                                    전면 밑: <?= $frontBottom; ?> &nbsp;&nbsp; 레일폭: <?= $railWidth; ?> &nbsp;&nbsp;&nbsp;&nbsp;
                                </span>
                                <span class="text-center fs-6 ms-1 me-1 text-primary">
                                    가로(폭) x 세로(높이)
                                </span>
                                <span class="text-danger ms-1 me-1"><?= $boxSize; ?></span>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
    </div>
		
	<?php
	// 공통인 것	
	// print '박스 width : ' . $boxWidth . ', $boxHeight '. $boxHeight;	
		
	$selected_check_typeFlat = $exitDirection . ' 점검구';		
	// 케이스 전개도 함수
	require_once($_SERVER['DOCUMENT_ROOT'] . "/shutterbox/fun_case.php");
	$productData = getCasePlate($selected_check_typeFlat, $boxWidth, $boxHeight, $railWidth, $frontBottom);	
	
// echo '<pre>';
// print_r($productData);
// echo '</pre>';	

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

<div class="row justify-content-center text-center">
	<div class="table-container">
		<table class="table">
			<thead class="table-secondary">
				<tr style="margin:0; padding:1px;">
					<th class="w100px">번호</th>                
					<th class="w100px">재질</th>                
					<th class="text-center" >절곡치수</th>
					<th class="text-start w140px"> &nbsp;&nbsp;길이 &nbsp;&nbsp; 수량 &nbsp;&nbsp; 면적 </th>
				</tr>
			</thead>
	<tbody>

	<?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" >';

		$lastSum = 0;
		// 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>';
			$lastSum =$sum; // 마지막 합을 저장
		}
		echo '</td>';
		
		$box_data = [];
		$length_data = [
			['length' => '1219', 'sum' => 0],
			['length' => '2438', 'sum' => 0],
			['length' => '3000', 'sum' => 0],
			['length' => '3500', 'sum' => 0],
			['length' => '4000', 'sum' => 0],
			['length' => '4150', 'sum' => 0],
		];

		$found = false;

			foreach ($box_data as &$box_row) {
				if ($box_row['size'] === $boxSize) {
					$box_row['sum'] += $shutter['count'];
					$found = true;
					break;
				}
			}

			if (!$found) {
				$box_data[] = [
					'size' => $boxSize,
					'sum' => $shutter['count'],
				];
			}

			// 길이와 수량 데이터 반영
			foreach ($shutter['boxsum'] as $index => $quantity) {
				if ($quantity > 0) {
					$length_data[$index]['sum'] += $quantity;
				}
			}
		
		$box_rowspan = array_filter($box_data, function ($row) {
			return $row['sum'] > 0;
		});


		$length_rowspan = count(array_filter($length_data, function($length) {
			return $length['sum'] > 0;
		}));	
			
		echo '<td rowspan="2" >' ;  
		echo '<div class="d-flex justify-content-start align-items-top">';
		echo '<table class="table table-bordered" style="width:130px;">';
		echo '<tbody>';    
				
		if (!strpos($product['label'], '마구리(가로)') &&  !strpos($product['label'], '마구리(세로)') && !strpos($product['label'], '상부덮개' )) {
			foreach ($length_data as $row) {
				  if($row['sum']>0) {
					  
					$length =  $row['length'];
					echo '<tr>';
					if (strpos($product['label'], '마구리(가로)') ) {
						$surang = $sideFinSu;
						$length = $boxHeight + 104;
					}
					else if (strpos($product['label'], '마구리(세로)') ) {
						$surang = $sideFinSu;
						$length = $boxWidth + 104;
					}
					else if (strpos($product['label'], '상부덮개') !== false) {
						$surang = $boxtopcover_sum; 
					}
					else if( $selected_check_typeFlat === '양쪽 점검구' and strpos($product['label'], '후면 코너부') !== false ) {
						$surang = $row['sum']*2;
					}
					else {
						$surang = $row['sum'];
					}			
					
					echo '<td class="text-center w40px" style="padding:0;" >' . $length . '</td>';

					$area =  intval($length) * $lastSum / 1000000 ;
					echo '<td class="text-center w30px"  style="padding:0;">' . $surang . '</td>';						
					echo '<td class="text-center w40px "  style="padding:0;"> '. number_format($area,2) . ' </td>';
					echo '</tr>';					
				  }  
				}
			}
		else if ( strpos($product['label'], '마구리(가로)') ||  strpos($product['label'], '마구리(세로)') ) {		
					echo '<tr>';
					if (strpos($product['label'], '마구리(가로)') ) {
						$surang = $sideFinSu;
						$length = $boxHeight + 104;
					}
					else if (strpos($product['label'], '마구리(세로)') ) {
						$surang = $sideFinSu;
						$length = $boxWidth + 104;
					}				
					echo '<td class="text-center w40px" style="padding:0;" >' . $length . '</td>';
					$area =  intval($length) * $lastSum / 1000000 * $surang;
					echo '<td class="text-center w30px"  style="padding:0;">' . $surang . '</td>';						
					echo '<td class="text-center w40px "  style="padding:0;"> '. number_format($area,2) . ' </td>';
					echo '</tr>';					
			  } 
			else if (strpos($product['label'], '상부덮개') ) {		
					echo '<tr>';				
					$surang =$boxtopcover_sum; 
					echo '<td class="text-center w40px" style="padding:0;" > 1219 </td>';
					$area =  1219 * $lastSum / 1000000 * $surang;
					echo '<td class="text-center w30px"  style="padding:0;">' . $surang . '</td>';						
					echo '<td class="text-center w40px "  style="padding:0;"> '. number_format($area,2) . ' </td>';
					echo '</tr>';					
				  }  		
			echo '</tbody>';
			echo '</table>';
			echo '</div>';
			echo '</td>';	;
			echo '</tr>';

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

<?php endforeach; ?>










	<!-- 하장바 -->
	<?PHP	
		try {
			$sql = "SELECT * FROM {$DB}.bottombar WHERE model_name=?";
			$stmh = $pdo->prepare($sql);        
			$stmh->bindValue(1, $prodCode, PDO::PARAM_STR);         // prodCode와 일치하는 값
			$stmh->execute();
			$row = $stmh->fetch(PDO::FETCH_ASSOC);

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

	?>

	<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">  하장바세트 </span> 
									<span class="text-center fs-6 ms-1 me-1 text-primary"> 폭: </span> 
									<span class="text-primary ms-1 me-1"><?=$rail_length?></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"><?=$railWidth?></span>
								</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;
	$railWidth = isset($row['railWidth']) ? $row['railWidth'] : 0;
	$model_name = $prodCode;
	$check_type = isset($row['check_type']) ? $row['check_type'] : 0;

	// 함수 호출
	require_once($_SERVER['DOCUMENT_ROOT'] . "/bottombar/fun_bottombar.php");
	$productData = getBottombarData($model_name, $finishing_type, $rail_length, $rail_width);

	   // 하단 마감재, 하단 보강엘바, 하단 보강평철, 하단 무게평철의 데이터를 저장할 배열
		$item_data = [
			'하단마감재' => [
				'size' => '(60*40)',
				'length_3000' => 0,
				'length_4000' => 0
			],
			'하단보강엘바' => [
				'size' => '(60*17)',
				'length_3000' => 0,
				'length_4000' => 0
			],
			'하단보강평철' => [
				'size' => '',
				'length_3000' => 0,
				'length_4000' => 0
			]
		];

		// 데이터를 누적하여 합산
		foreach ($eList as $item) {

		}
		
		foreach ($eList as $item) {
			if ($screenorslat === 'screen') {
				// 스크린 데이터
				$item_data['하단마감재']['length_3000'] += intval($item['col49']);
				$item_data['하단마감재']['length_4000'] += intval($item['col50']);
				$item_data['하단보강엘바']['length_3000'] += intval($item['col52']);
				$item_data['하단보강엘바']['length_4000'] += intval($item['col53']);
				$item_data['하단보강평철']['length_3000'] += intval($item['col55']);
				$item_data['하단보강평철']['length_4000'] += intval($item['col56']);
			} elseif ($screenorslat === 'slat') {
				// 철재스라트 데이터
				$item_data['하단마감재']['length_3000'] += intval($item['col50']);
				$item_data['하단마감재']['length_4000'] += intval($item['col51']);				
			}
		}		
		

	?>

	<div class="table-container">
		<table class="table">
			<thead class="table-secondary">
				<tr style="margin:0; padding:1px;">
					<th class="w100px">번호</th>                
					<th class="w100px">재질</th>                
					<th class="text-center" >절곡치수</th>
					<th class="text-start w140px"> &nbsp;&nbsp;길이 &nbsp;&nbsp; 수량 &nbsp;&nbsp; 면적 </th>
				</tr>
			</thead>
	<tbody >
			<tbody id="tableBody">
				<?php 
				foreach ($productData as $productIndex => $product): 
					// 합계 행
					echo '<tr>';
					echo '<td rowspan="2">' . $product['label'] . '</td>';        		
					echo '<td rowspan="2">' . $product['material'] . '</td>';
					echo '<td class="input-container">';
					
					// sums와 colors를 함께 사용하여 배경색을 설정
					$lastSum = 0;
					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>';
						$lastSum = $sum;
					}
					echo '</td>';
					
					echo '<td rowspan="2">';  
					echo '<div class="d-flex justify-content-start align-items-top">';
					echo '<table class="table table-bordered" style="width:120px;">';
					echo '<tbody>';

					// 현재 제품에 해당하는 길이와 수량을 출력 (예: 하장바는 하단 마감재 데이터만 출력)
					$current_item_data = [];
					switch ($product['label']) {
						case '1번(하장바)':
							$current_item_data = $item_data['하단마감재'];
							break;
						case '2번(L-바)':
							$current_item_data = $item_data['하단보강엘바'];
							break;
						case '3번(평철)':
							$current_item_data = $item_data['하단보강평철'];
							break;
						// 추가적인 품목이 있다면 여기에 케이스를 추가
					}

					// 해당 제품의 길이별 데이터 출력
					if (!empty($current_item_data)) {
						if ($current_item_data['length_4000'] > 0) {
							echo '<tr>';
							echo '<td class="text-center w40px"  style="padding:0;"> 4000 </td>';
							echo '<td class="text-center w30px"  style="padding:0;">' . $current_item_data['length_4000'] . '</td>';
							$area_4000 = $current_item_data['length_4000'] * 4000 * $lastSum / 1000000;
							echo '<td class="text-center w40px"  style="padding:0;">' . number_format($area_4000, 2) . '</td>';
							echo '</tr>';   
						}
						if ($current_item_data['length_3000'] > 0) {
							echo '<tr>';
							echo '<td class="text-center w40px" style="padding:0;">  3000 </td>';
							echo '<td class="text-center w30px"  style="padding:0;">'  . $current_item_data['length_3000'] . '</td>';
							$area_3000 = $current_item_data['length_3000'] * 4000 * $lastSum / 1000000;
							echo '<td class="text-center w40px" style="padding:0;">'  . number_format($area_3000, 2) . '</td>';
							echo '</tr>';
						}
					}
					
					echo '</tbody>';
					echo '</table>';
					echo '</div>';
					echo '</td>';
					echo '</tr>';

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

	<!-- 연기차단재 -->
		
	<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">  연기차단재 (레일용, 셔터박스용) </span> 								
								</div>
							</td>
						</tr>                           
					</tbody>
				</table>
			</div>
	</div>	

	<!-- 연기 차단재 -->
	<div class="row m-1 mt-3">
	<?php
		$smoke_data = [
			['length' => 2438, 'sum' => 0],
			['length' => 3000, 'sum' => 0],
			['length' => 3500, 'sum' => 0],
			['length' => 4000, 'sum' => 0],
			['length' => 4300, 'sum' => 0]
		];

		foreach ($eList as $item) {
			if ($screenorslat === 'screen') {
				// 스크린 데이터
				$quantities = [
					floatval($item['col31']), // 2438 크기 수량
					floatval($item['col32']), // 3000 크기 수량
					floatval($item['col33']), // 3500 크기 수량
					floatval($item['col34']), // 4000 크기 수량
					floatval($item['col35'])  // 4300 크기 수량
				];
				
				// 각 크기에 맞는 수량을 smoke_data에 추가
				for ($i = 0; $i < count($smoke_data); $i++) {
					$smoke_data[$i]['sum'] += $quantities[$i];
				}
			} elseif ($screenorslat === 'slat') {
				// 철재스라트 데이터
				$quantities = [
					floatval($item['col32']), 
					floatval($item['col33']), 
					floatval($item['col34']), 
					floatval($item['col35']), 
					floatval($item['col36'])  
				];
				
				// 각 크기에 맞는 수량을 smoke_data에 추가
				for ($i = 0; $i < count($smoke_data); $i++) {
					$smoke_data[$i]['sum'] += $quantities[$i];
				}
			}
		}


		
		// 연기차단재 데이터가 있는 경우만 출력
		$smoke_rows = [];
		foreach ($smoke_data as $row) {
			if ($row['sum'] > 0) {
				$smoke_rows[] = [
					'length' => $row['length'],
					'sum' => $row['sum']
				];
			}
		}
		$smoke_rowspan = count($smoke_rows);   
		
	   // W80 기준 숫자 찾기
	   
		$smokeban80 = 0;
		foreach ($eList as $item) {
			if ($screenorslat === 'screen') {
				// 스크린 데이터
				$smokeban80 +=  floatval($item['col47']);
			} elseif ($screenorslat === 'slat') {
				// 철재스라트 데이터
				$smokeban80 +=  floatval($item['col48']);
			}
		}	   
					
		echo '<div class="col-sm-12">';
		echo '<div class="d-flex justify-content-start">';
		echo '<table class="table" style="border-collapse: collapse; width:70%;">';
		echo '<tbody>';
		echo '<tr>';
		echo '<td class="text-center lightgray">세부품명</td>';
		echo '<td class="text-center lightgray w200px;">재질</td>';
		echo '<td class="text-start lightgray">  &nbsp;&nbsp;&nbsp;&nbsp; 길이&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;  수량   </td>';
		echo '</tr>';
		echo '<tr>';
		echo '<td class="text-center text-dark ">레일용 [W50]</td>';
		echo '<td class="text-center text-dark">EGI 0.8T 화이바 글라스 코팅직물 </td>';
		echo '<td class="text-center w120px">';        
		echo '<table class="table" style="border-collapse: collapse;" style="width:80px;">';
		echo '<tbody>'; 
		$side_sum = 0;
		foreach ($smoke_data as $row) {
			  if($row['sum']>0) {
				echo '<tr>';
				echo '<td class="text-center w40px">' . $row['length'] . '</td>';
				echo '<td class="text-center w30px">' . $row['sum'] . '</td>';		
				echo '</tr>';
				$side_sum += $row['sum'];
			}  }
		echo '</tbody>';
		echo '</table>';
		echo '</div>';
		echo '</td>';
		echo '</tr>';
		echo '<tr>';
		echo '<td class="text-center text-dark"> 케이스용 [W80]  </td>';    
		echo '<td class="text-center text-dark">EGI 0.8T 화이바 글라스 코팅직물 </td>';
		echo '<td class="text-center ">';    
		echo '<div class="d-flex justify-content-start m-1">';
		echo '<table class="table" style="border-collapse: collapse;" style="width:80px;">';
		echo '<tbody>';
		echo '<tr>';
		echo '<td class="text-center w40px"> 3000</td>';
		echo '<td class="text-center w30px">' . $smokeban80 . '</td>';				
		echo '</tr>';
		echo '</tbody>';
		echo '</table>';
		echo '</td>';
		echo '</tr>';
		
		echo '</tbody>';
		echo '</table>';
		echo '</div>';
		echo '</div>';
	?>
	</div>



	</div>

<div class="d-flex align-items-center justify-content-center mb-5 mt-5">
</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>

