<?php
// 절곡일지 fetch 파일
require_once($_SERVER['DOCUMENT_ROOT'] . "/session.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/lib/mydb.php");
$pdo = db_connect();

$item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
$Request_item_name = isset($_POST['item_name']) ? trim($_POST['item_name']) : '';
$tablename = 'instock';

$lot_type = $_POST['lot_type'];
$usesurang = $_POST['usesurang'];


        // 품목명을 매핑하는 배열
        $prodNames = [
            'R' => '가이드레일(벽면형)',
            'S' => '가이드레일(측면형)',
            'G' => '연기차단재',
            'B' => '하단마감재(스크린)',
            'T' => '하단마감재(철재)',
            'L' => 'L - Bar',
            'C' => '케이스'
        ];
		
        // 종류명을 매핑하는 배열
        $specNames = [
            'I' => '화이바원단',
            'S' => 'SUS(마감)',
            'U' => 'SUS(마감)2',
            'E' => 'EGI(마감)',
            'A' => '스크린용',
            'D' => 'D형',
            'C' => 'C형',
            'M' => '본체',
            'T' => '본체(철재)',
            'B' => '후면코너부',
            'L' => '린텔부',
            'P' => '점검구',
            'F' => '전면부'
        ];

        // 모양&길이를 매핑하는 배열
        $slengthNames = [
            '53' => 'W50 × 3000',
            '54' => 'W50 × 4000',
            '83' => 'W80 × 3000',
            '84' => 'W80 × 4000',
            '12' => '1219',  // 1219 기장 철판이 없어서 2438 적용
            '24' => '2438',
            '30' => '3000',
            '35' => '3500',
            '40' => '4000',
            '41' => '4150',
            '42' => '4200',
            '43' => '4300'
        ];	

    echo "찾는 형태: " . $lot_type . '<br>' ;
  			
	// 'SS-24' 값을 'S', 'S', '24'로 분리하여 검색 조건에 적용
	$prod_value = substr($item_name, 0, 1);  // 첫 번째 'S'는 prod
	$spec_value = substr($item_name, 1, 1);  // 두 번째 'S'는 spec
	$slength_value = substr($item_name, 3);  // '24'는 slength  
	
	// echo $prod_value . ' ' . $spec_value . ' ' . $slength_value ;	

if ($lot_type === 'product') {
    // 생산품 로트번호 조회 코드
	echo '<div class="alert alert-primary"> 생산품 : ' . $item_name . ' </div>';    
} elseif ($lot_type === 'material') {
    // 원자재 로트번호 조회 코드    
	switch ($spec_value)
	{ 
	   case 'S':
	     if ($prod_value == 'B')
			$rawitemname = "SUS1.55T";
		   else
			 $rawitemname = "SUS1.2T";
		break;
	   case 'X' or 'M' :
			$rawitemname = "EGI1.55T";
		break;
	   case 'H' :
			$rawitemname = "EGI1.15T";
		break;
	   case 'Y' :
			$rawitemname = "SUS1.2T";
		break;
	}
	echo "원자재 " . $rawitemname  . " 로트 ";	
}

if (empty($item_name)) {
    echo '<div class="alert alert-danger">품목명이 없습니다.</div>';
    exit;
}

if ($lot_type === 'product') {	
try {	

	$sql = "SELECT *  
			FROM {$DB}.lot 
			WHERE prod = :prod_value 
			  AND spec = :spec_value
			  AND slength = :slength_value
			  AND (is_deleted IS NULL OR is_deleted = '0')  
			ORDER BY reg_date DESC 
			LIMIT 12";

	// SQL 쿼리 실행 시 바인딩할 값 설정
	$stmt = $pdo->prepare($sql);
	$stmt->bindValue(':prod_value', $prod_value);
	$stmt->bindValue(':spec_value', $spec_value);
	$stmt->bindValue(':slength_value', $slength_value);
	$stmt->execute();
	$rows = $stmt->fetchAll(PDO::FETCH_ASSOC); // 여기서 'stmt' 사용


	 if (count($rows) > 0) {
		echo '<div style="max-height: 400px; overflow-y: auto;">'; // 스크롤 컨테이너 시작
		echo '<table class="table table-hover">';
		echo '<thead class="table-primary">';
		echo '<tr>';
		echo '<th class="text-center">생산로트 </th>';
		echo '<th class="text-center">등록일</th>';
		echo '<th class="text-center">품목명</th>';
		echo '<th class="text-center">종류</th>';
		echo '<th class="text-center">모양&길이</th>';
		echo '<th class="text-center">원단로트</th>';
		echo '<th class="text-center">재고</th>';
		echo '<th class="text-center">사용수량</th>';
		echo '</tr>';
		echo '</thead>';
		echo '<tbody id="lotModalBody">';

		foreach ($rows as $row) {
			$lot_number = htmlspecialchars($row['lot_number']);
			$surang = number_format((int)$row['surang']);    
			$prod = htmlspecialchars($row['prod']);
			$spec = htmlspecialchars($row['spec']);
			$slength = htmlspecialchars($row['slength']);
			$reg_date = htmlspecialchars($row['reg_date']);
			$num = htmlspecialchars($row['num']); // 추가: num 값을 가져옵니다.
			$fabric_lot = htmlspecialchars($row['fabric_lot']);

				// 품목명, 종류, 모양&길이에 대한 친절한 표시를 준비
				$prodDisplay = isset($prodNames[$prod]) ? "{$prod}({$prodNames[$prod]})" : $prod;
				$specDisplay = isset($specNames[$spec]) ? "{$spec}({$specNames[$spec]})" : $spec;
				$slengthDisplay = isset($slengthNames[$slength]) ? "{$slength}({$slengthNames[$slength]})" : $slength;

				echo '<tr>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $lot_number . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $reg_date . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $prodDisplay . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $specDisplay . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $slengthDisplay . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $fabric_lot . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $surang . '</td>';                
				echo '<td class="text-center" onclick="selectLotNumber_prod(\'' . $lot_number . '\')">' . $usesurang . '</td>';                
				echo '</tr>';    
		}
		echo '</tbody>';
		echo '</table>';
		echo '</div>'; // 스크롤 컨테이너 종료
	} else {
		echo '<div class="alert alert-warning">해당 품목명에 대한 로트 번호가 없습니다.</div>';
	}

} catch (PDOException $e) {
    echo '<div class="alert alert-danger">오류: ' . htmlspecialchars($e->getMessage()) . '</div>';
}

} 

if ($lot_type === 'material') {	

	switch (substr($item_name, 0, 1))
	{ 	 
	   case 'H' :
			$rawitemname = "EGI1.15T";
		break;
	   case 'X' :
			$rawitemname = "EGI1.55T";
		break;
	   case 'Y' :
			$rawitemname = "SUS1.2T";
		break;
	}

	try { 
		// 로트 번호를 품목명에 따라 조회
		$sql = "SELECT num, item_name, lot_no, received_qty, supplier, inspection_date, specification 
				FROM {$DB}.instock 
				WHERE item_name LIKE :item_name AND is_deleted IS NULL AND lotDone IS NULL  
				ORDER BY inspection_date DESC, lot_no ASC ";

		$stmh = $pdo->prepare($sql);
		$stmh->bindValue(':item_name', "%$rawitemname%", PDO::PARAM_STR);
		$stmh->execute();
		$rows = $stmh->fetchAll(PDO::FETCH_ASSOC);
		
		// echo '<pre>';
		// print_r($rows);
		// echo '</pre>';
			
		$slength = substr($Request_item_name, 3);  // '24'는 slength  
		if($slength == '12')
				$slength = '24';		
		
		echo '<div class="alert alert-primary"> 검색어 item_name : ' . $item_name . ' ' . $rawitemname . ', 길이 : ' . $slength . ' </div>';

	 if (count($rows) > 0) {
		echo '<div style="max-height: 400px; overflow-y: auto;">'; // 스크롤 컨테이너 시작
		echo '<table class="table table-hover">';
		echo '<thead class="table-primary">';
		echo '<tr>';
		echo '<th class="text-center">로트 번호</th>';
		echo '<th class="text-center">품명 </th>';
		echo '<th class="text-center">규격</th>';
		echo '<th class="text-center">수량(EA)<br> 길이(M)</th>';
		echo '<th class="text-center">납품업체</th>';
		echo '<th class="text-center">검사일</th>';
		echo '<th class="text-center">로트소진</th>';
		echo '</tr>';
		echo '</thead>';
		echo '<tbody id="lotModalBody">';

  foreach ($rows as $row) {
    $lot_no = htmlspecialchars($row['lot_no']);
    $received_qty = number_format((int)$row['received_qty']);
    $supplier = htmlspecialchars($row['supplier']);
    $inspection_date = htmlspecialchars($row['inspection_date']);
    $num = htmlspecialchars($row['num']); 
    $item_name = htmlspecialchars($row['item_name']); 
    $specification = htmlspecialchars($row['specification']); 
	$parts = explode('*', $specification);
	$beforeAsterisk = isset($parts[0]) ? $parts[0] : ''; // '*' 기준 앞으로
	$afterAsterisk = isset($parts[1]) ? $parts[1] : ''; // '*' 4000, 3500 이런식으로 뒤의 값 추출  
	if($afterAsterisk =='1219')
		$afterAsterisk ='2438' ;    // 철판 1219 기장은 없음
	
	$slengthDisplay = isset($slengthNames[$slength]) ? "{$slengthNames[$slength]}" : $slength;		
	// echo 'beforeAsterisk : ' . intval($beforeAsterisk) . 'afterAsterisk : ' . intval($afterAsterisk) . ' , slengthDisplay :  ' . intval($slengthDisplay) . '<br>';
	
    if ($item_name == '내화실') {
        echo '<tr>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $lot_no . '</td>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $item_name . '</td>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $specification . '</td>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $received_qty . '</td>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $supplier . '</td>';
        echo '<td class="text-center" onclick="selectLotNumber_wire(\'' . $lot_no . '\')">' . $inspection_date . '</td>';
        // '소진' 버튼 추가
        echo '<td class="text-center">';
        echo '<button  type="button" class="btn btn-sm btn-danger lot-done-wire-btn " data-num="' . $num . '" data-tablename="' . $tablename . '">소진</button>';
        echo '</td>';
        echo '</tr>';
    } else  {		
		    if (intval($slengthDisplay) === intval($afterAsterisk) || strpos($slengthDisplay, '*') !== false) { // *3000  뒷 3000이 같은 코드만 or 하부베이스 120*120 형태로 불러오기 
				echo '<tr>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')"> ' . $lot_no . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')"> ' . $item_name . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')">' . $specification . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')"> ' . $received_qty . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')"> ' . $supplier . '</td>';
				echo '<td class="text-center" onclick="selectLotNumber(\'' . $lot_no . '\')"> ' . $inspection_date . '</td>';
				// '소진' 버튼 추가
				echo '<td class="text-center">';
				echo '<button type="button" class="btn btn-sm btn-danger lot-done-btn" data-num="' . $num . '" data-tablename="' . $tablename . '"   data-rawitemname="' . $rawitemname . '"  data-lottype="' . $lot_type . '"   >소진</button>';
				echo '</td>';
				echo '</tr>';
			}
	} 
	
	}

    echo '</tbody>';
    echo '</table>';
    echo '</div>'; // 스크롤 컨테이너 종료
} else {
    echo '<div class="alert alert-warning">해당 품목명에 대한 로트 번호가 없습니다. item_name : ' . $item_name . '</div>';
}

} catch (PDOException $e) {
    echo '<div class="alert alert-danger">오류: ' . htmlspecialchars($e->getMessage()) . '</div>';
}

}

?>
