<?php
include_once 'src/inc/db/function.php';
include_once("sendEmail.php");

$error = '';
if (isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    if ($_POST['action'] == 'register') {
        // 驗證 CSRF 令牌
        if (!isset($_POST['csrfToken']) || $_POST['csrfToken'] !== $_SESSION['csrfToken']) {
            die('CSRF 令牌驗證失敗');
        }
        // 獲取並清理輸入數據
        $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 = "";
        // 驗證輸入
        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 0,1");
        $stmt->execute([$account, $email]);
        if ($stmt->fetchColumn() > 0) {
            // die('該帳號已被使用');
            $message = "該帳號已被使用";
        }
        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發送失敗！';
                } else {
                    $message = '註冊失敗！';
                }
                // 註冊成功
                echo json_encode(['success' => true, 'message' => $message]);
            } catch (PDOException $e) {
                // 註冊失敗
                echo json_encode(['success' => false, 'message' => '註冊失敗: ' . $e->getMessage()]);
            }
        } else {
            echo json_encode(['success' => false, 'message' => $message]);
        }
        exit;
        /*
        $name = isset($_POST['name']) && $_POST['name'] !== '' ? htmlspecialchars(trim($_POST['name']), ENT_QUOTES, 'UTF-8') : null;
        $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;
        $email = isset($_POST['email']) && $_POST['email'] !== '' ? htmlspecialchars(trim($_POST['email']), ENT_QUOTES, 'UTF-8') : null;
        $unit = isset($_POST['unit']) && $_POST['unit'] !== '' ? htmlspecialchars(trim($_POST['unit']), ENT_QUOTES, 'UTF-8') : null;
        $Npassword = isset($_POST['Npassword']) && $_POST['Npassword'] !== '' ? htmlspecialchars(trim($_POST['Npassword']), ENT_QUOTES, 'UTF-8') : null;
        if ($password !== $Npassword) {
            $error = '密碼不一致！';
        } else {
            $sql = "Select userNo FROM users WHERE userNo = ? OR email = ? ";
            $stmt = $conn->prepare($sql);
            $stmt->execute([$account, $email]);
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($result) {
                $error = '此帳號或電子信箱已存在！';
            } else {
                $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);
                $where_claud = "rid= $n_rid";
                if ($n_rid !== 0) {
                    $result = send_email_regist2($email, $n_rid, $mgo = "token=HanyuToken24982988&act=confirm_customer_mail&email=", $key, $iv);
                    $error = $result ? '帳號確認信件已寄至您的信箱，請確認！' : 'Email發送失敗！';
                } else {
                    $error = '註冊失敗！';
                }
            }
        }
            */
    } else {
        $error = '請重新輸入！';
    }
}

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

<head>
    <meta charset="utf-8">
    <meta content="width=device-width, initial-scale=1.0" name="viewport">

    <title>海洋能及負碳高速運算資料管理平臺</title>
    <meta content="" name="description">
    <meta content="" name="keywords">

    <!-- Favicons -->
    <link href="assets/img/favicon.png" rel="icon">
    <link href="assets/img/apple-touch-icon.png" rel="apple-touch-icon">

    <!-- Google Fonts -->
    <link href="fonts/fonts.css" rel="stylesheet">
    <!-- Vendor CSS Files -->
    <link href="assets/vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="assets/vendor/bootstrap-icons/bootstrap-icons.css" rel="stylesheet">

    <!-- Template Main CSS File -->
    <link href="assets/css/style.css" rel="stylesheet">
    <script src="assets/js/jquery-3.7.1.js"></script>
    <script src="assets/js/jquery.blockUI.js"></script>

    <script>
        //註冊ajax觸發就show blockUI
        $(document).ajaxStart(function() {
            $.blockUI({
                // message: '<h3> 請稍候...</h3>',
                message: '<img src="assets/img/wait.gif" alt="Please wait..." style="height:120px;" />',
                timeout: 60000, //超時時間：60秒
            });
        }).ajaxStop($.unblockUI);

        /* setInterval(function() {
            $.get('/Home/KeepSessionAlive');
        }, 600000); // 每 300000 毫秒（即 5 分鐘）發送一次請求
         */


        window.onload = function() {
            // 检查 PHP 变量是否包含错误消息
            var errorMessage = "<?php echo $error; ?>";
            // 如果错误消息不为空，则显示警报消息
            if (errorMessage !== '') {
                alert(errorMessage);
                // 如果訊息內容是註冊成功
                if (errorMessage === '帳號確認信件已寄至您的信箱，請確認！') {
                    // 按下確定後跳轉到登入頁面
                    window.location.href = 'login.php';
                }
            }
        };
    </script>

    <style>
        body {
            background-color: #f5faed;
        }

        .container {
            display: flex;
            min-height: 100vh;
            flex-direction: column;
            justify-content: space-between;
        }

        .main-content {
            display: flex;
            justify-content: center;
            align-items: center;
            flex-grow: 1;
        }

        .login-form {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            width: 100%;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="main-content">
            <form method="POST" action="" class="mt-4 mb-4" id="form1" enctype="multipart/form-data">
                <div class="login-form">
                    <input type="hidden" name="csrfToken" value="<?php echo htmlspecialchars($_SESSION['csrfToken'], ENT_QUOTES, 'UTF-8'); ?>">
                    <h2 class="mb-3 fw-normal text-center" style="color: #323e35;">帳號註冊</h2>

                    <div class="row mb-8">
                        <label class="col-md-2 col-form-label">姓名</label>
                        <div class="col-md-4"></div>
                        <label class="col-md-2 col-form-label">帳號</label>
                    </div>

                    <div class="row mb-12">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="name" name="name" placeholder="姓名" required>
                        </div>
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="account" name="account" placeholder="帳號" required>
                        </div>
                    </div>
                    <br>

                    <div class="row mb-8">
                        <label class="col-md-3 col-form-label">電子信箱</label>
                        <div class="col-md-3"></div>
                        <label class="col-md-2 col-form-label">密碼</label>
                    </div>

                    <div class="row mb-6">
                        <div class="col-md-6">
                            <input type="email" class="form-control" id="email" name="email" placeholder="電子信箱" required>
                        </div>
                        <div class="col-md-6">
                            <input type="password" class="form-control" id="password" name="password" placeholder="密碼" required>
                        </div>
                    </div>
                    <br>

                    <div class="row mb-8">
                        <label class="col-md-4 col-form-label">服務單位</label>
                        <div class="col-md-2"></div>
                        <label class="col-md-4 col-form-label">再次輸入密碼</label>
                    </div>

                    <div class="row mb-6">
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="unit" name="unit" placeholder="服務單位" required>
                        </div>
                        <div class="col-md-6">
                            <input type="password" class="form-control" id="Npassword" name="Npassword" placeholder="再次輸入密碼" required>
                        </div>
                    </div>
                    <br>

                    <div class="row mb-6">
                        <div class="col-md-6"></div>
                        <div class="col-md-4">
                            <a> ● 隱私權政策</a>
                        </div>
                    </div>
                    <br>
                    <br>
                    <div class="row text-center">
                        <div class="col-6">
                            <a class="btn btn-secondary w-100" id="cancelButton" href="login.php" role="button">取消</a>
                        </div>
                        <div class="col-6">
                            <button type="button" id="saveButton" name="action" value="register" class="btn btn-primary w-100" onclick="chkdata()">送出</button>

                            <!-- <button type="submit" id="saveButton" name="action" value="register" class="btn btn-primary w-100">送出</button> -->
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <footer id="footer" style="background-color: #f1f1f1; font-size: 12px; padding: 10px 0;">
        <div class="row">
            <!-- 左側內容 -->
            <div class="col-12 col-md-4 mb-3 mb-md-0" style="text-align: left;">
                <br>
                <div style="font-weight: bold; margin-bottom: 5px;">
                    海洋能及負碳高速運算資料管理平臺
                </div>
                <div>指導單位：</div>
                <div>執行單位：</div>
            </div>
            <!-- 中間內容 -->
            <div class="col-12 col-md-4 mb-3 mb-md-0">
                <br>
                <br>
                <div style="text-align: left; padding-left: 10px; border-left: 1px dashed #000;">
                    <div>聯絡單位：</div>
                    <div>聯絡信箱：</div>
                    <div>執行電話：</div>
                </div>
            </div>
            <!-- 右側內容 -->
            <div class="col-12 col-md-4">
                <div class="row mb-3">
                    <div class="col-3">
                        <button>平台簡介</button>
                    </div>
                    <div class="col-3">
                        <button>執行團隊</button>
                    </div>
                    <div class="col-5">
                        <a>隱私權保護</a>
                        <a>網站安全政策</a>
                    </div>
                </div>
                <br>
                <br>
                <div>© 2024 財團國家實驗研究院國家高速網路與計算中心</div>
            </div>
        </div>
    </footer>


    <script>
        $(document).ready(function() {

        });

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

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

            // if (name === "" || account === "" || email === "" || password === "" || Npassword === "" || unit === "") {
            //     alert("所有欄位都是必填的，請填寫完整！");
            //     return false;
            // }

            // 確認兩次密碼一致
            if (password !== Npassword) {
                alert("兩次輸入的密碼不一致！");
                return false;
            }
            // 驗證電子郵件格式

            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) {
                    // 處理成功響應
                    alert('註冊成功!');
                    window.location.href = 'login.php'; // 重定向到登錄頁面
                },
                error: function(xhr, status, error) {
                    // 處理錯誤
                    alert('註冊失敗: ' + error);
                }
            });


        }
    </script>

</body>

</html>