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

// 권한 체크 (관리자 이하만 접근)
if (!isset($_SESSION["level"]) || intval($_SESSION["level"]) > 1) {
    sleep(1);
    header("Location:" . $WebSite . "login/login_form.php");
    exit;
} 

$title_message = '연차 설정';
$admin = (intval($_SESSION["level"]) === 1) ? 1 : 0;

$tablename = 'almember';
$num = $_REQUEST["num"] ?? '';
$mode = $_REQUEST["mode"] ?? '';
$mode = isset($_REQUEST["mode"]) ? $_REQUEST["mode"] : '';

require_once($_SERVER['DOCUMENT_ROOT'] . "/common.php");	

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

// modify 모드면 기존 데이터 조회하여 변수 설정
if ($mode == 'modify' && !empty($num)) {
    try {
        $sql = "SELECT * FROM {$DB}.{$tablename} WHERE num = ?";
        $stmh = $pdo->prepare($sql);
        $stmh->bindValue(1, $num, PDO::PARAM_STR);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        // _row.php 내부에서 $name, $comment, $company, $part, $dateofentry, $referencedate, $availableday 등 변수를 설정한다고 가정
        include $_SERVER['DOCUMENT_ROOT'] . '/almember/_row.php';
		
    } catch (PDOException $Exception) {
        print "오류: " . $Exception->getMessage();
    }
	
		
}
else {
	$referencedate = date('Y'); // 현재 연도만 가져오기
}

$usedname = $name; // 불러온 이름 저장

// almember의 기본정보 배열을 불러옴 (예, $basic_name_arr, $basic_part_arr 등)
require_once($_SERVER['DOCUMENT_ROOT'] . "/almember/load_DB.php");

// member 테이블에서 회사(division) 정보를 distinct로 조회하여 select 옵션에 사용
$divisions = [];
try {
    $sql = "SELECT DISTINCT division FROM {$DB}.member WHERE division IS NOT NULL AND division <> ''";
    $stmt = $pdo->query($sql);
    $divisions = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
    print "오류: " . $e->getMessage();
}

include $_SERVER['DOCUMENT_ROOT'] . '/load_header.php' ?>   
    <title><?=htmlspecialchars($title_message)?></title>    
    <!-- 추가 CSS나 메타 태그가 필요하면 여기 추가 -->
</head>
<body>
<div class="container mt-4">
    <h4 class="text-center mb-4"><?=htmlspecialchars($title_message)?></h4>
    <form name="board_form" id="board_form" method="post">
        <!-- 숨겨진 필드들 -->
        <input type="hidden" id="mode" name="mode">
        <input type="hidden" id="num" name="num" value="<?=htmlspecialchars($num)?>">
        <input type="hidden" id="user_name" name="user_name" value="<?=htmlspecialchars($user_name)?>">
        <input type="hidden" id="admin" name="admin" value="<?=htmlspecialchars($admin)?>">
   <!-- 부트스트랩 table (4열) 형태의 입력폼 -->
        <table class="table table-bordered">
            <tbody>
                <!-- 1행: 회사 / 부서 -->
                <tr>
                    <td style="width:20%;"><label for="name">성명</label></td>
                    <td style="width:30%;">
                        <select name="name" id="name" required class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
                            <?php 
                            // employee_name_arr 를 이용하여 옵션 생성 (중복 제거)
                            $unique_names = array_unique($employee_name_arr);
                            foreach ($unique_names as $n) {
                                $selected = (isset($usedname) && $usedname === $n) ? "selected" : "";
                                echo "<option value=\"" . htmlspecialchars($n) . "\" $selected>" . htmlspecialchars($n) . "</option>";
                            }
                            ?>
                        </select>
                    </td>
                    <td style="width:20%;"><label for="dateofentry">입사일</label></td>
                    <td style="width:30%;">
                        <input type="date" id="dateofentry" name="dateofentry" class="form-control" placeholder="입사일" readonly required value="<?=isset($dateofentry) ? htmlspecialchars($dateofentry) : ''?>">
                    </td>
                </tr>                
                <tr>					
                    <td><label for="company">회사</label></td>
                    <td>
                        <input type="text" id="company" name="company" class="form-control" placeholder="회사" readonly required value="<?=isset($company) ? htmlspecialchars($company) : ''?>">
                    </td>
                    <td style="width:15%;"><label for="part">부서</label></td>
                    <td style="width:35%;">			
                       <input type="text" id="part" name="part" class="form-control" placeholder="부서" readonly required value="<?=isset($part) ? htmlspecialchars($part) : ''?>">
                    </td>
                </tr>
                <!-- 3행: 해당연도 -->
                <tr>
                    <td><label for="referencedate">해당연도</label></td>
                    <td>
                        <input type="number" id="referencedate" name="referencedate" class="form-control" placeholder="해당연도" required value="<?=isset($referencedate) ? htmlspecialchars($referencedate) : ''?>">
                    </td>
                    <td class="text-center"><label for="continueYear">근속년수</label></td>
                    <td>
                        <input type="number" id="continueYear" name="continueYear" class="form-control" placeholder="근속년수"  readonly required value="<?=isset($continueYear) ? htmlspecialchars($availableday) : ''?>">
                    </td>
                </tr>
                <!-- 4행: 해당연도 -->
                <tr>                    
                    <td class="text-center"><label for="initial_less_than_one_year">1년미만 가산</label></td>
                    <td>
                        <input type="number" id="initial_less_than_one_year" name="initial_less_than_one_year" class="form-control"  readonly placeholder="1년미만 가산" required value="<?=isset($initial_less_than_one_year) ? htmlspecialchars($availableday) : ''?>">
                    </td>
                    <td><label for="service_based">년도별 연차</label></td>
                    <td>
                        <input type="number" id="service_based" name="service_based" class="form-control" placeholder="년도별 연차"  readonly required value="<?=isset($service_based) ? htmlspecialchars($service_based) : ''?>">
                    </td>
                </tr>
                <!-- 5행:  선사용 년도별 연차 발생일수 -->
                <tr>
                    <td class="text-center"><label for="previous_year_usage" class="fw-bold text-dnager" >전년도 선사용</label></td>
                    <td colspan="1">
                        <input type="number" id="previous_year_usage" name="previous_year_usage" class="form-control fw-bold text-dnager" placeholder="전년도 선사용"  required value="<?=isset($previous_year_usage) ? htmlspecialchars($previous_year_usage) : ''?>">
                    </td>
                    <td class="text-center"><label for="availableday" class="fw-bold text-primary" >발생일수</label></td>
                    <td colspan="1">
                        <input type="number" id="availableday" name="availableday" class="form-control fw-bold text-primary" placeholder="발생일수"  readonly required value="<?=isset($availableday) ? htmlspecialchars($availableday) : ''?>">
                    </td>
                </tr>
            </tbody>
        </table>
    </form>
        <!-- 하단 버튼 영역 -->
        <div class="d-flex justify-content-end mt-4">
            <button type="button" id="saveBtn" class="btn btn-dark btn-sm mx-1"> <i class="bi bi-floppy-fill"></i> 저장
                <?= ((int)$num > 0 ? '수정' : '저장') ?>
            </button>
            <?php if ((int)$num > 0) { ?>
                <button type="button" id="copyBtn" class="btn btn-primary btn-sm mx-1"> <i class="bi bi-copy"></i>  데이터복사</button>
                <button type="button" id="delBtn" class="btn btn-danger btn-sm mx-1"> <i class="bi bi-trash"></i>  삭제  </button>
            <?php } ?>
                <button type="button" id="closeBtn" class="btn btn-secondary btn-sm ms-4"> &times; 닫기</button>
        </div>
</div>

<script>
$(document).ready(function(){
    // 로딩 오버레이가 있다면 숨김
    var loader = document.getElementById('loadingOverlay');
    if(loader) loader.style.display = 'none';

    // 성명 선택 변경 시, 해당 직원의 정보를 가져와 동적으로 업데이트
    $("#name").change(function(){
        var selectedName = $(this).val();
        $.ajax({
            url: "get_employee_info.php",
            type: "post",
            data: { name: selectedName },
            dataType: "json",
            success: function(data){
				//alert(data);
				console.log(data);
                if(data) {
                    // 업데이트: 회사, 부서, 입사일
                    $("#company").val(data.division);
                    $("#part").val(data.part);
                    $("#dateofentry").val(data.enterDate);
                    $("#referencedate").val(data.referencedate);
                    $("#initial_less_than_one_year").val(data.initial_less_than_one_year);
                    $("#continueYear").val(data.continueYear);
                    $("#service_based").val(data.service_based);
                    $("#previous_year_usage").val(data.previous_year_usage);
                    $("#availableday").val(data.available);
                }
            },
            error: function(xhr, status, error){
                console.log("Error: " + error);
            }
        });	

    });

    $("#closeBtn").click(function(){
        self.close();
    });

    $("#saveBtn").click(function(){
        var admin = $("#admin").val();
        if(admin == '1'){
            var num = $("#num").val();
            // num 값이 있으면 modify, 없으면 insert 모드로 전송
            if(Number(num) > 0)
                $("#mode").val('modify');
            else
                $("#mode").val('insert');

            $.ajax({
                url: "insert.php",
                type: "post",
                data: $("#board_form").serialize(),
                dataType: "json",
                success: function(data){
                    console.log(data);
                    setTimeout(function(){
                        opener.location.reload();
                        window.close();
                    }, 1000);
                },
                error: function(jqxhr, status, error){
                    console.log(jqxhr, status, error);
                }
            });
        }
    });

    $("#copyBtn").click(function(){
        var admin = $("#admin").val();
        if(admin == '1'){
            $("#mode").val('copy');
            $.ajax({
                url: "insert.php",
                type: "post",
                data: $("#board_form").serialize(),
                dataType: "json",
                success: function(data){
                    console.log(data);
                    setTimeout(function(){
                        opener.location.reload();
                        window.close();
                    }, 1000);
                },
                error: function(jqxhr, status, error){
                    console.log(jqxhr, status, error);
                }
            });
        }
    });

    $("#delBtn").click(function(){
        var admin = $("#admin").val();
        if(admin == '1'){
            Swal.fire({
                title: '해당 DATA 삭제',
                text: "DATA 삭제는 신중하셔야 합니다.\n정말 삭제 하시겠습니까?",
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#3085d6',
                cancelButtonColor: '#d33',
                confirmButtonText: '삭제',
                cancelButtonText: '취소'
            }).then((result) => {
                if(result.isConfirmed){
                    $("#mode").val('delete');
                    $.ajax({
                        url: "insert.php",
                        type: "post",
                        data: $("#board_form").serialize(),
                        dataType: "json",
                        success: function(data){
                            console.log(data);
                            opener.location.reload();
                            window.close();
                        },
                        error: function(jqxhr, status, error){
                            console.log(jqxhr, status, error);
                        }
                    });
                }
            });
        }
    });
	
	// 최초실행시 선택
	$("#name").trigger('change');
});
</script>
</body>
</html>