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

// 결재권자 직함과 이름을 정해준다.
$approvalName = '대표 이경호';

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

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

// 배열로 기본정보 불러옴
require_once($_SERVER['DOCUMENT_ROOT'] . "/common.php");
require_once($_SERVER['DOCUMENT_ROOT'] . "/almember/load_DB.php");

// holiday 테이블에서 휴일 목록 불러오기
$holidayDates = [];
try {
    $holidaySql = "SELECT startdate, enddate FROM " . $DB . ".holiday WHERE is_deleted IS NULL";
    $holidayStmt = $pdo->query($holidaySql);
    $holidayRows = $holidayStmt->fetchAll(PDO::FETCH_ASSOC);
    
    foreach ($holidayRows as $holidayRow) {
        $startdate = $holidayRow['startdate'];
        $enddate = $holidayRow['enddate'];
        
        // enddate가 '0000-00-00'이거나 비어있으면 startdate만 휴일
        if (empty($enddate) || $enddate === '0000-00-00' || $enddate === null) {
            $holidayDates[] = $startdate;
        } else {
            // 기간 내의 모든 날짜를 배열에 추가
            $start = new DateTime($startdate);
            $end = new DateTime($enddate);
            $end->modify('+1 day'); // 종료일 포함
            
            $period = new DatePeriod($start, new DateInterval('P1D'), $end);
            foreach ($period as $date) {
                $holidayDates[] = $date->format('Y-m-d');
            }
        }
    }
} catch (PDOException $e) {
    // 오류 발생 시 빈 배열 유지
    error_log("Holiday 데이터 로드 오류: " . $e->getMessage());
}

if ($mode === 'update' && $num) {
    try {
        $sqlModal = "SELECT * FROM " . $DB . "." . $tablename . " WHERE num=?";
        $stmh = $pdo->prepare($sqlModal);
        $stmh->bindValue(1, $num, PDO::PARAM_STR);
        $stmh->execute();
        $row = $stmh->fetch(PDO::FETCH_ASSOC);
        include 'rowDBask.php';
    } catch (PDOException $Exception) {
        echo "오류: " . $Exception->getMessage();
    }
} else {
    include '_request.php';
    $mode = 'insert';

    $registdate = date("Y-m-d H:i:s");
    $al_askdatefrom = date("Y-m-d");
    $al_askdateto = date("Y-m-d");
    $al_usedday = abs(strtotime($al_askdateto) - strtotime($al_askdatefrom)) + 1;
    $al_item = '연차';
    $status = 'send';
    $statusstr = '결재요청';
    $author = $_SESSION["name"];
    $author_id = $user_id;
	$al_company = $_SESSION["mycompany"];
	$al_part = $_SESSION["mypart"];
}

try {
    $totalusedday = 0;
    $totalremainday = 0;
    $previous_usage = 0;
    for ($i = 0; $i < count($totalname_arr); $i++) {
        if ($author == $totalname_arr[$i]) {
			$previous_usage = $previous_usage_arr[$i];
            $availableday = $availableday_arr[$i] - $previous_usage;
        }
    }
	
    for ($i = 0; $i < count($totalname_arr); $i++) {
        if ($author == $totalname_arr[$i]) {
            $totalusedday = $totalused_arr[$i];
            $previous_usage = $previous_usage_arr[$i];
            $totalremainday = $availableday - $previous_usage - $totalusedday;
        }
    }
} catch (PDOException $Exception) {
    echo "오류: " . $Exception->getMessage();
}

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

?>

<input type="hidden" id="mode" name="mode" value="<?= isset($mode) ? $mode : '' ?>">
<input type="hidden" id="num" name="num" value="<?= isset($num) ? $num : '' ?>">    
<input type="hidden" id="registdate" name="registdate" value="<?= isset($registdate) ? $registdate : '' ?>">
<input type="hidden" id="author_id" name="author_id" value="<?= isset($author_id) ? $author_id : '' ?>">    
<input type="hidden" id="status" name="status" value="<?= isset($status) ? $status : '' ?>">
<input type="hidden" id="division" name="division" value="<?= isset($al_company) ? $al_company : '' ?>">
<input type="hidden" id="htmltext" name="htmltext">
<?php
// 임시 키 생성 (고유값, 예: uniqid 사용)
if ($mode === 'insert' || empty($num)) {
    $temp_key = 'temp_' . uniqid('al_', true);
} else {
    $temp_key = $num;
}
?>
<input type="hidden" id="temp_key" name="temp_key" value="<?= $temp_key ?>">

<div class="container-fluid" >
	<div class="row d-flex justify-content-center align-items-center h-75">
		<div class="col-12 text-center">
			<div class="card" style="border-radius:20px;">                    
				 <h4 class="card-title text-center" style="color:#113366;"> 연차 신청 <span class="text-secondary small"> #<?= $num ?></span> </h4>
				<div class="card-body">
					<?php if ($e_confirm === '') {
						$formattedDate = date("m/d", strtotime($registdate));
						if ($al_part == '경동' || $al_part == '주일' ) {
							$approvals = array(
								array("name" => $approvalName , "date" =>  $formattedDate),
							);
						}
					} else {
						$approver_ids = explode('!', $e_confirm_id);
						$approver_details = explode('!', $e_confirm);
						$approvals = array();
						foreach ($approver_ids as $index => $id) {
							if (isset($approver_details[$index])) {
								preg_match("/^(.+ \d{4}-\d{2}-\d{2}) (\d{2}:\d{2}:\d{2})$/", $approver_details[$index], $matches);
								if (count($matches) === 3) {
									$nameWithTitle = $matches[1];
									$time = $matches[2];
									$date = substr($nameWithTitle, -10);
									$nameWithTitle = trim(str_replace($date, '', $nameWithTitle));
									$formattedDate = date("m/d H:i:s", strtotime("$date $time"));
									$approvals[] = array("name" => $nameWithTitle, "date" => $formattedDate);
								}
							}
						}
					}
					if ($status === 'end') { ?>
						<div class="d-flex justify-content-center " >						
						<div class="row d-flex justify-content-center align-items-center w300px">
							<table class="table table-bordered table-sm p-0" >
								<thead>
									<tr>
										<th colspan="<?php echo count($approvals); ?>" class="text-center fs-6">결재</th>
									</tr>
								</thead>
								<tbody>
									<tr>
										<?php foreach ($approvals as $approval) { ?>
											<td class="text-center fs-6" style="height: 50px;"><?php echo $approval["name"]; ?></td>
										<?php } ?>
									</tr>
									<tr>
										<?php foreach ($approvals as $approval) { ?>
											<td class="text-center"><?php echo $approval["date"]; ?></td>
										<?php } ?>
									</tr>
								</tbody>
							</table>
						</div>
						</div>
					<?php } ?>
					<div id="savetext">
						<div class="row d-flex justify-content-center align-items-center">
							성명
							<select name="author" id="author" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
								<?php
								for ($i = 0; $i < count($employee_name_arr); $i++) {
									if ($author == $employee_name_arr[$i])
										print "<option selected value='" . $employee_name_arr[$i] . "'> " . $employee_name_arr[$i] . "</option>";
									else
										print "<option value='" . $employee_name_arr[$i] . "'> " . $employee_name_arr[$i] . "</option>";
								}
								?>
							</select>
							&nbsp; 회사
							<input type="text" id="al_company" name="al_company" value="<?=$al_company ?>" class="form-control w100px mx-1" readonly>
							&nbsp; 파트
							<input type="text" id="al_part" name="al_part" class="form-control mx-1" style="width:100px;" value="<?= $al_part ?>" readonly>
						</div>

						<div class="table-responsive mt-2">
							<table class="table table-bordered table-sm w-auto mb-2" style="width:auto; margin:0 auto;">
								<tr>
									<td class="text-center" style="width:120px;">구분</td>
									<td>
										<?php
										$item_arr = array('연차', '오전반차','오후반차','경조사');
										foreach ($item_arr as $i => $item) {
											echo "<label class='me-2'>";
											echo "<input type='radio' name='al_item' value='" . $item . "' " . ($al_item == $item ? "checked='checked'" : "") . "> " . $item;
											echo "</label>";
											// if ($i == 1) echo "<br>";
										}
										?>
									</td>
								</tr>
								<tr>
									<td class="text-center">신청시작일</td>
									<td class="text-start">
										<input type="date" id="al_askdatefrom" name="al_askdatefrom" class="form-control d-inline-block" style="width:120px;" required value="<?= $al_askdatefrom ?>">
									</td>
								</tr>
								<tr>
									<td class="text-center">신청종료일</td>
									<td class="text-start">
										<input type="date" id="al_askdateto" name="al_askdateto" class="form-control d-inline-block" style="width:120px;" required value="<?= $al_askdateto ?>">
									</td>
								</tr>
								<tr>
									<td class="text-center" style="color:blue;">신청 기간 산출</td>
									<td class="text-start">
										<input type="text" id="al_usedday" size="2" name="al_usedday" readonly class="form-control text-center d-inline-block" style="width:50px;" value="<?= $al_usedday ?>">
									</td>
								</tr>
								<tr>
									<td class="text-center" style="color:red;">연차 잔여일수</td>
									<td class="text-start">
										<input type="text" id="totalremainday" name="totalremainday" size="2" class="form-control text-center d-inline-block" style="width:50px;" readonly value="<?= $totalremainday ?>">
									</td>
								</tr>
							</table>
						</div>
						<div class="table-responsive mt-2">
						<table class="table table-bordered table-sm w-auto mb-2" style="width:auto; margin:0 auto;">
							<tr>
								<td class="text-center" style="width:120px;">신청 사유</td>
								<td>
									<select name="al_content" id="al_content" class="form-select mx-1 d-block w-auto" style="font-size: 0.8rem; height: 32px;">
										<?php
										$al_content_arr = array("개인사정", "휴가", "여행", "병원진료등", "전직원연차", "경조사", "기타");
										for ($i = 0; $i < count($al_content_arr); $i++) {
											if ($al_content == $al_content_arr[$i])
												print "<option selected value='" . $al_content_arr[$i] . "'> " . $al_content_arr[$i] .   "</option>";
											else
												print "<option value='" . $al_content_arr[$i] . "'> " . $al_content_arr[$i] .   "</option>";
										}
										?>
									</select>
								</td>
							</tr>
							<tr>
								<td class="text-center" style="width:120px;">결재 상태</td>
								<td class="text-start align-middle vertical-align-middle">
									<?php
									switch ($status) {
										case 'send':
											$statusstr = '결재요청';
											break;
										case 'ing':
											$statusstr = '결재중';
											break;
										case 'end':
											$statusstr = '결재완료';
											break;
										default:
											$statusstr = '';
											break;
									}
									?>
									<input type="text" id="statusstr" name="statusstr" class="form-control text-center"  readonly value="<?= $statusstr ?>">
								</td>
							</tr>
						</table>
						</div>

						<!-- 파일첨부 섹션 추가 -->
						<div class="table-responsive mt-2">
							<table class="table table-bordered table-sm w-auto mb-2" style="width:auto; margin:0 auto;">
								<tr>
									<td class="text-center" style="width:120px;">파일첨부</td>
									<td class="text-start">
										<div class="d-flex flex-column gap-2">
											<!-- 일반 파일 첨부 -->
											<div class="d-flex align-items-center">
												<label for="upfile" class="input-group-text btn btn-outline-primary btn-sm me-2" style="font-size: 0.8rem;">
													파일 첨부
												</label>
												<input id="upfile" name="upfile[]" type="file" multiple style="display:none" accept=".pdf,.doc,.docx,.xls,.xlsx,.txt,.zip,.rar">
												<span class="text-muted small">(10MB 이하, PDF, 문서, 압축파일 등)</span>
											</div>
											<!-- 이미지 첨부 -->
											<div class="d-flex align-items-center">
												<label for="upfileimage" class="input-group-text btn btn-outline-dark btn-sm me-2" style="font-size: 0.8rem;">
													이미지 첨부
												</label>
												<input id="upfileimage" name="upfileimage[]" type="file" multiple style="display:none" accept=".gif,.jpg,.jpeg,.png">
												<span class="text-muted small">(이미지 파일: GIF, JPG, PNG)</span>
											</div>
										</div>
										<!-- 첨부된 파일 표시 영역 -->
										<div id="displayFile" class="mt-2" style="display:none;"></div>
										<div id="displayImage" class="mt-2" style="display:none;"></div>
									</td>
								</tr>
							</table>
						</div>

					
						<div class=" d-flex justify-content-center mt-2 mb-2 align-items-center">						
						<? if ((int)$num > 0 and $level =='1' ) {
							print '<button  type="button"  id="saveBtn" class="btn btn-sm btn-dark mx-1 " type="button">';
							print '결재요청(수정)';
							print '</button>';
						} else if ($statusstr !== '결재완료') {
							print '<button  type="button" id="saveBtn" class="btn btn-sm btn-dark mx-1 " type="button">';
							print '결재요청';
							print '</button>';
						}
						if ((int)$num > 0 and $level =='1'  ) { ?>
							<button type="button" id="deleteBtn" class="btn btn-sm btn-danger mx-1" type="button"> <i class="bi bi-trash"></i>  삭제 </button>
						<? } ?>
		  
						<button  type="button"  class="btn btn-dark btn-sm ms-4" id="closeBtn"> &times; 닫기 </button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

<script>
// fetch_modal.php에서도 holiday 데이터를 전달 (기존 holidaySet과 병합)
(function() {
    var modalHolidayDates = <?= json_encode($holidayDates, JSON_UNESCAPED_UNICODE) ?>;
    
    // 전역 holidaySet 초기화 또는 업데이트
    if (typeof window.holidaySet === 'undefined' || !(window.holidaySet instanceof Set)) {
        window.holidaySet = new Set(modalHolidayDates);
    } else {
        // 기존 holidaySet에 추가
        modalHolidayDates.forEach(function(date) {
            window.holidaySet.add(date);
        });
    }
    
    // 로컬 스코프에도 설정 (기존 코드와의 호환성)
    if (typeof holidaySet === 'undefined') {
        window.holidaySet = window.holidaySet || new Set(modalHolidayDates);
    } else {
        modalHolidayDates.forEach(function(date) {
            holidaySet.add(date);
        });
    }
    
    console.log('Holiday 데이터 로드 완료:', modalHolidayDates.length, '개');
})();
</script>
