<?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_check_type = isset($row['check_type']) ? $row['check_type'] : '벽면형';
$selected_model_name = isset($row['model_name']) ? $row['model_name'] : '';
$selected_finishing_type = isset($row['finishing_type']) ? $row['finishing_type'] : '';

// 추가 변수들 정의
$model_UA = isset($row['model_UA']) ? $row['model_UA'] : '';
$model_name = isset($row['model_name']) ? $row['model_name'] : '';
$check_type = isset($row['check_type']) ? $row['check_type'] : '';
$finishing_type = isset($row['finishing_type']) ? $row['finishing_type'] : '';
$search_keyword = isset($row['search_keyword']) ? $row['search_keyword'] : '';

// getProductData 함수를 위해 숫자로 변환
$rail_length_num = isset($row['rail_length']) ? (int)$row['rail_length'] : 0;
$rail_width_num = isset($row['rail_width']) ? (int)$row['rail_width'] : 0;

// $model_name   = 'KSS01';
// $finishing_type  = 'SUS마감';
// $rail_length  = 100; // 예시 값
// $rail_width   = 50;  // 예시 값
// $check_type   = '벽면형'; // 또는 '측면형'

include $_SERVER['DOCUMENT_ROOT'] . "/guiderail/fun_guiderail.php" ;

$productData = getProductData($model_name, $finishing_type, $rail_length_num, $rail_width_num, $check_type);

?>

<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 type="button" class="btn btn-success btn-sm ms-5 me-2" onclick="generateData()">  <i class="bi bi-database-fill"></i> DATA생성 </button>	
							<button type="button" class="btn btn-dark btn-sm me-2" onclick="generatePDF()">  <i class="bi bi-floppy-fill"></i> PDF 저장 </button>	
							<button type="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 FlatcloseBtn">  &times; 닫기 </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  fw-bold" style="width:150px;">등록일</td>
                                    <td class="text-center w100px" >
                                        <input type="date" class="form-control  " id="registration_date" readonly name="registration_date" value="<?=$registration_date?>">
                                    </td>
                                    <td class="text-center  fw-bold" >작성자</td>
                                    <td class="text-center" style="width:100px;">
                                       <div class="d-flex">
                                            <input class="form-control " id="author" name="author" readonly value="<?=$author?>" autocomplete="off">
                                        </div>
                                    </td>                                
                                    <td class="text-center  fw-bold" >비고</td>
                                    <td colspan="3" class="text-center">
                                        <input type="text" class="form-control  text-start" id="remark" name="remark" readonly value="<?=$remark?>" autocomplete="off">
                                    </td>
                                </tr>                               
                                <tr>
                                    <td class="text-center  fw-bold" colspan="6" style="height:60px;">
										<div class="d-flex align-items-center justify-content-center">
										  <span class="text-center  ms-1 me-1"> 가이드레일 외형치수  </span> 
										  <span class="text-center  ms-1 me-1 text-primary"> 가로(너비) </span> 
										  <input type="text" class="form-control  w50px text-primary ms-1 me-1"readonly id="rail_length" name="rail_length" value="<?=$rail_length?>">
										  <span class="text-center  ms-1 me-1"> X </span> 
										  <span class="text-center  ms-1 me-1 text-danger"> 세로(폭) </span> 
										  <input type="text" class="form-control  w50px text-danger" id="rail_width"  readonly name="rail_width" value="<?=$rail_width?>">
										</div>
									</td>
                                </tr>
								<tr>
								<td class="text-center  fw-bold" colspan="6" >
									<div class="d-flex justify-content-center align-items-center">						
											제품코드  <input type='text' id="selected_model_name" name="selected_model_name" class="form-control w120px mx-1" value="<?=$selected_model_name?>">  							
											&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 형태  <input type='text' id="selected_check_type" name="selected_check_type" class="form-control w120px mx-1" value="<?=$selected_check_type?>">  								
											 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; 마감 :  <input type='text' id="selected_finishing_type" name="selected_finishing_type" class="form-control w120px mx-1" value="<?=$selected_finishing_type?>">  								
									</div>
								</td>
							</tr>
							<tr>
								<td class="text-center  fw-bold" colspan="6" >
									<div class="d-flex justify-content-center align-items-center">						
											품목검색어  <input type='text' id="search_keyword" name="search_keyword" class="form-control w200px mx-1" value="<?=$search_keyword?>">  							
									</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">
					<!-- 초기 src는 빈값으로 두고, JavaScript로 업데이트 -->
					<img id="checkImageFlat" style="width:180px;height:auto;" src="" alt="Image">
					<input type="text" class="input-overlay" id="displayFlat_rail_length" readonly style="top: 155px; left: 70px;" placeholder="레일 길이">
					<input type="text" class="input-overlay" id="displayFlat_rail_width" readonly style="top: 50px; left: 180px;" placeholder="레일폭">
				  </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  fw-bold" colspan="6" >
							<div class="d-flex align-items-center justify-content-center">
								<span class="text-center  ms-1 me-1"> (<?=$model_UA?>) (<?=$model_name?>) (<?=$check_type?>) (<?=$finishing_type?>) &nbsp;&nbsp;
                                <span class="text-center  ms-1 me-1"> 레일 가로(너비): <?=$rail_length?> &nbsp;&nbsp;  레일폭 : <?=$rail_width?> &nbsp;&nbsp;&nbsp;&nbsp; </span> 
                                <span class="text-center  ms-1 me-1"> <strong> 품목검색어 : </strong>  <?=$search_keyword?> &nbsp;&nbsp;&nbsp;&nbsp; </span> 
                            </div>
                        </td>
                    </tr>                           
                </tbody>
            </table>
        </div>
    </div>					
<div class="row justify-content-center text-center">

<?php
// getProductData 함수를 위해 숫자로 변환
$rail_length_num = isset($row['rail_length']) ? (int)$row['rail_length'] : 0;
$rail_width_num = isset($row['rail_width']) ? (int)$row['rail_width'] : 0;
$productData = getProductData($model_name, $finishing_type, $rail_length_num, $rail_width_num, $check_type);

?>

<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="7" >' . $product['label'] . '</td>';
        echo '<td rowspan="7" >' . $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['inputValues'] as $index => $value) {
            $calculatedValue = $value + $product['bendingRates'][$index];
            echo '<span class="text-center" style="width: 30px;">' . $calculatedValue . '</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) {
            $style = $color ? 'bg-dark text-white' : '';
            echo '<span class="form-control text-center readonly w30px ' . $style . '" style="width: 30px;">' . ($color ? '음영' : '&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) {
            $style = $angle ? 'bg-primary text-white' : '';
            echo '<span class="form-control text-center readonly w30px ' . $style . '" style="width: 30px;">' . ($angle ? 'A각' : '&nbsp;') . '</span>';
        }
        echo '</td>';
        echo '</tr>';
        ?>
    <?php endforeach; ?>
	</tbody>	  
    </table>
</div>	   
</div>
</div>
</div>  

<script>
// PHP 변수들을 JavaScript에서 사용할 수 있도록 변수 선언
var search_keyword = '<?php echo addslashes($search_keyword ?? ""); ?>';
var model_name = '<?php echo addslashes($model_name ?? ""); ?>';
var check_type = '<?php echo addslashes($check_type ?? ""); ?>';
var finishing_type = '<?php echo addslashes($finishing_type ?? ""); ?>';
var rail_length = '<?php echo addslashes($rail_length_num ?? ""); ?>';
var rail_width = '<?php echo addslashes($rail_width_num ?? ""); ?>';
var model_UA = '<?php echo addslashes($model_UA ?? ""); ?>';

// DATA생성 함수
function generateData() {
    if (!confirm('현재 전개도 데이터를 DB에 저장하시겠습니까?')) {
        return;
    }

    // 테이블 데이터 수집
    const tableData = collectTableData();
    
    // 서버로 데이터 전송
    saveDataToServer(tableData);
}

// 테이블 데이터 수집 함수
function collectTableData() {
    const assemblyParts = [];
    const tableBody = document.getElementById('tableBody');
    const rows = tableBody.querySelectorAll('tr');
    
    let currentPart = null;
    let partIndex = 0;
    
    // 7행씩 그룹화하여 부품 데이터 수집
    for (let i = 0; i < rows.length; i += 7) {
        if (i + 6 >= rows.length) break;
        
        const firstRow = rows[i];
        const label = firstRow.cells[0].textContent.trim();
        const material = firstRow.cells[1].textContent.trim();
        
        // 각 행에서 데이터 추출
        const inputValues = [];
        const bendingRates = [];
        const sums = [];
        const colors = [];
        const aAngles = [];
        
        // 입력값 행 (i+1)
        const inputRow = rows[i + 1];
        const inputSpans = inputRow.querySelectorAll('.input-container span');
        inputSpans.forEach(span => {
            inputValues.push(parseInt(span.textContent) || 0);
        });
        
        // 연신율 행 (i+2)
        const bendingRow = rows[i + 2];
        const bendingSpans = bendingRow.querySelectorAll('.input-container span');
        bendingSpans.forEach(span => {
            bendingRates.push(parseInt(span.textContent) || 0);
        });
        
        // 합계 행 (i+4)
        const sumRow = rows[i + 4];
        const sumSpans = sumRow.querySelectorAll('.input-container span');
        sumSpans.forEach(span => {
            sums.push(parseInt(span.textContent) || 0);
        });
        
        // 음영 행 (i+5)
        const colorRow = rows[i + 5];
        const colorSpans = colorRow.querySelectorAll('.input-container span');
        colorSpans.forEach(span => {
            colors.push(span.textContent.trim() === '음영');
        });
        
        // A각 표시 행 (i+6)
        const angleRow = rows[i + 6];
        const angleSpans = angleRow.querySelectorAll('.input-container span');
        angleSpans.forEach(span => {
            aAngles.push(span.textContent.trim() === 'A각');
        });
        
        // 부품 데이터 구성
        const part = {
            orderNumber: partIndex + 1,
            itemName: label,
            material: material,
            inputList: inputValues,
            bendingrateList: bendingRates,
            sumList: sums,
            colorList: colors,
            AList: aAngles
        };
        
        assemblyParts.push(part);
        partIndex++;
    }
    
    return assemblyParts;
}

// 서버로 데이터 전송 함수
function saveDataToServer(assemblyParts) {
    // 기본 정보 수집
    var mode = "<?php echo $mode; ?>";    
    var num = "<?php echo $num; ?>";    

    const formData = {
        mode: mode,
        selectWork : 'unfold',        
        bending_components: JSON.stringify(assemblyParts),        
        material_summary: JSON.stringify(generateMaterialSummary(assemblyParts)),
        num: num
    };
    
    // AJAX 요청
    $.ajax({
        url: '/guiderail/process.php',
        type: 'POST',
        data: formData,
        dataType: 'json',
        success: function(response) {
            if (response.error) {
                alert('저장 중 오류가 발생했습니다: ' + response.error);
            } else {
                alert('데이터가 성공적으로 저장되었습니다. (번호: ' + response.num + ')');
                // 모달 닫기
                $('.closeBtn').click();
            }
        },
        error: function(xhr, status, error) {
            alert('저장 중 오류가 발생했습니다: ' + error);
            console.error('Error:', error);
        }
    });
}

// 자재 요약 생성 함수
function generateMaterialSummary(assemblyParts) {
    const materialSummary = {};
    
    assemblyParts.forEach(part => {
        const material = part.material;
        if (!materialSummary[material]) {
            materialSummary[material] = {
                material: material,
                count: 0,
                totalLength: 0
            };
        }
        
        materialSummary[material].count++;
        // 합계의 마지막 값이 총 길이로 간주
        if (part.sumList && part.sumList.length > 0) {
            materialSummary[material].totalLength += part.sumList[part.sumList.length - 1];
        }
    });
    
    return Object.values(materialSummary);
}

// 가이드레일 이미지 데이터 로드
var guiderailImages = <?php 
    $jsonFile = $_SERVER['DOCUMENT_ROOT'].'/guiderail/guiderail.json';
    if(file_exists($jsonFile)){
        echo file_get_contents($jsonFile);
    } else {
        echo '[]';
    }
?>;

// 이미지 업데이트 함수
function updateImage(model, checkType, finishing_type) {
    let imagePath = '';
    
    console.log('guiderailImages', guiderailImages);
    console.log('model', model);
    console.log('finishing_type', finishing_type);
    console.log('checkType', checkType);
    console.log('search_keyword', search_keyword);
    
    // guiderailImages 배열에서 이미지 검색 (우선순위 순서대로)
    if (Array.isArray(guiderailImages)) {
        let found = false;
        
        // 경우의 수 1: search_keyword가 있고, JSON에도 search_keyword가 있는 경우 (가장 우선)
        if(search_keyword !== ''){
            found = guiderailImages.find(function(item) {
                return item.search_keyword && item.search_keyword === search_keyword;
            });
            if (found) {
                imagePath = found.image;
            }
        }
        
        // 경우의 수 2: search_keyword로 찾지 못했거나 없는 경우, model_name + check_type + finishing_type으로 검색
        if(!found && model && checkType && finishing_type){
            found = guiderailImages.find(function(item) {
                return item.model_name && item.model_name === model && 
                        item.check_type && item.check_type === checkType && 
                        item.finishing_type && item.finishing_type === finishing_type;
            });
            if (found) {
                imagePath = found.image;
            }
        }
        
        // 경우의 수 3: model_name + check_type으로만 검색 (finishing_type 무시)
        if(!found && model && checkType){
            found = guiderailImages.find(function(item) {
                return item.model_name && item.model_name === model && 
                        item.check_type && item.check_type === checkType;
            });
            if (found) {
                imagePath = found.image;
            }
        }
        
        // 경우의 수 4: model_name만으로 검색 (check_type, finishing_type 무시)
        if(!found && model){
            found = guiderailImages.find(function(item) {
                return item.model_name && item.model_name === model;
            });
            if (found) {
                imagePath = found.image;
            }
        }
        
        // 경우의 수 5: check_type + finishing_type으로 검색 (model_name 무시)
        if(!found && checkType && finishing_type){
            found = guiderailImages.find(function(item) {
                return item.check_type && item.check_type === checkType && 
                        item.finishing_type && item.finishing_type === finishing_type;
            });
            if (found) {
                imagePath = found.image;
            }
        }
    }

    // checkImageFlat 엘리먼트가 존재하는지 확인 후 이미지 경로 적용
    if ($('#checkImageFlat').length) {
        $('#checkImageFlat').attr('src', imagePath);
    }
}

// 페이지 로드 시 이미지 업데이트
$(document).ready(function() {
    updateImage(model_name, check_type, finishing_type);
});
</script>  