HEX
Server: Apache/2.4.37 (CentOS Stream) OpenSSL/1.1.1k
System: Linux ysnet.com.tw 4.18.0-553.5.1.el8.x86_64 #1 SMP Tue May 21 05:46:01 UTC 2024 x86_64
User: test (521)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /var/www/test/Installationlist/oldphp/form1(1).php
<?php
	// 使用 db.php 連接資料庫
	$user_id = $_GET['user_id'];
	require_once '../db.php';
	try {
		$stmt = $conn->prepare("SELECT name, user, member, speed, season, halfyear, year, twoyear, discount, email, homenumber, phone, memberaddress, useraddress, basenumber, pppoeid, pppoepw, standard, fistcount FROM filemaker WHERE user = ?");
		$stmt->bind_param('s', $user_id);
		$stmt->execute();
		$result = $stmt->get_result();
		if ($result->num_rows > 0) {
			$user = $result->fetch_assoc();
            $name = $user['name'];
            $member = $user['member'];
            $speed = $user['speed'];
			$season = $user['season'];
    		$halfyear = $user['halfyear'];
    		$year = $user['year'];
    		$twoyear = $user['twoyear'];
            $discount = $user['discount'];
            $email= $user['email'];
        	$homenumber =$user['homenumber'];
            $phone = $user['phone'];
            $memberaddress = $user['memberaddress'];
            $useraddress = $user['useraddress'];
            $basenumber = $user['basenumber'];
            $pppoeid = $user['pppoeid'];
            $pppoepw = $user['pppoepw'];
        	$standard = $user['standard'];
			$fistcount = $user['fistcount'];
		}
	} catch (Exception $e) {
		$error = "資料庫錯誤:" . $e->getMessage();
    }
	$standard_on =($standard !='');
	$isSubscription = (strpos($speed, '定期') !== false) ? 1: 0;

	//讓js可抓取變數
	$plan_options = [
        "season" => !empty($season) ? ["price" => $season, "barcode" => $season] : null,
        "halfyear" => !empty($halfyear) ? ["price" => $halfyear, "barcode" => $halfyear] : null,
        "year" => !empty($year) ? ["price" => $year, "barcode" => $year] : null,
        "twoyear" => !empty($twoyear) ? ["price" => $twoyear, "barcode" => $twoyear] : null
    ];
	
	$todayObj  = new DateTime();           // 今天
?>
<!DOCTYPE html>
<html lang="zh-Hant">
    <head>
        <meta charset="UTF-8">
    	<meta name="format-detection" content="telephone=no"> <!-- 防止手機偵測電話 -->
        <title>網際網路接取服務申請書</title>
        <style>
            body {
                font-family: "Microsoft JhengHei", sans-serif;
                font-size: 20px;
                margin: 20px;
                font-weight: bold;
            }

            table {
                border-collapse: collapse;
                width: 100%;
            }

            td, th {
                border: 1px solid #000;
                padding: 5px;
                vertical-align: top;
            }

            .title {
                text-align: center;
                font-size: 25px;
                font-weight: bold;
                padding: 10px 0;
            }

            .section-title {
                background: #eee;
            }

            .nowrap {
                white-space: nowrap; 
                text-align:center;
            }

            input[type="text"],
            input[type="date"],
            input[type="tel"] {
                width: 100%;
                font-size:22px;
                box-sizing: border-box;
            }
			
			.auto-break {
   				white-space: pre-wrap;    /* 保留空格並自動換行 */
    			word-break: break-word;   /* 強制文字換行,避免溢出 */
    			font-size: 22px;
    			text-align: center;
    			vertical-align: middle;
			}
			
			.responsive-input {
                flex: 1;
                width: 100%;
                min-width: 50%;
                max-width: 100%;
                text-align: center;
                font-size: 22px;
                background-color: transparent; /* 背景透明,呈現純文字感 */
                outline: none;                 /* 移除點選時的外框 */
            }

            /* 響應式設定 */
            @media (max-width: 768px) {
                .responsive-input {
                    font-size: 3vw;            /* 自動縮放字體大小 */
                }
            }

			.no-tel-link {
            	pointer-events: none;
            	color: inherit;
            	text-decoration: none;
        	}

        	.no-tel-link a {
            	pointer-events: none !important;
            	text-decoration: none !important;
            	color: inherit !important;
        	}
        </style>
    </head>
    <body>
        <div style="font-size:14px; text-align: center;">
            公司地址:桃園市桃園區大興西路二段61號16樓&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
            電話:03-358-5867&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
            傳真:03-301-2115&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp
            官方網址:www.ysnet.com.tw
        </div><br>
        <div style="display: flex; align-items: center; padding-bottom: 5px; border-bottom: 1px solid black;">
            <div style="display: flex; flex-direction: column; justify-content: center; align-items: center; line-height: 1.2; margin-left: 50px;">
                <strong style="font-size: 22px;">YSNET</strong>
                <span style="font-size: 12px;">亞訊股份有限公司</span>
            </div>
            <div style="flex: 1; text-align: center; font-size: 30px;"><u>___網際網路接取服務申請書___</u></div>
            <img src="/eye-close.png" style="margin-right: 50px;" />
        </div>
        <table>
            <tr class="section-title">
                <td colspan="6">申請人資訊</td>
            </tr>
            <tr>
                <td class="nowrap">用戶編號</td>
                <td><input type="text" name="user_id_display" value="<?php echo htmlspecialchars($user_id); ?>" class="responsive-input" style="border: none;" readonly></td>
                <td class="nowrap">社區名稱</td>
                <td><input type="text" name="member_display" value="<?php echo htmlspecialchars($member); ?>" class="responsive-input" style="border: none;" readonly></td>
                <td class="nowrap">申請人姓名</td>
                <td><input type="text" name="applicant_name" value="<?= htmlspecialchars($name ?? '')?>" class="responsive-input"></td>      
            </tr>
            <tr>
                <td class="nowrap">住宅電話</td>
                <td><input type="tel" name="applicant_homenumber" value="<?= htmlspecialchars($homenumber ?? '')?>" class="responsive-input"></td>
                <td class="nowrap">身份證字號</td>
                <td><input type="text" name="applicant_usernumber" class="responsive-input"></td>
                <td class="nowrap">行動電話</td>
                <td><input type="tel" name="applicant_phone" value="<?= htmlspecialchars($phone ?? '')?>" class="responsive-input"></td>
            </tr>
		</table>
        <table>
            <tr>
                <td class="nowrap" style="width:5%">裝機地址</td>
                <td colspan="5" style="font-size:22px;"><span><?= htmlspecialchars($memberaddress); ?></span><input type="text" name="install_address" value="<?= htmlspecialchars($useraddress ?? '')?>" style="width: 500px; flex: 1; min-width: 50%; max-width: 100%; "></td>
            </tr>
            <tr>
                <td class="nowrap">電子信箱</td>
                <td colspan="5"><input type="text" name="applicant_email" style="flex: 1; min-width: 50%; max-width: 100%;"></td>
            <tr>
				<td class="nowrap" >申請速率</td>
                <td colspan="3" ><div style="font-size:22px; text-align:center;"><span>最高下載速率(</span><?= htmlspecialchars($speed); ?><span>)Mbps</span></div></td>
				<td class="nowrap" >連接據點編號</td>
				<td><input type="text" name="basenumber" value="<?= htmlspecialchars($basenumber ?? '')?>" class="responsive-input"></td>
			</tr>
			<tr>
                <td class="nowrap">pppoe<br>連線帳號</td>
                <td class="nowrap" class="no-tel-link" style="min-width: 150px;"><div style="height: 50px; line-height: 50px; font-size:40px;"><?= htmlspecialchars($pppoeid ?? '') ?></div></td>
				<td class="nowrap" rowspan="2" style="text-align: center; vertical-align: middle;">首次裝機<br>優惠資訊</td>
				<?php if(!$isSubscription): ?>
					<td class="auto-break" rowspan="2" colspan="3" style="font-size:16px; text-align:left;"><?php echo $fistcount; ?></td>
				<?php else: ?>
					<td class="auto-break" rowspan="2" colspan="3" style="font-size:16px; text-align:left; vertical-align:top; white-space:normal;">
        					<?php echo "信用卡定期定額注意事項:<br>
                    			定期定額僅提供月扣方案,並不適用現金繳費好禮方案。<br>
                    			使用未滿一個月中途退租終止恕不退費,服務可使用至已扣款之繳費期限。"
        					?>
					</td>
				<?php endif; ?>				
			</tr>
			<tr>
                <td class="nowrap">pppoe<br>連線密碼</td>
                <td class="nowrap" style="min-width: 150px;"><div style="height: 50px; line-height: 50px; font-size:40px;"><?= htmlspecialchars($pppoepw ?? '') ?></div></td>
            </tr>
        </table>        
        <br>
        <table style="width:100%; border-collapse: collapse;" border="1">
    		<tr class="section-title">
        		<td colspan="4" style="width:100%; text-align:center;">請工程師與客戶確認下列資料</td>
    		</tr>
    		<tr>
        		<td style="width:16%; text-align:center;">設備資訊</td>
        		<td style="width:28%; text-align:center;">室內資訊箱設備</td>
        		<td style="width:28%; text-align:center;">室內網路設備</td>
        		<td style="width:28%; text-align:center;">借用設備料號</td>
    		</tr>
			<tr>
                <td style="text-align:center;">使用資訊</td>
				<td>
					<div id="info-box-container"></div>
					<button type="button" onclick="addinfoBox()" style="font-size: 18px; padding: 4px 8px;">+</button>
				</td>
				<td>
					<div id="Router-box-container"></div>
					<button type="button" onclick="addRouterBox()" style="font-size: 18px; padding: 4px 8px;">+</button>
				</td>
				<td>
					<div id="use-box-container"></div>
					<button type="button" onclick="adduseBox()" style="font-size: 18px; padding: 4px 8px;">+</button>
				</td>
			</tr>
		</table>
		<table>
            <tr>
                <td class="nowrap" style="width:16%; text-align:center;">收費項目</td>
                <td class="nowrap" style="width:22%; text-align:center;">單價(元)</td>
                <td class="nowrap" style="width:34%; text-align:center;">金額</td>
            </tr>
            <tbody id="fee-table-body">
        		<tr>
            		<td class="nowrap">網路費用</td>
            		<td>
						<select id="fee-select" style="width:100%; font-size:16px;" onchange="togglepayInput(this)">
						</select>
					</td>
            		<td><div id="pay-container" class="price-cell" style="text-align:center;"></div></td>       
        		</tr>
    		</tbody>
            <tr>
                <td class="nowrap" colspan="2">
                    <div style="display: flex; justify-content: space-between; width: 100%;">
						<button type="button" onclick="addpricebox()" style="font-size: 18px; padding: 4px 8px;">+</button>
                        <span>應繳費用總計</span>
                    </div>
                </td>
                <td colspan="1"><input type="text" name="total_fee" style="flex: 1; min-width: 50%; max-width: 100%;"></td>
				<td>
            		<div style="display: flex; align-items: center; flex-wrap: nowrap;">
  						<label style="white-space: nowrap;">收款人簽名:</label>
  						<canvas id="signaturePreview" width="200" height="30" style="border:1px solid #000; margin-left: 8px; cursor:pointer; flex-shrink: 0;"></canvas>
					</div>
        		</td>
            </tr>
        </table>
        <table>
			 <colgroup>
    			<col style="width: 10%;">   <!-- 第1欄:裝機日/起租日 -->
    			<col style="width: 41%;">   <!-- 第2欄 -->
    			<col style="width: 24%;">   <!-- 第3欄 -->
    			<col style="width: 24%;">   <!-- 第4欄 -->
  			</colgroup>
            <tr>
                <td class="nowrap">裝機日</td>
				<td >
					<div style="display: flex; align-items: center; justify-content: flex-end; gap: 4px;">
   						<input type="date" name="install_date" style="flex: 1; min-width: 50%; max-width: 100%;">    					
  					</div>
				</td>
				<td rowspan="4" colspan="2">
					<div style="font-size:18px; text-align:center;">
						<u>____網路開通後,請確認下列事項____</u>
							<ol style="font-size:14px; text-align:left;">
  								<li>確定已可上網連線使用,完成驗收無誤。</li>
  								<li>已詳閱並確認本公司契約條款與資費方案。</li>
								<li>發票將於建檔完成後由本公司郵寄送達。</li>
								<li>購買本公司產品由我方提供壹年保固。</li>
								<li>若提前退租,其所享之贈送上網月份將自動喪失。</li>
								<li>提前退租須備原申請人身份證件至本總公司辦理退費折讓。</li>
								<li>確認電話、電視及對講機線路皆可正常使用。</li>
							</ol>
					</div>
				</td>
			</tr>
            <tr>
                <td class="nowrap">起租日</td>
                <td >
					<div style="display: flex; align-items: center; justify-content: flex-end; gap: 4px;">
   						<input type="date" name="rental_start_date" style="flex: 1; min-width: 50%; max-width: 100%;">    					
  					</div>
				</td>				
            </tr>
            <tr>
                <td class="nowrap">到期日</td>
                <td >
					<div style="display: flex; align-items: center; justify-content: flex-end; gap: 4px;">
   						<input type="date" name="rental_end_date" style="flex: 1; min-width: 50%; max-width: 100%;">    					
  					</div>
				</td>
            </tr>
            <tr>
                <td class="nowrap">贈送月份</td>
                <td>
					<div id="given-months-container"></div>
					<button type="button" onclick="givenmonthsBox()" style="font-size: 18px; padding: 4px 8px;">+</button>
				</td>
            </tr>
            <tr>
				<td class="nowrap" style="font-size:18px;">贈送後<br>到期日</td>
                <td >
					<div style="display: flex; align-items: center; justify-content: flex-end; gap: 4px;">
   						<input type="date" name="real_end_date" style="flex: 1; min-width: 50%; max-width: 100%;">    					
  					</div>
				</td>
				<td colspan="2">
					<div style="display: flex; justify-content: center; align-items: center; margin-top: 10px;">
    					<label style="white-space: nowrap; margin-right: 8px;">申請人簽名:</label>
    					<canvas id="applicantSignaturePreview" width="200" height="30" style="border:1px solid #000; margin-left: 8px; cursor:pointer; flex-shrink: 0;"></canvas>
					</div>
				</td>
            </tr>
        </table>
		<!-- 共用簽名 Modal -->
		<div id="signatureModal" style="display:none; position:fixed; top:0; left:0; width:100vw; height:100vh;
    		background:rgba(0,0,0,0.5); justify-content:center; align-items:center; z-index:9999;">
    		<div style="background:#fff; padding:20px; border-radius:10px;">
        		<p id="signatureTitle" style="margin:0 0 10px;">請簽名</p>
        		<canvas id="signaturePad" width="500" height="200" style="border:2px solid #000; touch-action: none;"></canvas><br><br>
        		<button onclick="clearSignature()">清除</button>
        		<button onclick="saveSignature()">完成</button>
    		</div>
		</div>
        <script>
			function addinfoBox() {
                const container = document.getElementById('info-box-container');

                const newGroup = document.createElement('div');
                newGroup.className = 'info-box-group';
                newGroup.style.marginBottom = '4px';

                newGroup.innerHTML = `             
                    <button type="button" onclick="removeinfoBox(this)" style="font-size: 18px; padding: 4px 4px;">-</button>
                    <select name="info_box[]" style="font-size:18px;">
                    	<option value="100M有線分享器">100M有線分享器</option>
                    	<option value="1000M有線分享器">1000M有線分享器</option>
						<option value="100M無線分享器">100M無線分享器</option>
                    	<option value="1000M無線分享器">1000M無線分享器</option>
						<option value="MESH">MESH</option>
                    	<option value="光轉B">光轉B</option>
						<option value="光貓">光貓</option>
						<option value="100M集線器">100M集線器</option>
						<option value="1000M集線器">1000M集線器</option>
						<option value="UY">UY</option>
						<option value="Panel">Panel</option>
                    </select>
					<select name="info_qty[]" style="font-size:18px;">
                    	<option value="1">1</option>
                    	<option value="2">2</option>
						<option value="3">3</option>
                    	<option value="4">4</option>
						<option value="5">5</option>
                    </select>
                `;

                container.appendChild(newGroup);
            }

			function removeinfoBox(button) {
                const group = button.closest('.info-box-group');
                group.remove();
            }

            function addRouterBox() {
                const container = document.getElementById('Router-box-container');

                const newGroup = document.createElement('div');
                newGroup.className = 'Router-box-group';
                newGroup.style.marginBottom = '4px';

                newGroup.innerHTML = `					                    
                    <button type="button" onclick="removeRouterBox(this)" style="font-size: 18px; padding: 4px 4px;">-</button>
                    <select name="Router_box[]" style="font-size:18px;" onchange="updateRouterQtyInput(this)">
						<option value="">選擇設備</option>
                    	<option value="100M有線分享器">100M有線分享器</option>
                    	<option value="1000M有線分享器">1000M有線分享器</option>
						<option value="100M無線分享器">100M無線分享器</option>
                    	<option value="1000M無線分享器">1000M無線分享器</option>
						<option value="MESH">MESH</option>
						<option value="電視盒">電視盒</option>
						<option value="100M集線器">100M集線器</option>
						<option value="1000M集線器">1000M集線器</option>
                    </select>
					<div class="qty-container" style="display:inline-block; margin-left: 8px;">
        			</div>
                `;

                container.appendChild(newGroup);
            }
			
			function updateRouterQtyInput(selectElem) {
    			const qtyContainer = selectElem.parentElement.querySelector('.qty-container');

    			if (selectElem.value === '電視盒') {
       			 	qtyContainer.innerHTML = `
            		<select name="tv_box[]" onchange="toggleTvOtherInput(this)" style="width:60px; height:30px;">
                			<option value="cm">公司</option>
                			<option value="or">其他</option>
            			</select>
					<input type="text" name="tv_other[]" style="display:none;width:200px;height:30px;" placeholder="請輸入廠牌">
        			`;
    			} else {
        			qtyContainer.innerHTML = `
           			<select name="Router_qty[]" style="font-size:18px;">
                    	<option value="1">1</option>
                    	<option value="2">2</option>
						<option value="3">3</option>
                    	<option value="4">4</option>
						<option value="5">5</option>
                    </select> 
        			`;
    			}
			}

			function toggleTvOtherInput(selectElem) {
    			const input = selectElem.parentElement.querySelector('input[name="tv_other[]"]');
    			input.style.display = selectElem.value === 'or' ? 'inline-block' : 'none';
			}

			function removeRouterBox(button) {
                const group = button.closest('.Router-box-group');
                group.remove();
            }
			
			
			function adduseBox() {
                const container = document.getElementById('use-box-container');

                const newGroup = document.createElement('div');
                newGroup.className = 'use-box-group';
                newGroup.style.marginBottom = '4px';

                const selectHTML = `
                    <div style="display: flex; align-items: center; gap: 8px;">
						<button type="button" onclick="removeuseBox(this)" style="font-size: 18px; padding: 4px 4px;">-</button>
                        <select name="router_box[]" onchange="toggleQtyInput(this)" style="font-size:18px;">
                            <option value="">選擇設備</option>
                            <option value="1000M無線分享器">100M無線分享器</option>
                            <option value="1000M無線分享器">1000M無線分享器</option>
                            <option value="光轉">光轉</option>
                            <option value="光貓">光貓</option>
                            <option value="電視盒">電視盒</option>
                        </select>                        
                    </div>
                    <div class="qty-wrapper" style="display:none; margin-top: 4px;">
                        料號:<input type="text" name="use_sn[]" maxlength="20" style="width: 200px;" placeholder="請輸入設備料號"><br>
						押金:<input type="text" name="use_dp[]" maxlength="20" style="width: 200px;" placeholder="請輸入設備押金">
                    </div>					
                `;
                newGroup.innerHTML = selectHTML;
                container.appendChild(newGroup);
            }

            function toggleQtyInput(selectElem) {
    			const parentGroup = selectElem.closest('.use-box-group');
    			const wrapper = parentGroup.querySelector('.qty-wrapper');

    			if (selectElem.value) {
       				wrapper.style.display = 'inline-block';
    			} else {
        			wrapper.style.display = 'none';
    			}
			}

            function removeuseBox(button) {
                const group = button.closest('.use-box-group');
                group.remove();
            }
			
			const planOptions = <?php echo json_encode($plan_options); ?>;
			const isSubscription = <?= $isSubscription ?>;

			document.addEventListener("DOMContentLoaded", function () {
                const selectElem = document.getElementById("fee-select");

                // 先清空選單
                selectElem.innerHTML = "";

                const defaultOption = document.createElement("option");
                defaultOption.value = "";
                defaultOption.textContent = "請選擇費率";
                selectElem.appendChild(defaultOption);

                if (isSubscription) {
                    const option = document.createElement("option");
                    option.value = "定期定額月扣";
                    option.textContent = "定期定額月扣";
                    selectElem.appendChild(option);
                } else {
                    const options = ["季繳", "半年繳", "一年繳", "兩年繳"];
                    options.forEach(function (label) {
                        const option = document.createElement("option");
                        option.value = label;
                        option.textContent = label;
                        selectElem.appendChild(option);
                    });
                }
            });

			function togglepayInput(selectElem) {
    			const payContainer = document.getElementById('pay-container');
    			let selected = selectElem.value;

    			let key = '';
    			switch (selected) {
        			case '季繳': key = 'season'; break;
        			case '半年繳': key = 'halfyear'; break;
        			case '一年繳': key = 'year'; break;
        			case '兩年繳': key = 'twoyear'; break;
        			case '定期定額月扣':
            			payContainer.innerHTML = '信用卡扣款';
						calculateTotal(); // <-- 呼叫計算
            			return;
        			default:
            			payContainer.innerHTML = '';
						calculateTotal(); // <-- 呼叫計算
            			return;
    			}

    			if (planOptions[key]) {
        			payContainer.innerHTML = `${planOptions[key].price} `;
    			} else {
        			payContainer.innerHTML = '此選項無對應金額';
    			}
				calculateTotal(); // <-- 呼叫計算
			}

			function addpricebox() {
                const tbody = document.getElementById('fee-table-body');

                const newRow = document.createElement('tr');
                newRow.className = 'price-box-row';

                newRow.innerHTML = `
                    <td>
                        <button type="button" onclick="removepriceBox(this)" style="font-size: 18px; padding: 4px 4px;">-</button>
                        <select name="price_box[]" style="font-size:18px;" onchange="toggleNumberInput(this)">
                            <option value="裝機費用">裝機費用</option>
                            <option value="配線費用">配線費用</option>
                            <option value="周邊設備">周邊設備</option>
                        </select>
                    </td>
                    <td><input type="text" name="other_fee_price[]" oninput="calculateTotal()"></td>
                    <td><input type="text" name="other_fee_amount[]" oninput="calculateTotal()"></td>
                    <td class="number-input-container" style="display: none;">
                        <div style="display: flex; align-items: center; white-space: nowrap;">
                            <span>設備料號</span>
                            <input type="text" name="other_fee_number[]" style="margin-left: 6px; flex: 1; min-width: 0;">
                        </div>
                    </td>
                `;

                tbody.appendChild(newRow);
            }
			
			function calculateTotal() {
    			let total = 0;

    			// 1. 網路費用加總
    			const payDiv = document.getElementById('pay-container');
    			const netFee = parseFloat(payDiv.textContent);
    			if (!isNaN(netFee)) {
        			total += netFee;
    			}

    			// 2. 動態欄位金額加總
    			const otherAmounts = document.querySelectorAll('input[name="other_fee_amount[]"]');
    			otherAmounts.forEach(input => {
        			const value = parseFloat(input.value);
        			if (!isNaN(value)) {
            			total += value;
        			}
    			});

    			// 顯示總額
    			document.querySelector('input[name="total_fee"]').value = total.toFixed(0);
			}

			
			// 切換「設備料號」欄位顯示
			function toggleNumberInput(selectElement) {
    			const container = selectElement.closest('tr').querySelector('.number-input-container');
    			if (selectElement.value === '周邊設備') {
        			container.style.display = 'flex';
    			} else {
        			container.style.display = 'none';
    			}
			}

			function removepriceBox(button) {
    			const row = button.closest('tr');
    			row.remove();
				calculateTotal();
			}

			const modal = document.getElementById('signatureModal');
            const signaturePad = document.getElementById('signaturePad');
            const previewCanvas = document.getElementById('signaturePreview');
            const applicantPreviewCanvas = document.getElementById('applicantSignaturePreview');
            const previewCtx = previewCanvas.getContext('2d');
            const applicantPreviewCtx = applicantPreviewCanvas.getContext('2d');
            const padCtx = signaturePad.getContext('2d');
            const signatureTitle = document.getElementById('signatureTitle');

            let drawing = false;
            let currentTarget = null; // 'payer' or 'applicant'

            function getPosition(e, canvas) {
                const rect = canvas.getBoundingClientRect();
                if (e.touches) {
                    return {
                        x: e.touches[0].clientX - rect.left,
                        y: e.touches[0].clientY - rect.top
                    };
                } else {
                    return {
                        x: e.clientX - rect.left,
                        y: e.clientY - rect.top
                    };
                }
            }

            function startDrawing(e) {
                e.preventDefault();
                drawing = true;
                const pos = getPosition(e, signaturePad);
                padCtx.beginPath();
                padCtx.moveTo(pos.x, pos.y);
            }

            function draw(e) {
                if (!drawing) return;
                e.preventDefault();
                const pos = getPosition(e, signaturePad);
                padCtx.lineTo(pos.x, pos.y);
                padCtx.stroke();
            }

            function stopDrawing(e) {
                e.preventDefault();
                drawing = false;
            }

			document.addEventListener("DOMContentLoaded", function () {
                const installInput = document.querySelector('input[name="install_date"]');
                const rentalStartInput = document.querySelector('input[name="rental_start_date"]');
                const rentalEndInput = document.querySelector('input[name="rental_end_date"]');
                const realEndInput = document.querySelector('input[name="real_end_date"]');
                const feeSelect = document.getElementById("fee-select");

                const today = "<?= (new DateTime())->format('Y-m-d') ?>";
                installInput.value = today;

                updateRentalStartDate(today);
                updateRentalEndDate();

                installInput.addEventListener("change", function () {
                    updateRentalStartDate(installInput.value);
                    updateRentalEndDate();
                });

                feeSelect.addEventListener("change", function () {
                    updateRentalEndDate();
                });

                rentalEndInput.addEventListener("change", updateRealEndDate);

                function updateRentalStartDate(installDateStr) {
                    const date = new Date(installDateStr);
                    date.setDate(date.getDate() + 1);
                    rentalStartInput.value = date.toISOString().split("T")[0];
                }

                function isEndOfMonth(date) {
                    const next = new Date(date);
                    next.setDate(date.getDate() + 1);
                    return next.getDate() === 1;
                }

                function calculateEndDateByInstallDate(installDateStr, monthsToAdd) {
                    const start = new Date(installDateStr);
                    const result = new Date(start);
                    result.setDate(1);
                    result.setMonth(result.getMonth() + monthsToAdd);

                    if (isEndOfMonth(start)) {
                        result.setMonth(result.getMonth() + 1);
                        result.setDate(0);
                    } else {
                        const targetDay = start.getDate();
                        const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
                        result.setDate(Math.min(targetDay, lastDay));
                    }

                    return result.toISOString().split("T")[0];
                }

                function updateRentalEndDate() {
                    const selected = feeSelect.value;
                    const installDate = installInput.value;

                    let monthsToAdd = 0;
                    switch (selected) {
                        case "季繳": monthsToAdd = 3; break;
                        case "半年繳": monthsToAdd = 6; break;
                        case "一年繳": monthsToAdd = 12; break;
                        case "兩年繳": monthsToAdd = 24; break;
                        default:
                            rentalEndInput.value = "";
                            updateRealEndDate();
                            return;
                    }

                    const endDateStr = calculateEndDateByInstallDate(installDate, monthsToAdd);
                    rentalEndInput.value = endDateStr;

                    updateRealEndDate(); // ✅ 關鍵呼叫:同步贈送後到期日
                }

                function updateRealEndDate() {
                    const rentalEndDateStr = rentalEndInput.value;
                    if (!rentalEndDateStr) {
                        realEndInput.value = '';
                        return;
                    }

                    const baseDate = new Date(rentalEndDateStr);
                    const monthSelects = document.querySelectorAll('select[name="give_qty[]"]');

                    let totalMonths = 0;
                    monthSelects.forEach(select => {
                        totalMonths += parseInt(select.value || 0, 10);
                    });

                    const realDate = new Date(baseDate);
                    realDate.setMonth(realDate.getMonth() + totalMonths);

                    const targetDay = baseDate.getDate();
                    const lastDay = new Date(realDate.getFullYear(), realDate.getMonth() + 1, 0).getDate();
                    realDate.setDate(Math.min(targetDay, lastDay));

                    realEndInput.value = realDate.toISOString().split("T")[0];
                }

                window.givenmonthsBox = function () {
                    const container = document.getElementById('given-months-container');
                    const newGroup = document.createElement('div');
                    newGroup.className = 'given-months-group';
                    newGroup.style.marginBottom = '4px';

                    newGroup.innerHTML = `
                        <button type="button" onclick="removegivenBox(this)" style="font-size: 18px; padding: 4px 4px;">-</button>
                        <select name="given_box[]" style="font-size:18px;">
                            <option value="首裝優惠">首裝優惠</option>
                            <option value="他網轉入">他網轉入</option>
                            <option value="總幹事介紹">總幹事介紹</option>
                            <option value="業務贈送">業務贈送</option>
                            <option value="LINE推廣">LINE推廣</option>
                            <option value="住戶介紹">住戶介紹</option>
                        </select>
                        <select name="give_qty[]" style="font-size:18px;">
                            ${[...Array(12)].map((_, i) => `<option value="${i+1}">${i+1}</option>`).join("")}
                        </select>
                    `;

                    container.appendChild(newGroup);
                    newGroup.querySelector('select[name="give_qty[]"]').addEventListener("change", updateRealEndDate);
                    updateRealEndDate();
                }

                window.removegivenBox = function (button) {
                    const group = button.closest('.given-months-group');
                    group.remove();
                    updateRealEndDate();
                }
            });

			function updateRealEndDate() {
    			const rentalEndDateInput = document.querySelector('input[name="rental_end_date"]');
    			const realEndDateInput = document.querySelector('input[name="real_end_date"]');

    			if (!rentalEndDateInput.value) {
        			realEndDateInput.value = '';
       		 		return;
    			}

    			const baseDate = new Date(rentalEndDateInput.value);
    			const monthSelects = document.querySelectorAll('select[name="give_qty[]"]');

    			let totalGivenMonths = 0;
    			monthSelects.forEach(select => {
        			totalGivenMonths += parseInt(select.value, 10);
    			});

    			// 複製日期物件,避免原本的值被改動
    			const realEndDate = new Date(baseDate);
    			const baseDay = baseDate.getDate();
    			realEndDate.setMonth(realEndDate.getMonth() + totalGivenMonths);

    			// 處理月底邏輯,避免跳到隔月
    			if (baseDate.getDate() !== realEndDate.getDate()) {
        			// 嘗試設定為月底
        			realEndDate.setDate(0); // 回到上個月的最後一天
    			}

    			realEndDateInput.value = realEndDate.toISOString().split("T")[0];
			}
			
            signaturePad.addEventListener('mousedown', startDrawing);
            signaturePad.addEventListener('mousemove', draw);
            signaturePad.addEventListener('mouseup', stopDrawing);
            signaturePad.addEventListener('mouseout', stopDrawing);

            signaturePad.addEventListener('touchstart', startDrawing);
            signaturePad.addEventListener('touchmove', draw);
            signaturePad.addEventListener('touchend', stopDrawing);

            // 預覽 canvas 點擊事件
            previewCanvas.addEventListener('click', () => {
                currentTarget = 'payer';
                signatureTitle.textContent = '請簽名(收款人)';
                modal.style.display = 'flex';
                clearSignature();
            });

            applicantPreviewCanvas.addEventListener('click', () => {
                currentTarget = 'applicant';
                signatureTitle.textContent = '請簽名(申請人)';
                modal.style.display = 'flex';
                clearSignature();
            });

            function clearSignature() {
                padCtx.clearRect(0, 0, signaturePad.width, signaturePad.height);
            }

            function saveSignature() {
                const image = new Image();
                image.src = signaturePad.toDataURL();
                image.onload = () => {
                    if (currentTarget === 'payer') {
                        previewCtx.clearRect(0, 0, previewCanvas.width, previewCanvas.height);
                        previewCtx.drawImage(image, 0, 0, previewCanvas.width, previewCanvas.height);
                    } else if (currentTarget === 'applicant') {
                        applicantPreviewCtx.clearRect(0, 0, applicantPreviewCanvas.width, applicantPreviewCanvas.height);
                        applicantPreviewCtx.drawImage(image, 0, 0, applicantPreviewCanvas.width, applicantPreviewCanvas.height);
                    }
                };
                modal.style.display = 'none';
            }
        </script>
    </body>
</html>