<?php
include_once 'src/inc/db/function.php';
include_once 'createToken.php';
include_once("sendEmail.php");
//echo "csrfToken= ".$_SESSION['csrfToken'] ;
$error = '';

if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    $mcsrfToken = $_POST['csrfToken'] ?? null;
    if ($mcsrfToken == $_SESSION['csrfToken'] && $_POST['action'] == 'login') {
        $account = isset($_POST['account']) && $_POST['account'] !== '' ? htmlspecialchars(trim($_POST['account']), ENT_QUOTES, 'UTF-8') : null;
        $password = isset($_POST['password']) && $_POST['password'] !== '' ? htmlspecialchars(trim($_POST['password']), ENT_QUOTES, 'UTF-8') : null;
        $validate = isset($_POST['validate']) && $_POST['validate'] !== '' ? htmlspecialchars(trim($_POST['validate']), ENT_QUOTES, 'UTF-8') : null;
        if (strtoupper($validate) === strtoupper($_SESSION['captcha'])) {
            $error = login($account, $password);
        } else {
            $error = '驗證碼錯誤！';
        }
    } else if ($mcsrfToken == $_SESSION['csrfToken'] && $_POST['action'] == 'register') {
        // 獲取並清理輸入數據
        /*  $name = filter_input(INPUT_POST, 'userName');
        $account = filter_input(INPUT_POST, 'userNo');
        $email = filter_input(INPUT_POST, 'email');
        $password = $_POST['userPassword']; // 不要過濾密碼,因為它將被哈希
        $unit = filter_input(INPUT_POST, 'department'); */
        // 獲取並清理輸入數據
        $name = filter_input(INPUT_POST, 'name');
        $account = filter_input(INPUT_POST, 'account');
        $email = filter_input(INPUT_POST, 'email');
        $password = $_POST['password']; // 不要過濾密碼,因為它將被哈希
        $unit = filter_input(INPUT_POST, 'unit');
        $message = "";
        $n_rid = 0;
        $mtype = 'error';  //'error',"info","success","warning","question"
        // 驗證輸入
        if (empty($name) || empty($account) || empty($email) || empty($password) || empty($unit)) {
            // die('請填寫所有必填字段');
            $message = "請填寫所有必填項目";
        }

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            //die('無效的電子郵件地址');
            $message = "無效的電子郵件地址";
        }

        // 檢查帳號是否已存在
        // $stmt = $conn->prepare("SELECT COUNT(*)  FROM users WHERE userNo = ? OR email = ? limit 1");
        $stmt = $conn->prepare("SELECT * FROM users WHERE userNo = ? OR email = ? limit 1");
        $stmt->execute([$account, $email]);
        if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            if ($result['userNo'] == $account && $account == $email) {
                $n_rid = $result['user_id'];  // 使用者ID
            }
            $message = "該帳號或email已存在!";
            $mtype = 'info';  //'error',"info","success","warning","question"
            echo json_encode(['success' => false, 'type' => $mtype, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);

            /* if ($stmt->fetchColumn() > 0) {
                $message = "該帳號已被使用";
            } */
        } else {
            // if ($message == "") {
            try {
                $mhsah1 = password_hash($password, PASSWORD_DEFAULT); // 哈希密碼
                $fieldarray = array(
                    'userName' => $name,
                    'userNo' => $account,
                    'userPassword' => $mhsah1,
                    'email' => $email,
                    'department' => $unit,
                    'create_date' => $now,
                    'update_date' => $now,
                    'updated_by' => 'register'
                );

                $n_rid = insert_data1("users", $fieldarray);

                if ($n_rid !== 0) {
                    $result = send_email_regist2($email, $n_rid, $mgo = "token=HanyuToken24982988&act=confirm_customer_mail&email=", $key, $iv);
                    $message = $result ? '帳號確認信件已寄至您的信箱，請確認！' : 'Email發送失敗！';
                    $mtype = 'success';  //'error',"info","success","warning","question"
                } else {
                    $message = '註冊失敗！';
                }
                // 註冊成功
                echo json_encode(['success' => true, 'type' => $mtype, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);
            } catch (PDOException $e) {
                // 註冊失敗
                echo json_encode(['success' => false, 'type' => 'error', 'rid' => $n_rid, 'message' => '註冊失敗: ' . $e->getMessage()], JSON_UNESCAPED_UNICODE);
            }
        }
        /*  else {
            echo json_encode(['success' => false, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);
        } */
        exit;
    } else if ($_REQUEST['action'] == 'register_email') {
        $n_rid = filter_input(INPUT_POST, 'rid');
        $email = filter_input(INPUT_POST, 'email');

        if ($n_rid !== 0 && !empty($email)) {
            $result = send_email_regist2($email, $n_rid, $mgo = "token=HanyuToken24982988&act=confirm_customer_mail&email=", $key, $iv);
            $message = $result ? '帳號確認信件已寄至您的信箱，請確認！' : 'Email發送失敗！';
        } else {
            $message = '信件發送失敗！';
        }
        // 註冊成功
        echo json_encode(['success' => true, 'rid' => $n_rid, 'message' => $message]);
        exit;
    } else if ($mcsrfToken == $_SESSION['csrfToken'] && $_POST['action'] == 'forgetPwd') {
        $email = filter_input(INPUT_POST, 'memail');
        $message = "";
        $msuccess = false;
        $n_rid = 0;
        $mtype = 'error';  //'error',"info","success","warning","question"
        // 驗證輸入
        if (empty($email)) {
            $message = "請填寫所有必填項目";
        }
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $message = "無效的電子郵件地址";
        }
        // 檢查帳號是否已存在      
        $stmt = $conn->prepare("SELECT * FROM users WHERE email = ? limit 1");
        $stmt->execute([$email]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($result) {
            $Npassword = getToken(8);
            $vol = send_email_regist($C_email = $result['email'], $mgo = $Npassword);
            if ($vol) {
                $mhsah1 = password_hash($Npassword, PASSWORD_DEFAULT);
                $fieldarray = array(
                    'userPassword' => $mhsah1,
                    'update_date' => $now,
                    'updated_by' => 'forget'
                );
                $rid = $result['user_id'];
                $where_claud = "user_id= $rid";
                $n_rid = update_data("users", $fieldarray, $where_claud);
                if ($n_rid !== 0) {
                    $message = '登入密碼已寄至您的信箱，請重新登入！';
                    $mtype = 'success';
                    $msuccess = true;
                } else {
                    $message = 'Email發送失敗！';
                }
            }
        } else {
            $message = '帳號或電子信箱輸入錯誤！';
        }
        /* if ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $n_rid = $result['user_id'];  // 使用者ID
            if ($n_rid !== 0) {
                $result = send_email_regist2($email, $n_rid, $mgo = "token=HanyuToken24982988&act=confirm_customer_mail&email=", $key, $iv);
                $message = $result ? '帳號確認信件已寄至您的信箱，請確認！' : 'Email發送失敗！';
                $mtype = 'success';
            } else {
                $message = "該 email 不存在!";
                $mtype = 'info';  //'error',"info","success","warning","question"
            }
            echo json_encode(['success' => true, 'type' => $mtype, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);
        } else {
            $message = "email 不存在!";
            $mtype = 'info';  //'error',"info","success","warning","question"
            echo json_encode(['success' => false, 'type' => $mtype, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);
        } */
        echo json_encode(['success' => $msuccess, 'type' => $mtype, 'rid' => $n_rid, 'message' => $message], JSON_UNESCAPED_UNICODE);

        exit;
    }
} else if (!empty($_REQUEST['logout']) and strtoupper($_REQUEST['logout']) == "Y") {
    session_unset();
    session_destroy(); //删除当前用户对应的session文件以及释放session	
}

?>

<!DOCTYPE html>
<html lang="zh-TW">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="assets/img/favicon.png" rel="icon">
    <title>海洋能及風能高速運算資料管理平台</title>
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="./assets/css/login.css">
    <!--  <link rel="stylesheet" href="assets/css/sweetalert2.min.css">  -->
    <script src="./assets/js/jquery-3.7.1.js"></script>

    <script src="./assets/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <!--   <script src="assets/js/sweetalert2.min.js"></script>
    <script src="./assets/js/SweetAlertBox.js"></script>  -->
    <script src="./assets/js/sweetalert2@11.js"></script>
    <script>
        $(document).ready(function() {
            // 當標籤被點擊時
            $('.tab-link').click(function(e) {
                e.preventDefault(); // 防止連結的預設行為

                // 移除所有標籤的 active 狀態
                $('.tab-link').removeClass('active');
                $('.tab-content').removeClass('active');

                // 為當前點擊的標籤增加 active 狀態
                var targetTab = $(this).data('tab'); // 取得 data-tab 屬性
                $('#' + targetTab).addClass('active');
                $(this).addClass('active');
            });
        });

        function showAlert1() {
            /*  swal({ */
            Swal.fire({
                title: '確認送出帳號申請',
                text: '資料確認正確，將送出申請',
                timer: 3000,
                confirmButtonText: '確 認'
                // type: 'success'
            });
        }

        function btn_send() {
            Swal.fire({
                title: '確認送出帳號申請',
                text: '資料確認正確，將送出申請',
                // timer: 3000,
                confirmButtonText: '確 認',
                customClass: {
                    title: 'swal2-title',
                    confirmButton: 'swal2-confirm'
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    // 當確認按鈕被點擊後，執行 chg_tab(3)
                    $("#form-register").submit();
                    chg_tab(3);
                }
            });
        }

        function chg_tab(mTab = 1) {
            var targetTab = "tab" + mTab;
            // 移除所有標籤的 active 狀態
            $('.tab-link,.tab-content').removeClass('active');
            // 根據 targetTab 顯示對應內容
            $('#' + targetTab).addClass('active');

            // 將對應的標籤加上 active 狀態
            $(`[data-tab=${targetTab}]`).addClass('active');

            // 如果是 tab3，顯示 tab3 並隱藏 tab2
            if (mTab === 3) {
                $(`[data-tab="tab2"]`).hide(); // 隱藏 tab2 的標籤
                $(`[data-tab="tab3"]`).show(); // 顯示 tab3 的標籤
            } else {
                // 其他情況下顯示 tab2 並隱藏 tab3
                $(`[data-tab="tab2"]`).show(); // 顯示 tab2 的標籤
                $(`[data-tab="tab3"]`).hide(); // 隱藏 tab3 的標籤
                chg_agree();
            }
        }
    </script>

    <style>
        /* 自定義 title 樣式 */
        .swal2-modal {
            width: 329px;
            /*  height: 224px; */
        }

        .swal2-title {
            margin-top: 20px;
            font-family: 'Microsoft JhengHei', sans-serif;
            font-size: 20px;
            font-weight: 700;
            line-height: 26.6px;
            letter-spacing: 0.05em;
            /*  text-align: left; */
        }

        /* 自定義 text 樣式 */
        #swal2-html-container {
            font-family: 'Microsoft JhengHei', sans-serif;
            font-size: 18px;
            font-weight: 290;
            line-height: 23.94px;
            letter-spacing: 0.05em;
            /* text-align: left; */
        }

        /* 自定義按鈕樣式 */
        .swal2-confirm {
            width: 124px;
            height: 45px;
            background-color: #0188C2;
        }
    </style>
</head>

<body>
    <div class="login-container">
        <div class="left-section">
            <div style="display: block;width: 420px;margin:20px auto 0;">
                <img style="top:20px;" src="./assets/img/國網中心logo3.png" />
            </div>
            <div class="head">
                海洋能及風能高速運算資料管理平台
            </div>

            <div class="contact-input">
                <div class="tabs">
                    <a href="#tab1" class="tab-link active" data-tab="tab1">帳號登入</a>
                    <a href="#tab2" class="tab-link" data-tab="tab2">帳號申請</a>
                    <a href="#tab3" class="tab-link" style="display: none;" data-tab="tab3">帳號申請完成</a>
                </div>
                <div class="tab-content m-auto active" id="tab1">
                    <form id="login-form" class="login-form " action="login.php" method="POST">
                        <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
                        <label for="account">帳號</label>
                        <input type="text" id="account" name="account" placeholder="登入帳號">
                        <label for="password">密碼</label>
                        <input type="password" id="password" name="password" placeholder="登入密碼">
                        <!--  <label for="captcha">驗證碼</label> -->
                        <div class="row m-2">
                            <!-- <div class="captcha-image" style="width: 50%;">
                                <img src="./assets/img/captcha.png" alt="驗證碼">
                            </div> -->
                            <div class="col-6 captcha-image" style="cursor: pointer;" tabindex="0" data-bs-trigger="hover focus" data-bs-toggle="popover" data-bs-placement="top" data-bs-content="可按圖片更換驗證碼">
                                <img id="verifyimage" class="verifyimage" src="captcha.php" alt="Captcha Image" alt="<?= $_SESSION['captcha'] ?? 'img'; ?>">
                            </div>
                            <div class="col-6">
                                <input style="width:100%;" type="text" id="Validate" name="validate" placeholder="驗證碼" required>

                            </div>
                        </div>
                        <div class="buttons">
                            <!-- <button type="button" onclick="showAlert1()" class="cancel">取消</button> -->
                            <button type="reset" class="cancel">取消</button>
                            <!--  <button type="submit" class="login">登入</button> -->
                            <button type="submit" id="saveButton" name="action" value="login" class="login">登入</button>
                        </div>
                        <div style="width: 100%;width: 100%;text-align: right;margin-top: 50px;">
                            <a href="#" class="forgot-password" data-bs-toggle="modal" data-bs-target="#uploadModal">忘記密碼</a>
                        </div>
                    </form>

                    <!-- <a href="#" class="forgot-password">忘記密碼</a> -->

                </div>
                <div class="tab-content" id="tab2">
                    <!-- <h2>帳號申請</h2> -->
                    <form id="form-register" class="login-form" action="login.php" method="POST">
                        <input type="hidden" id="csrfToken2" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
                        <label for="userNo"><code>*</code>帳號</label>
                        <input type="text" id="userNo" name="userNo" placeholder="登入帳號" required>
                        <label for="userPassword"><code>*</code>密碼</label>
                        <input type="password" id="userPassword" name="userPassword" placeholder="登入密碼" required>
                        <div style="display: flex;">
                            <div style="width: 45%;">
                                <label for="userName"><code>*</code>姓名</label>
                                <input type="text" id="userName" name="userName" style="width:145px;" placeholder="姓名">
                            </div>
                            <div style="float:right;right: 0;">
                                <label for="department">服務單位</label>
                                <input style="width:100%;" type="text" id="department" name="department"
                                    placeholder="服務單位名稱">
                            </div>
                        </div>
                        <label for="email"><code>*</code>電子信箱</label>
                        <input type="text" id="email" name="email" placeholder="example@abc.com.tw" required>
                        <div style="display: flex; margin-left: 1rem;">
                            <input type="checkbox" id="check_agree" style="width: 24px;" onchange="chg_agree()" />
                            <code>*</code>我已閱讀並同意隱私權保護
                        </div>

                        <div class="buttons" style="margin-top: 7%;">
                            <button class="cancel" type="reset">取消</button>
                            <!--  <button type="button" onclick="showAlert()" class="cancel">取消</button> -->
                            <!-- <button type="button" id="btn_register" onclick="btn_send()" class="login disabled" disabled>送出</button> -->
                            <button type="button" id="btn_register" name="action" value="register" class="login disabled" onclick="chkdata()">送出</button>

                        </div>
                    </form>
                </div>
                <div class="tab-content" id="tab3">
                    <form class="login-form">
                        <input type="hidden" id="mrid">

                        <h3>帳號申請完成</h3>
                        <label style="margin-top: 1.5rem;"> 您已完成帳號申請，我們已寄送驗證信至您的信箱，
                            請至信箱開啟信件驗證。</label>
                        <label style="color:#2973DB;margin-top: 1rem;">
                            沒有收到信件，點選<a href="#" id="send_again" onclick="sendEmail()">再寄一次</a>。
                        </label>

                        <div class="buttons" style="margin-top: 10%;margin-left: 50%;">
                            <button type="button" onclick="chg_tab(1)" class="login">關閉</button>
                        </div>
                    </form>
                </div>

            </div>

            <!-- Modal -->

            <div class="modal " id="uploadModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg modal-dialog-centered ">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h1 class="modal-title fs-5" id="exampleModalLabel">忘記密碼</h1>
                            <button type="button" class="btn-close bg-secondary" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <form action="" id="form_forget" method="POST">
                            <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
                            <div class="modal-body">
                                <div class="row mb-3">
                                    <label for="email" class="form-label col-md-2"><code>*</code>電子信箱</label>
                                    <div class="col-md-10">
                                        <input type="text" id="memail" class="form-control" name="memail" placeholder="example@abc.com.tw" required>
                                    </div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <table class="table ">
                                    <tr>
                                        <td> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button></td>
                                        <td><button type="button" id="btn_forgetPwd" class="btn btn-primary w-50" name="action" value="forgetPwd" onclick="sendForgetEmail()">送出</button>
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </form>
                    </div>
                </div>
            </div>



        </div>


        <div class="right-section" style="background-image: url(./assets/img/login_right.png);">
            <!-- style="background-image: url('assets/img/login_right.png');" -->
            <div class="welcome">WELCOME
                <p>歡迎使用本平台</p>
            </div>
            <div class="contact-info">
                <p>聯絡單位：XXX高效能運算中心</p>
                <p>聯絡信箱：XXXXX@XXXXX.com</p>
                <p>聯絡電話：0900-000000</p>
            </div>
            <div class="contact-info1">
                <table>
                    <tr>
                        <td style="width: 200px;">指導單位：</td>
                        <td style="width: 200px;">執行單位：</td>
                    </tr>
                    <tr>
                        <td>
                            <div class="logo"><img style="margin: 8px auto;" src="./assets/img/0125-國科會標誌組合2.png" />
                            </div>
                        </td>
                        <td>
                            <div class="logo1"><img style="margin: 8px auto;" src="./assets/img/國網中心logo3.png" /></div>
                        </td>
                    </tr>
                </table>
            </div>
        </div>
    </div>

    <div class="footer">
        <div class="footer-content" style="display: flex;">
            <p style="width: 55%;">隱私權保護 | 網站安全政策</p>
            <p style="width: 45%;">© 2024 國家風能數據管理實驗中心</p>
        </div>
    </div>
    <script>
        $(function() {
            //刷新驗證碼(改變圖片連結  連結成功後改Session並產生圖)
            $('.verifyimage').on('click', function() {
                var random = Math.random();
                $('.verifyimage').each(function() {
                    $(this).attr('src', 'captcha.php');
                });
            });
        });

        window.onload = function() {
            // 检查 PHP 变量是否包含错误消息
            var errorMessage = "<?php echo $error; ?>";
            console.log("errorMessage:", errorMessage);
            // 如果错误消息不为空，则显示警报消息
            if (errorMessage !== '') {
                if (errorMessage === '登入成功!') {
                    // 按下確定後跳轉到登入頁面
                    window.location.href = 'index.php';
                } else {
                    //  alert(errorMessage);
                    Swal.fire({
                        icon: 'error', //"info","success","warning","question"
                        title: errorMessage,
                        // text: errorMessage,                     
                        timer: 6000,
                        confirmButtonText: '確 認',
                    });
                }
            }
        };

        $(document).ready(function() {
            // $("#btn_register").prop("disabled", true);
            $('#saveButton').click(function(event) {
                var account = $('#account').val();
                var password = $('#password').val();
                var Validate = $('#Validate').val();

                // 檢查帳號是否為空
                if (account === '') {
                    alert('請輸入帳號');
                    event.preventDefault(); // 阻止表單提交
                    return;
                }

                // 檢查密碼是否為空
                if (password === '') {
                    alert('請輸入密碼');
                    event.preventDefault(); // 阻止表單提交
                    return;
                }

                // 檢查密碼是否至少包含 8 個字元
                if (password.length < 4) {
                    alert('密碼必須至少包含 4 個字元');
                    event.preventDefault(); // 阻止表單提交
                    return;
                }

                if (Validate === '') {
                    alert('請輸入驗證碼');
                    event.preventDefault(); // 阻止表單提交
                    return;
                }
                // 若通過所有檢查，表單將提交
            });
        });

        function chg_agree() {
            // 檢查 checkbox 是否被選取
            if ($("#check_agree").is(":checked")) {
                // 如果被勾選，移除按鈕的 disabled 類別，並啟用按鈕
                $("#btn_register").removeClass("disabled").prop("disabled", false);
            } else {
                // 如果未被勾選，添加按鈕的 disabled 類別，並禁用按鈕
                $("#btn_register").addClass("disabled").prop("disabled", true);
            }
        }

        function chkdata() {
            // 確保所有必填欄位都有值
            var name = $('#userName').val().trim();
            var account = $('#userNo').val().trim();
            var email = $('#email').val().trim();
            var password = $('#userPassword').val().trim();
            var unit = $('#department').val().trim();
            //var csrfToken = $('input[name="csrfToken"]').val();
            var csrfToken = $('#csrfToken2').val();

            // 驗證所有字段是否已填寫
            if (!name || !account || !email || !password) {
                alert('請填寫所有*必填字段');
                return;
            }

            // 驗證電子郵件格式
            var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(email)) {
                alert("請輸入有效的電子郵件地址！");
                return false;
            }
            // 如果所有檢查都通過，提交表單
            // $('#form1').submit();
            // 如果所有驗證都通過,提交表單
            $.ajax({
                url: '', // 留空表示提交到當前頁面
                method: 'POST',
                data: {
                    name: name,
                    account: account,
                    email: email,
                    password: password,
                    unit: unit,
                    csrfToken: csrfToken,
                    action: 'register'
                },
                success: function(response) {
                    var res;
                    if (typeof response === "string") {
                        try {
                            res = JSON.parse(response); // 嘗試將字串轉換為物件
                        } catch (e) {
                            console.error("JSON 解析失敗：", e, response);
                            return;
                        }
                    } else {
                        res = response; // 如果已經是物件，直接使用
                    }
                    // 輸出檢查結果
                    console.log('[chkdata] res=>', res);
                    $("#mrid").val(res.rid);
                    Swal.fire({
                        title: '帳號申請',
                        icon: res.type,
                        text: res.message,
                        timer: 3000,
                        confirmButtonText: '確 認',
                        customClass: {
                            title: 'swal2-title',
                            confirmButton: 'swal2-confirm'
                        }
                    }).then((result) => {
                        if (result.isConfirmed && res.rid > 0) {
                            chg_tab(3);
                        }
                    });
                    // 處理成功響應
                    // alert('註冊成功!');
                    //   window.location.href = 'login.php'; // 重定向到登錄頁面
                },
                error: function(xhr, status, error) {
                    // 處理錯誤
                    alert('註冊失敗: ' + error);
                }
            });
        }


        function sendEmail() {
            var mrid = $('#mrid').val().trim();
            var email = $('#email').val().trim();

            // 驗證所有字段是否已填寫
            if (!email || !mrid) {
                alert('資料不完整!');
                return;
            }

            $.ajax({
                url: '', // 留空表示提交到當前頁面
                method: 'POST',
                data: {
                    rid: mrid,
                    email: email,
                    action: 'register_email'
                },
                success: function(response) {
                    var res;
                    if (typeof response === "string") {
                        try {
                            res = JSON.parse(response); // 嘗試將字串轉換為物件
                        } catch (e) {
                            console.error("JSON 解析失敗：", e, response);
                            return;
                        }
                    } else {
                        res = response; // 如果已經是物件，直接使用
                    }
                    // 輸出檢查結果
                    console.log('[chkdata] res=>', res, response);
                    $("#mrid").val(res.rid);
                    Swal.fire({
                        title: '信件寄送',
                        text: res.message,
                        timer: 3000,
                        confirmButtonText: '確 認',
                        customClass: {
                            title: 'swal2-title',
                            confirmButton: 'swal2-confirm'
                        }
                    });
                },
                error: function(xhr, status, error) {
                    // 處理錯誤
                    alert('註冊失敗: ' + error);
                }
            });
        }

        function sendForgetEmail() {

            var email = $('#memail').val().trim();
            var csrfToken = $('#csrfToken2').val();
            // 驗證所有字段是否已填寫
            if (!email) {
                alert('資料不完整!');
                return;
            }
           $("#btn_forgetPwd").hide();
            $.ajax({
                url: '', // 留空表示提交到當前頁面
                method: 'POST',
                data: {
                    csrfToken: csrfToken,
                    memail: email,
                    action: 'forgetPwd'
                },
                success: function(response) {
                    console.log('[uploadModal] response=>',  response);
                    var res;
                    if (typeof response === "string") {
                        try {
                            res = JSON.parse(response); // 嘗試將字串轉換為物件
                        } catch (e) {
                            console.error("JSON 解析失敗：", e, response);
                            return;
                        }
                    } else {
                        res = response; // 如果已經是物件，直接使用
                    }
                    // 輸出檢查結果
                    console.log('[uploadModal] res=>', res, response);

                    Swal.fire({
                        title: '信件寄送',
                        text: res.message,
                        timer: 3000,
                        confirmButtonText: '確 認',
                        customClass: {
                            title: 'swal2-title',
                            confirmButton: 'swal2-confirm'
                        }
                    }).then((result) => {
                        $('#uploadModal').modal('hide');
                    });
                },
                error: function(xhr, status, error) {
                    // 處理錯誤
                    alert('失敗: ' + error);
                }
            });
        }
    </script>

</body>

</html>