<!-- 모달창 -->
<div class="modal fade" id="supplierModal" tabindex="-1" aria-labelledby="supplierModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="supplierModalLabel">새 납품업체 추가</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <label for="newSupplierInput" class="form-label">납품업체 이름:</label>
                <input type="text" id="newSupplierInput" class="form-control">
            </div>
            <div class="modal-footer">
                <button type="button" id="addSupplierBtn" class="btn btn-dark">추가</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
            </div>
        </div>
    </div>
</div>

<!-- 제조사 모달창 -->
<div class="modal fade" id="manufacturerModal" tabindex="-1" aria-labelledby="manufacturerModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="manufacturerModalLabel">새 제조사 추가</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <label for="newManufacturerInput" class="form-label">제조사 이름:</label>
                <input type="text" id="newManufacturerInput" class="form-control">
            </div>
            <div class="modal-footer">
                <button type="button" id="addManufacturerBtn" class="btn btn-dark">추가</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
            </div>
        </div>
    </div>
</div>

<!-- 단위 모달창 -->
<div class="modal fade" id="unitModal" tabindex="-1" aria-labelledby="unitModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="unitModalLabel">새 단위 추가</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <label for="newUnitInput" class="form-label">단위 이름:</label>
                <input type="text" id="newUnitInput" class="form-control">
            </div>
            <div class="modal-footer">
                <button type="button" id="addUnitBtn" class="btn btn-dark">추가</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">취소</button>
            </div>
        </div>
    </div>
</div>

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

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

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

// `instock` 테이블에서 `item_name` 컬럼 값 가져오기
$sql = "SELECT item_name FROM  {$DB}.{$tablename} WHERE is_deleted IS NULL";
try {
    $stmh = $pdo->query($sql);
    $itemNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // item_name 컬럼의 값을 배열로 저장

    // 공백 및 엔터, 탭 제거
    $cleanedItemNames = array_map(function($name) {
        // 모든 공백, 탭, 줄 바꿈 제거
        return preg_replace('/\s+/', '', $name);
    }, $itemNames);

	// 중복 제거
	$uniqueItemNames = array_unique($cleanedItemNames);

	// 공백으로만 구성된 요소 제거
	$uniqueItemNames = array_filter($uniqueItemNames, function($name) {
		return trim($name) !== '';
	});
	$uniqueItemNames = array_filter($uniqueItemNames, function($name) {
		return trim($name) !== '　'; // 전각문자 일반 공백: ' ' 전각 공백: '　' (유니코드 U+3000) 이 차이로 오류가 난것임
	});

	// 한글, 영문 오름차순 정렬
	usort($uniqueItemNames, function($a, $b) {
		return strcoll($a, $b); // strcoll을 사용해 로케일에 따른 오름차순 정렬
	});
	
	// 결과 출력 (예: 배열 확인용)
   // print_r($uniqueItemNames);
   
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// `instock` 테이블에서 `supplier` 컬럼 값 가져오기
$sql = "SELECT supplier FROM {$DB}.{$tablename} WHERE is_deleted IS NULL";
try {
    $stmh = $pdo->query($sql);
    $supplierNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // supplier 컬럼의 값을 배열로 저장

    // 공백 및 엔터, 탭 제거
    $cleanedSupplierNames = array_map(function($name) {
        return preg_replace('/\s+/', '', $name);
    }, $supplierNames);	

    // 중복 제거
    $uniqueSupplierNames = array_unique($cleanedSupplierNames);

    // 공백으로만 구성된 요소 제거
    $uniqueSupplierNames = array_filter($uniqueSupplierNames, function($name) {
        return trim($name) !== '' && trim($name) !== '　';
    });

    // 한글, 영문 오름차순 정렬
    usort($uniqueSupplierNames, function($a, $b) {
        return strcoll($a, $b); // 로케일에 따른 오름차순 정렬
    });
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// `instock` 테이블에서 `manufacturer` 컬럼 값 가져오기
$sql = "SELECT manufacturer FROM {$DB}.{$tablename} WHERE is_deleted IS NULL";
try {
    $stmh = $pdo->query($sql);
    $manufacturerNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // manufacturer 컬럼의 값을 배열로 저장

    // 공백 및 엔터, 탭 제거
    $cleanedManufacturerNames = array_map(function($name) {
        return preg_replace('/\s+/', '', $name); // 공백 제거
    }, $manufacturerNames);

    // 중복 제거
    $uniqueManufacturerNames = array_unique($cleanedManufacturerNames);

    // 공백으로만 구성된 요소 제거
    $uniqueManufacturerNames = array_filter($uniqueManufacturerNames, function($name) {
        return trim($name) !== '' && trim($name) !== '　'; // 전각 공백도 제거
    });

    // 한글, 영문 오름차순 정렬
    usort($uniqueManufacturerNames, function($a, $b) {
        return strcoll($a, $b); // 로케일에 따른 정렬
    });
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

// `instock` 테이블에서 `unit` 컬럼 값 가져오기
$sql = "SELECT unit FROM {$DB}.{$tablename} WHERE is_deleted IS NULL";
try {
    $stmh = $pdo->query($sql);
    $unitNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // unit 컬럼의 값을 배열로 저장

    // 공백 및 엔터, 탭 제거
    $cleanedUnitNames = array_map(function($name) {
        return preg_replace('/\s+/', '', $name); // 공백 제거
    }, $unitNames);

    // 중복 제거
    $uniqueUnitNames = array_unique($cleanedUnitNames);

    // 공백으로만 구성된 요소 제거
    $uniqueUnitNames = array_filter($uniqueUnitNames, function($name) {
        return trim($name) !== '' && trim($name) !== '　'; // 전각 공백도 제거
    });
	
    // 한글, 영문 오름차순 정렬
    usort($uniqueUnitNames, function($a, $b) {
        return strcoll($a, $b); // 로케일에 따른 정렬
    });
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

if ($mode === 'update' && $num) {
    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;
    }
} else if ($mode === 'copy' && $num) {
    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';
		$num = '';   //copy일때는 $num 초기화
    } catch (PDOException $Exception) {
        echo "오류: ".$Exception->getMessage();
        exit;
    }
} else {
    include '_request.php';
    $mode = 'insert';    
    $inspection_date = date('Y-m-d');
	// $lot_no = date('ymd') . '-'; // 현재 날짜를 "년도(2자리)+월+일" 형식으로 생성 후 '-' 추가
	$currentDate = date('ymd'); // 예: 240926

	$filepath = $_SERVER['DOCUMENT_ROOT'] . '/instock/lotnum.txt';

	// 파일이 존재하지 않으면 새로 생성
	if (!file_exists($filepath)) {
		$lot_no = $currentDate . '-01';
	} else {
		// 파일에서 이전 로트번호 읽기
		$lastLotNumber = file_get_contents($filepath);
		list($date, $number) = explode('-', $lastLotNumber);

		// 날짜가 같으면 번호를 증가, 다르면 01로 초기화
		if ($date === $currentDate) {
			$newNumber = str_pad((int)$number + 1, 2, '0', STR_PAD_LEFT);
			$lot_no = $currentDate . '-' . $newNumber;
		} else {
			$lot_no = $currentDate . '-01';
		}
	}
	// 로트번호 갱신 서버저장은 저장버튼 클릭시 시작
	// file_put_contents($filepath, $lot_no);
}

// `instock` 테이블에서 `specification` 컬럼 값 가져오기
$sql = "SELECT specification FROM {$DB}.{$tablename} WHERE item_name = ? AND is_deleted IS NULL";
try {
	$stmh = $pdo->prepare($sql);
	$stmh->execute([$item_name]);
    $specificationNames = $stmh->fetchAll(PDO::FETCH_COLUMN, 0); // specification 컬럼의 값을 배열로 저장

    // 공백 및 엔터, 탭 제거
    $cleanedspecificationNames = array_map(function($name) {
        return preg_replace('/\s+/', '', $name); // 공백 제거
    }, $specificationNames);
	
	// $cleanedspecificationNames = array_map(function ($spec) {
		// return str_replace(["\r\n", "\r", "\n"], '', $spec);
	// }, $cleanedspecificationNames);	

    // 중복 제거
    $uniquespecificationNames = array_unique($cleanedspecificationNames);

    // 공백으로만 구성된 요소 제거
    $uniquespecificationNames = array_filter($uniquespecificationNames, function($name) {
        return trim($name) !== '' && trim($name) !== '　'; // 전각 공백도 제거
    });

    // 한글, 영문 오름차순 정렬
    usort($uniquespecificationNames, function($a, $b) {
        return strcoll($a, $b); // 로케일에 따른 정렬
    });
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}

$title_message = ($mode === 'update') ? '수입검사 수정' : '수입검사 신규 등록';
$specification_clean = preg_replace('/(\s+|<br>|<br\/>|<br \/>|\r\n|\r|\n)/', ' ', $specification); 
$remarks_clean = preg_replace('/(\s+|<br>|<br\/>|<br \/>|\r\n|\r|\n)/', ' ', $remarks); 
$item_name_clean = preg_replace('/(\s+|<br>|<br\/>|<br \/>|\r\n|\r|\n)/', ' ', $item_name);

?>

<input type="hidden" id="update_log" name="update_log" value="<?=$update_log?>">   

<div class="container-fluid">
    <div class="d-flex align-items-center justify-content-center">
        <div class="card justify-content-center">
            <div class="card-header text-center">
                <span class="text-center fs-5 ms-2 me-4"><?=$title_message?></span>
				<?php if ($mode === 'update'): ?>
					<button type="button" id="viewinspection" class="btn btn-dark btn-sm me-3"  
							data-num="<?= htmlspecialchars($num) ?>" 
							data-specification="<?= htmlspecialchars($specification_clean) ?>" 
							data-remarks="<?= htmlspecialchars($remarks_clean) ?>" 
							data-itemname="<?= htmlspecialchars($item_name_clean) ?>" >
						<i class="bi bi-list"></i> 수입검사서 
					</button>
				<?php endif; ?>
            </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 table-hover">
                            <tbody>
                                <tr>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">로트번호</td>
                                    <td class="text-center" style="width:200px;">
                                        <input type="text" class="form-control fs-6 noborder-input" id="lot_no" name="lot_no" value="<?=$lot_no?>" autocomplete="off" required >
                                    </td>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">검사일</td>
                                    <td class="text-center" style="width:200px;">
                                        <input type="date" class="form-control fs-6 noborder-input" id="inspection_date" name="inspection_date" value="<?=$inspection_date?>"  required >
                                    </td>
                                </tr>
                                <tr>
									<td class="text-center fs-6 fw-bold" style="width:150px;">납품업체</td>
									<!-- 납품업체 선택 -->
									<td class="text-center" style="width:200px;">
										<select class="form-control fs-6 noborder-input" id="supplier" name="supplier"  required >
											<option value="">선택</option>
											<?php
											foreach ($uniqueSupplierNames as $name) {
												$selected = (isset($supplier) && $supplier === $name) ? 'selected' : '';
												echo "<option value=\"$name\" $selected>$name</option>";
											}
											?>
											<option value="direct" class='text-danger'>직접입력</option> <!-- 직접입력 옵션 -->
										</select>
									</td>
									<td class="text-center fs-6 fw-bold" style="width:150px;">품명</td>
									<td class="text-center" style="width:200px;">
										<select class="form-control fs-6 noborder-input" id="item_name" name="item_name"  required >
											<option value="">선택</option> <!-- 기본값: 선택 -->
											<?php
											foreach ($uniqueItemNames as $name) {
												// 기본적으로 선택된 옵션이 있는 경우, `selected` 속성 추가
												$selected = (isset($item_name) && $item_name === $name) ? 'selected' : '';
												echo "<option value=\"$name\" $selected>$name</option>";
											}
											?>
										</select>
									</td>
                                </tr>
                                <tr>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">규격</td>
                                    <td class="text-center" style="width:200px;">
										<select class="form-control fs-6 noborder-input" id="specification" name="specification"  required >
											<option value="">선택</option> <!-- 기본값: 선택 -->										
											<?php
											foreach ($uniquespecificationNames as $name) {
												$selected = (isset($specification) && $specification === $name) ? 'selected' : '';
												echo "<option value=\"$name\" $selected>$name</option>";
											}
											?>										
                                    </td>
									<td class="text-center fs-6 fw-bold" style="width:150px;">단위</td>
									<td class="text-center" style="width:200px;">
										<select class="form-control fs-6 noborder-input" id="unit" name="unit">
											<option value="">선택</option>
											<?php
											foreach ($uniqueUnitNames as $name) {
												// 기존 값이 있으면 선택
												$selected = (isset($unit) && $unit === $name) ? 'selected' : '';
												echo "<option value=\"$name\" $selected>$name</option>";
											}
											?>
											<option value="direct" class='text-danger'>직접입력</option> <!-- 직접입력 옵션 -->
										</select>
									</td>
                                </tr>
                                <tr>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">품목코드</td>
                                    <td class="text-center" colspan="3" >
                                        <input type="text" class="form-control fs-6 noborder-input" id="prodcode" name="prodcode" value="<?=$prodcode?>" autocomplete="off"  required >
                                    
                                    </td>
                                </tr>
                                <tr>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">입고량</td>
                                    <td class="text-center" style="width:200px;">
                                        <input type="text" class="form-control text-center fs-6 noborder-input" id="received_qty" name="received_qty" value="<?=$received_qty?>" autocomplete="off" onkeyup="inputNumberFormat(this)"  required >
                                    </td>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">자재번호</td>
                                    <td class="text-center" style="width:200px;">
                                        <input type="text" class="form-control fs-6 noborder-input" id="material_no" name="material_no" value="<?=$material_no?>" autocomplete="off">
                                    </td>
                                </tr>
                                <tr>
									<td class="text-center fs-6 fw-bold" style="width:150px;">제조사</td>
									<td class="text-center" style="width:200px;">
										<select class="form-control fs-6 noborder-input" id="manufacturer" name="manufacturer"  required >
											<option value="">선택</option>
											<?php
											foreach ($uniqueManufacturerNames as $name) {
												// 기본적으로 선택된 옵션이 있는 경우, `selected` 속성 추가
												$selected = (isset($manufacturer) && $manufacturer === $name) ? 'selected' : '';
												echo "<option value=\"$name\" $selected>$name</option>";
											}
											?>
											<option value="direct" class='text-danger'>직접입력</option> <!-- 직접입력 옵션 -->
										</select>
									</td>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">소진여부</td>
                                    <td class="text-center" style="width:200px;">
                                    <input type="text" class="form-control  text-center fs-6 noborder-input" id="lotDone" name="lotDone" value="<?=$lotDone?>" autocomplete="off">
									</td>                                    
                                </tr>
<tr>
    <td class="text-center fs-6 fw-bold" style="width:150px;">매입가(VAT 별도)</td>
    <td class="text-center" style="width:200px;">
        <input type="text" class="form-control text-center fs-6 noborder-input" 
               id="purchase_price_excl_vat" name="purchase_price_excl_vat" 
               value="<?= isset($purchase_price_excl_vat) && is_numeric($purchase_price_excl_vat) ? number_format($purchase_price_excl_vat) : '' ?>" 
               autocomplete="off" onkeyup="inputNumberFormat(this)">
    </td>
    <td class="text-center fs-6 fw-bold" style="width:150px;">중량(kg)</td>
    <td class="text-center" style="width:200px;">
        <input type="text" class="form-control text-center fs-6 noborder-input" 
               id="weight_kg" name="weight_kg" 
               value="<?= isset($weight_kg) && is_numeric($weight_kg) ? number_format($weight_kg) : '' ?>" 
               autocomplete="off" onkeyup="inputNumberFormat(this)">
    </td>
</tr>


                                <tr>
                                    </td>
                                    <td class="text-center fs-6 fw-bold" style="width:150px;">비고</td>
                                    <td colspan="3" class="text-center" >
                                        <input type="text" class="form-control fs-6  noborder-input text-start" id="remarks" name="remarks" value="<?=$remarks?>" autocomplete="off">
                                    </td>                                    
                                </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="d-flex justify-content-center">
                    <button type="button" id="saveBtn" class="btn btn-dark btn-sm me-3">
                        <i class="bi bi-floppy-fill"></i> 저장
                    </button>                    
                    <?php if($mode != 'insert') { ?>
					<button type="button" id="copyBtn" class="btn btn-primary btn-sm me-3">
                        <i class="bi bi-copy"></i> 복사
                    </button>
                    <button type="button" id="deleteBtn" class="btn btn-danger btn-sm me-3">
                        <i class="bi bi-trash"></i>  삭제 
                    </button>
                    <?php } ?>
                    <button type="button" id="closeBtn" class="btn btn-outline-dark btn-sm me-2">
                        &times; 닫기
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>