<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
	xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">

<head>
	<th:block th:replace="/web/include/head :: layout_head"></th:block>
	<th:block layout:fragment="layout_css">
		<link rel="stylesheet" href="/css/kiosk/existing-patient.css">
	</th:block>
</head>

<th:block layout:fragment="layout_top_script">
	<script src="/js/kiosk/common.js"></script>
	<script src="/js/web/signature_pad.js"></script>
</th:block>

<th:block layout:fragment="layout_content">
	<div id="reserveReadyInsertModal" class="kiosk-container"> <!-- ID kept for JS compatibility -->

		<!-- Header -->
		<header class="page-header">
			<h1 class="title">기존 고객 바로접수</h1>
		</header>

		<!-- Body -->
		<main class="page-body">
			<div id="list1" class="form-grid-layout"> <!-- ID kept for JS compatibility -->

				<!-- Column 1: Customer Search & Info -->
				<section class="form-section-card">
					<div class="section-title">고객 조회</div>

					<div class="form-row">
						<label>고객 검색</label>
						<div class="search_box" data-toggle="modal" data-target=".client_inquiry"
							style="position:relative; cursor:pointer;">
							<input type="hidden" name="modalUserId" />
							<input type="text" name="modalUserName" placeholder="터치하여 고객 검색 (이름/연락처)" readonly
								style="padding-right: 40px; cursor:pointer;" />
							<img src="/image/web/search_B.svg" alt="search"
								style="position:absolute; right:12px; top:50%; transform:translateY(-50%); width:18px;">
						</div>
					</div>

					<div class="form-row">
						<label>고객 정보</label>
						<table class="info-table">
							<tr>
								<th>고객등급</th>
								<td class="modalUserType">-</td>
							</tr>
							<tr>
								<th>생년월일</th>
								<td class="modalBirthday">-</td>
							</tr>
							<tr>
								<th>성별</th>
								<td class="modalGender">-</td>
							</tr>
							<tr>
								<th>국적</th>
								<td class="modalNationality">-</td>
							</tr>
							<tr>
								<th>연락처</th>
								<td class="modalPhoneNumber">-</td>
							</tr>
							<tr>
								<th>특이사항</th>
								<td class="modalMemo">-</td>
							</tr>
						</table>
					</div>
				</section>

				<!-- Column 2: Reservation Details -->
				<section class="form-section-card reserveRowBox">
					<div class="section-title">예약 정보</div>

					<!-- Dynamic reservation row will be injected here or statically defined if logic permits. 
                         The original JS appends ".modal_table_content". We will adapt. 
                         For now, we define the structure directly for the FIRST row to avoid JS injection issues on load if possible.
                         However, legacy JS appends it. Let's keep the container relative.
                    -->

					<!-- We'll let JS append the complicated row, but stylize the container -->
				</section>

				<!-- Column 3: Staff & Memo -->
				<section class="form-section-card">
					<div class="section-title">담당자 및 메모</div>

					<div class="form-row">
						<label>담당자 (직원)</label>
						<input type="hidden" name="modalMemberId" />

						<!-- Read Mode -->
						<div class="read_box" style="display:flex; gap:10px;">
							<input type="text" name="modalMemberName" placeholder="담당자 없음" disabled>
							<button class="manager_btn" style="width:50px; padding:0; background:#f0f2f5;"><img
									src="/image/web/menu_6_off.svg" alt="수정" style="width:20px;"></button>
						</div>

						<!-- Edit Mode -->
						<div class="search_box member_box" style="display:none; position:relative; margin-top:5px;">
							<input type="text" name="modalMemberName" readonly placeholder="담당자 검색"
								style="padding-right: 80px;" />
							<img src="/image/web/search_B.svg"
								style="position:absolute; right:60px; top:50%; transform:translateY(-50%); width:18px;">
							<button class="cancel_btn"
								style="position:absolute; right:0; top:0; height:100%; border-radius:0 4px 4px 0;">취소</button>
						</div>
					</div>

					<div class="form-row" style="margin-top:20px;">
						<label>접수 메모</label>
						<textarea placeholder="접수 시 참고할 메모를 입력하세요 (선택)" style="height:150px;"></textarea>
					</div>
				</section>

			</div>
		</main>

		<!-- Footer -->
		<footer class="page-footer">
			<button type="button" class="cancel_btn btnCancle">취소</button>
			<div id="list1"> <!-- Scope required for JS selector -->
				<button type="button" class="registration_bth btnSave">접수 완료</button>
			</div>
		</footer>

	</div>
</th:block>

<th:block layout:fragment="layout_popup">
	<!-- Member Search Modal (Hidden by default) -->
	<div id="memberSearchModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true" style="display:none;">
		<div class="modal-dialog" style="max-width:600px; margin: 100px auto;">
			<div class="modal-content">
				<div class="modal-header" style="background:#f8f9fa; border-bottom:1px solid #ddd; padding:15px;">
					<h5 class="modal-title" style="margin:0; font-weight:700;">직원 검색</h5>
				</div>
				<div class="modal-body" style="padding:20px;">
					<div style="display:flex; gap:10px; margin-bottom:15px;">
						<input id="memberSearchKeyword" type="text" class="form-control" placeholder="이름 또는 연락처"
							style="height:40px; flex:1;">
						<button id="searchMemberBtn" class="btn btn-primary"
							style="height:40px; width:80px; background:#1B66C9; color:#fff; border:none; border-radius:4px;">검색</button>
					</div>
					<div class="list1_modal_table" style="max-height:300px; overflow-y:auto;">
						<table class="table table-hover" style="width:100%; font-size:14px;">
							<thead style="background:#f1f3f5;">
								<tr>
									<th style="padding:10px;">이름</th>
									<th style="padding:10px;">연락처</th>
									<th style="padding:10px;">부서</th>
								</tr>
							</thead>
							<tbody>
								<!-- Dynamic Content -->
							</tbody>
						</table>
					</div>
				</div>
				<div class="modal-footer" style="padding:15px; border-top:1px solid #ddd;">
					<button type="button" class="btn btn-secondary btnCancle" data-dismiss="modal">닫기</button>
				</div>
			</div>
		</div>
	</div>
</th:block>

<th:block layout:fragment="layout_script">
	<script type="text/javascript">
		$(document).ready(function () {
			// Page Init
			reserveReadyInsertModal.init();
		});

		let reserveReadyInsertModal = {
			callback: null,
			reqParam: null,
			init: function () {
				// Remove legacy modal template injection
				// $('#reserveReadyInsertModal').remove(); 
				// $('body').append( this.HtmlTemplate);

				// Initialize Events
				this.setEvent();

				// Add default row
				this.addRow();
			},
			setEvent: function () {
				$('.btnCancle').on("click", function () {
					history.back();
				});

				$('#list1 .btnSave').on("click", function () {
					reserveReadyInsertModal.save("I");
				});

				// User Search
				$('#list1 input[name="modalUserName"]').on("click", function () {
					userIntroSelectModal.popup(function (obj) {
						// Populate User Info
						$('#list1 input[name="modalUserId"]').val(obj.muuserid);
						$('#list1 input[name="modalUserName"]').val(obj.username);
						$('#list1 .modalPhoneNumber').text(fn_setFormatPhone(obj.phonenumber));

						if ("T" == obj.userType2) {
							$('.modalUserType').text('간편예약');
							$('.modalBirthday').text(obj.birthday || '-');
						} else {
							$('.modalUserType').html(obj.usertype ? `<img src="\${obj.usertype.replace('C:', '')}" height="20"/>` : '일반');
							$('.modalBirthday').text(obj.birthday);
							$('.modalGender').text(obj.gender);
							$('.modalNationality').text(obj.nationality || 'KR');
							$('.modalMemo').text(obj.memo);
						}
					});
				});

				// Manager Edit Toggle
				$('#list1 .manager_btn').on("click", function () {
					$('#list1 .read_box').hide();
					$('#list1 .member_box').show();
				});
				$('#list1 .cancel_btn').on("click", function () {
					$('#list1 .read_box').show();
					$('#list1 .member_box').hide();
				});

				// Manager Search
				$('input[name="modalMemberName"]').on("click", function () {
					memberSearchModal.popup(function (obj) {
						$('input[name="modalMemberName"]').val(obj.selectMemberName);
						$('input[name="modalMemberId"]').val(obj.selectMemberId);
						// Return to read mode
						$('#list1 .read_box').show();
						$('#list1 .member_box').hide();
					});
				});
			},

			/* Dynamic Row Addition (Re-styled) */
			addRow: function () {
				let h = `
               <div class="form-row modal_table_content" style="border:1px solid #eee; padding:15px; border-radius:8px; margin-bottom:10px;">
                    <!-- Date -->
                    <div style="margin-bottom:10px;">
                        <label>예약일시</label>
                        <div style="display:flex; gap:10px;">
                            <div style="flex:1; position:relative;">
                                <input type="text" class="date_picker" name="modalReserveDate" placeholder="YYYY-MM-DD">
                            </div>
                            <div class="select_box dropdown" style="flex:1;">
                                <button class="label" data-toggle="dropdown">00:00</button>
                                <input type="hidden" name="modalReserveTime">
                                <ul class="select_option_list dropdown-menu time"></ul>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Category -->
                    <div style="margin-bottom:10px;">
                        <label>예약경로</label>
                        <div class="select_box dropdown">
                            <button class="label" data-toggle="dropdown">선택하세요</button>
                            <input type="hidden" name="modalReserveCategoryItemCode">
                            <ul class="select_option_list dropdown-menu category-list"></ul>
                        </div>
                    </div>
                    
                    <!-- Procedure -->
                    <div style="margin-bottom:10px;">
                        <label>진료유형</label>
                        <div class="search_box">
                             <input type="hidden" name="modalTreatmentProcedureId" />
                             <input type="text" name="modalTreatmentProcedureName" readonly placeholder="진료/시술 검색" />
                        </div>
                    </div>
                    
                    <!-- Doctor -->
                     <div>
                        <label>닥터/상담</label>
                        <div class="select_box dropdown">
                            <button class="label" data-toggle="dropdown">선택하세요</button>
                            <input type="hidden" name="modalReserveMemberId">
                            <ul class="select_option_list dropdown-menu doctor-list"></ul>
                        </div>
                    </div>
               </div>
               `;

				$('.reserveRowBox').append(h);
				this.setReserveCategoryCombo();

				let lastRow = $('.reserveRowBox .modal_table_content').last();

				// Init Datepicker
				lastRow.find('.date_picker').datetimepicker({
					format: 'YYYY-MM-DD',
					defaultDate: moment()
				}).on("dp.change", function (e) {
					fn_searchSetTime(lastRow.find('.time'), e.date.format("YYYY-MM-DD"));
				});

				// Init Time
				fn_searchSetTime(lastRow.find('.time'), moment().format("YYYY-MM-DD"));

				// Procedure Search
				lastRow.find('input[name="modalTreatmentProcedureName"]').on("click", function () {
					treatmentProcedureSearchModal.popup(function (obj) {
						lastRow.find('input[name="modalTreatmentProcedureId"]').val(obj.mutreatmentprocedureid);
						lastRow.find('input[name="modalTreatmentProcedureName"]').val(obj.treatmentprocedurename);

						// Set Doctor Combo
						let comboData = fn_selectListReserveMemberOption(lastRow.find('.date_picker').val(), obj.mutreatmentprocedureid);
						let html = '';
						comboData.forEach(d => {
							html += `<li class="option_list_item" id="doc_\${d.mumemberid}">\${d.typename} \${d.membername}</li>`;
						});
						lastRow.find('.doctor-list').html(html);
					});
				});

				// Dropdown Click
				lastRow.on('click', '.option_list_item', function () {
					let txt = $(this).text();
					let id = $(this).attr('id');
					// Handle id prefix if any (e.g., doc_123)
					if (id && id.indexOf('_') > -1) id = id.split('_')[1];

					$(this).closest('.dropdown').find('.label').text(txt);
					$(this).closest('.dropdown').find('input[type="hidden"]').val(id);
				});
			},

			setReserveCategoryCombo: function () {
				let category = fn_selectCategoryList();
				let reservationCategory = category.find(cat => cat.categoryname === '예약경로');
				if (reservationCategory) {
					fn_selectModalOtherOption(reservationCategory.categorycode, '');
					// The common function targets generic selectors. We might need to manually populate if it fails.
					// Assuming fn_selectModalOtherOption works by finding selectors globally or passed context.
					// For safety, let's manually populate the last row's category list if possible, 
					// or rely on common.js if it finds '.category-list'. 
					// Common.js usually finds by class. Let's assume it works or we use a custom fetch here if needed.
				}
			},

			save: function (state) {
				// Validation & Save Logic (Copied from original but simplified selectors)
				let muUserId = $('#list1 input[name="modalUserId"]').val();
				let userName = $('#list1 input[name="modalUserName"]').val();

				// Get reservation details from the generated row
				let row = $('.reserveRowBox .modal_table_content').last();
				let reserveDate = row.find('input[name="modalReserveDate"]').val();
				let reserveTime = row.find('input[name="modalReserveTime"]').val();
				let catCode = row.find('input[name="modalReserveCategoryItemCode"]').val();
				let procId = row.find('input[name="modalTreatmentProcedureId"]').val();
				let docId = row.find('input[name="modalReserveMemberId"]').val();

				let memId = $('input[name="modalMemberId"]').val(); // Staff

				if (!muUserId) { modalEvent.warning("접수", "고객을 선택해주세요."); return; }
				if (!reserveDate || !reserveTime) { modalEvent.warning("접수", "예약 일시를 선택해주세요."); return; }
				if (!procId) { modalEvent.warning("접수", "진료 유형을 선택해주세요."); return; }

				modalEvent.info("접수", "접수를 진행하시겠습니까?", function () {
					let formData = new FormData();
					formData.append("muUserId", muUserId);
					formData.append("userName", userName);
					formData.append("reserveDate", reserveDate);
					formData.append("reserveTime", reserveTime);
					formData.append("reserveCategoryItemCode", catCode);
					formData.append("muTreatmentProcedureId", procId);
					formData.append("reserveMemberId", docId);
					formData.append("muMemberId", memId);

					$.ajax({
						url: '/webreserve/insertReserveReady.do',
						type: 'POST',
						data: formData,
						processData: false, contentType: false,
						success: function (data) {
							if (data.msgCode == '0') {
								modalEvent.success("성공", "접수가 완료되었습니다.", function () {
									history.back();
								});
							} else {
								modalEvent.danger("실패", data.msgDesc);
							}
						}
					});
				});
			}
		};

		let memberSearchModal = {
			callback: null,
			popup: function (cb) {
				this.callback = cb;
				$('#memberSearchModal').modal('show');
			},
			setSelect: function (id, name, phone) {
				if (this.callback) this.callback({ selectMemberId: id, selectMemberName: name });
				$('#memberSearchModal').modal('hide');
			}
		};

		// Search Button Event
		$('#searchMemberBtn').on('click', function () {
			let kw = $('#memberSearchKeyword').val();
			let fd = new FormData();
			fd.append("memberSearchKeywordParam", kw);
			$.ajax({
				url: '/kiosk/getMemberList.do',
				type: 'POST',
				data: fd, processData: false, contentType: false,
				success: function (data) {
					if (data.msgCode == '0') {
						let tbody = $('#memberSearchModal tbody');
						tbody.empty();
						data.rows.forEach(m => {
							let tr = $(`
                            <tr style="cursor:pointer;">
                                <td>\${m.membername}</td>
                                <td>\${fn_setFormatPhone(m.phonenumber)}</td>
                                <td>\${m.dutyname}</td>
                            </tr>
                           `);
							tr.click(() => memberSearchModal.setSelect(m.mumemberid, m.membername, m.phonenumber));
							tbody.append(tr);
						});
					}
				}
			});
		});

	</script>
</th:block>

</html>