<?php
include_once 'src/inc/db/function.php';
check_login();
$error = $_REQUEST['msg']??'';
$userId = $_SESSION['Nchc_userId'] ?? 0; // 假設使用者ID存在 session 中
if ($userId > 0) {
  if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {
    $mcsrfToken = $_POST['csrfToken'] ?? null;
    if ($mcsrfToken != $_SESSION['csrfToken']) {
      echo "<script>alert('驗證碼錯誤。');</script>";
      exit;
    }

    $n_rid = false;
    if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] === 'update') {
      $name = filter_input(INPUT_POST, 'userName');
      $email = filter_input(INPUT_POST, 'email');
      $unit = filter_input(INPUT_POST, 'department');
      if (!empty($name) && !empty($email) && !empty($unit)) {
        $fieldarray = array(
          'userName' => $name,
          'email' => $email,
          'department' => $unit,
          'update_date' => $now,
          'updated_by' => $userId
        );
        $where_claud = "user_id= $userId ";
        $n_rid = update_data("users", $fieldarray, $where_claud);
        if ($n_rid === true) {
          $error = '更新成功!';
        } else {
          $error = "更新失敗，請稍後再試。" . $n_rid;
        }
      } else {
        // print_r($_POST);
        $error = '欄位不可空白!';
      }
      unset($_POST); // 清除整個 $_POST 陣列
    } else if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['action']) && $_POST['action'] === 'change') {
      // 取得表單資料
      // $userId = $_SESSION['Nchc_userId']; // 假設使用者ID存在 session 中
      $sql = "SELECT * FROM users  WHERE user_id = ? and userStatus='Y' LIMIT 1;";
      $stmt = $conn->prepare($sql);
      $stmt->execute([$userId]);
      $result = $stmt->fetch(PDO::FETCH_ASSOC);  // 使用 FETCH_ASSOC 返回關聯數組
      if ($result != null) {
        $currentPassword = $_POST['password'];
        $newPassword = $_POST['newpassword'];
        $dbPassword = $result['userPassword']; // 取得密碼

        // 驗證當前密碼是否正確
        if (password_verify($currentPassword, $dbPassword)) {
          $mhsah = password_hash($newPassword, PASSWORD_DEFAULT);
          $fieldarray = array(
            'userPassword' => $mhsah,
            'update_date' => date("Y-m-d H:i:s"),
            'updated_by' => 'userInfo'
          );
          $where_claud = "user_id= $userId ";
          $n_rid = update_data("users", $fieldarray, $where_claud);
          if ($n_rid === true) {
            $error = '密碼變更成功!';
          } else {
            $error = "密碼更新失敗!";
          }
        } else {
          $error = "[舊密碼] 錯誤!";
        }
      } else {
        $error =  "更新失敗!";
      }
      unset($_POST); // 清除整個 $_POST 陣列
    }

 //  echo "<script>alert('{$error}');location.replace('userInfo.php');</script>"; 
  //  echo '<script>location.replace("userInfo.php");</script>';
    header("Location: userInfo.php?msg={$error}");
    exit();
  }
  // $sql = "SELECT userNo,userName,email,phone,department FROM users  WHERE user_id = ? and userStatus='Y' LIMIT 0, 1;";
  $sql = "SELECT * FROM users  WHERE user_id = ? and userStatus='Y' LIMIT 1;";
  try {
    $stmt = $conn->prepare($sql);
    $stmt->execute([$userId]);
    // $result = $stmt->fetch();
    // 取得資料並轉換為關聯陣列
    $result = $stmt->fetch(PDO::FETCH_ASSOC);  // 使用 FETCH_ASSOC 返回關聯數組
    if ($result != null) {
      /*
      $result1 = [
        "userNo" => $result["userNo"],
        "userName" => $result["userName"],
        "email" => $result["email"],
        "phone" => $result["phone"],
        "department" => $result["department"]
      ];
      $jsonResult = json_encode($result1); // 將資料轉換為 JSON
      // print_r($jsonResult);
     */
    }
  } catch (PDOException $e) {
    // return $e;
    echo "try錯誤。" . $e;
  }
}
unset($_REQUEST);
//echo "result=>" . $result;

?>
<!DOCTYPE html>

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

  <!-- <title>帳號基本資料</title> -->
  <?php include_once "template_css.php"; ?>

  <script>
    $(document).ready(function() {
      var errorMessage = "<?= $error; ?>";
      // 如果错误消息不为空，则显示警报消息
      if (errorMessage !== '') {
        alert(errorMessage);
      }
      $('#changeButton').click(function(event) {
        var currentPassword = $('#currentPassword').val();
        var newPassword = $('#newPassword').val();
        var renewPassword = $('#renewPassword').val();

        // 檢查新密碼是否一致
        if (newPassword !== renewPassword) {
          alert('新密碼與再次輸入的新密碼不一致');
          event.preventDefault(); // 阻止表單提交
          return;
        }

        // 檢查新密碼是否符合條件 (例如：最少 8 個字元)
        if (newPassword.length < 4) {
          alert('新密碼必須至少包含 4 個字元');
          event.preventDefault(); // 阻止表單提交
          return;
        }

        // 其他可以加入的驗證，例如包含數字、特殊字符等
      });

      /*
            var jsonData = <?= $jsonResult ?? '' ?>;
            console.log("jsonData", jsonData)      
            $("#form1 input").each(function() {// 迭代 #form1 中的所有 input 元素
              var inputId = $(this).attr('id'); // 取得 input 元素的 id
              if (jsonData[inputId]) { // 如果 jsonData 中有對應的 id
                $(this).val(jsonData[inputId]); // 將 input 的值設置為對應的 JSON 值
              }
            });
      */
    });
  </script>

  <style>
    .custom-label {
      background-color: #f0f0f0;
      /* 灰色背景 */
      text-align: right;
      /* 文字靠右 */
      padding: 10px;
      /* 增加內邊距，讓文字與邊緣保持距離 */
      display: block;
      /* 確保 label 佔據整個父元素的寬度 */
    }

    .table1 th {
      color: #505F8A;
      background-color: #ECF1FF;
      text-align: right;
      width: 150px;
      height: 60px;
      border-bottom: 4px solid #f6f9ff;
      padding-right: 10px;
    }

    .table1 td {
      padding-left: 10px;
    }
  </style>
</head>

<body>
  <!--BEGIN HEADER-->
  <?php include_once "template_header.php"; ?>
  <!--END HEADER-->

  <!--BEGIN SIDEBAR-->
  <?php include_once "template_sidebar.php"; ?>
  <!--END SIDEBAR-->

  <main id="main" class="main">
    <div class="pagetitle d-flex  justify-content-between align-items-center">
      <nav>
        <ol class="breadcrumb">
          <li class="breadcrumb-item "><a href="index.php"><i class="bi bi-house-door-fill"></i> 首頁</a></li>
          <li class="breadcrumb-item active">帳號基本資料</li>
        </ol>
      </nav>
      <span class="float: right;">
        <a href="index.php" class="btn btn-sm  btn-outline-primary"><i class="bi bi-arrow-90deg-left"></i> 回上一頁</a>
      </span>
    </div>
    <div class="d-flex align-items-center">
      <div class="head-line" style="width:80px;"></div>
      <span class="head-title mx-2 ">帳號基本資料</span>
      <div class="head-line " style="flex-grow: 1;"> </div>
    </div>
    <section class="section" style="max-width:1280px;">
      <ul class="nav nav-tabs nav-justified ">
        <li class="nav-item">
          <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#profile-overview">帳號基本資料</button>
        </li>
        <li class="nav-item">
          <button class="nav-link" data-bs-toggle="tab" data-bs-target="#profile-change-password">變更密碼</button>
        </li>
      </ul>
      <div class="tab-content pt-2">
        <div class="tab-pane fade show active profile-overview" id="profile-overview">

          <form method="POST" action="" class="mt-4 mb-4" id="form1" enctype="multipart/form-data">
            <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?>">
            <table class="table1 mt-4">
              <tr>
                <th><label class="form-label">帳號</label></th>
                <td style="width:320px;">
                  <div class="form-input"><?= $result["userNo"] ?? 'ABC'; ?>
              </tr>
              <tr>
                <th><label class="form-label">姓名</label></th>
                <td><input type="text" id="userName" name="userName" class="form-control form-input" value="<?= $result["userName"] ?? ''; ?>" placeholder="陳小明"></td>
              </tr>
              <tr>
                <th> <label class="form-label">電子信箱</label></th>
                <td> <input type="email" id="email" name="email" class="form-control form-input" value="<?= $result["email"] ?? ''; ?>" placeholder="sample@gmail.com"></td>
              </tr>
              <tr>
                <th> <label class="form-label">服務單位</label></th>
                <td><input type="text" id="department" name="department" class="form-control form-input" value="<?= $result["department"] ?? ''; ?>" placeholder="xxx"></td>
              </tr>
              <tr>
                <td class="text-center" colspan="2">
                  <button type="submit" id="saveButton" name="action" value="update" class="btn btn-info">
                    儲存
                  </button>
                </td>
              </tr>
            </table>

          </form>
        </div>

        <div class="tab-pane fade pt-3" id="profile-change-password">

          <form method="POST" action="" class="mt-4 mb-4" id="form_Pwd">
            <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?>">
            <table class="table1 mt-4">
              <tr>
                <th><label class="form-label">舊密碼</label></th>
                <td style="width:320px;"><input name="password" type="password" class="form-control" id="currentPassword" required></td>
              </tr>
              <tr>
                <th> <label class="form-label">新密碼</label></th>
                <td><input name="newpassword" type="password" class="form-control" id="newPassword" required></td>
              </tr>
              <tr>
                <th> <label class="form-label">再次輸入新密碼</label></th>
                <td><input name="renewpassword" type="password" class="form-control" id="renewPassword" required></td>
              </tr>
              <tr>
                <td class="text-center" colspan="2">
                  <button type="submit" id="changeButton" name="action" value="change" class="btn btn-info">
                    變更密碼
                  </button>
                </td>
              </tr>
            </table>

          </form>

        </div>
      </div>
    </section>
    <!--  <section class="section dashboard">
      <div class="card">
        <div class="card-body pt-3">

          <ul class="nav nav-tabs nav-tabs-bordered">
            <li class="nav-item">
              <button class="nav-link active" data-bs-toggle="tab" data-bs-target="#profile-overview">帳號基本資料</button>
            </li>

            <li class="nav-item">
              <button class="nav-link" data-bs-toggle="tab" data-bs-target="#profile-change-password">變更密碼</button>
            </li>
          </ul>
          <div class="tab-content pt-2">
            <div class="tab-pane fade show active profile-overview" id="profile-overview">

              <form method="POST" action="" class="mt-4 mb-4" id="form1" enctype="multipart/form-data">
                <input type="hidden" name="csrfToken1" value="<?php echo htmlspecialchars($_SESSION['csrfToken'], ENT_QUOTES, 'UTF-8'); ?>">

                <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?>">

                <div class="row mb-3">
                  <div class="col-lg-3 col-md-4 custom-label ">帳號</div>
                  <div class="col-lg-9 col-md-8">
                    <input type="text" class="form-control" id="userNo" name="userNo" value="" required>
                  </div>
                </div>

                <div class="row mb-3">
                  <div class="col-lg-3 col-md-2 custom-label">姓名</div>
                  <div class="col-lg-9 col-md-4">
                    <input type="text" class="form-control" id="userName" name="userName" value="" required>
                  </div>
                </div>

                <div class="row mb-3">
                  <div class="col-lg-3 col-md-2 custom-label">電子信箱</div>
                  <div class="col-lg-9 col-md-4">
                    <input type="text" class="form-control" id="email" name="email" value="">
                  </div>
                </div>

                <div class="row mb-3">
                  <div class="col-lg-3 col-md-2 custom-label">服務單位</div>
                  <div class="col-lg-9 col-md-4">
                    <input type="text" class="form-control" id="department" name="department" value="">
                  </div>
                </div>

                <div class="text-center">
                  <button type="submit" id="saveButton" name="action" value="update" class="btn btn-info">
                    儲存
                  </button>
                </div>
              </form>
            </div>

            <div class="tab-pane fade pt-3" id="profile-change-password">

              <form method="POST" action="" class="mt-4 mb-4" id="form_Pwd" enctype="multipart/form-data">
                <input type="hidden" name="csrfToken" value="">
                <div class="row mb-3">
                  <label for="currentPassword" class="col-md-4 col-lg-3 col-form-label">舊密碼</label>
                  <div class="col-md-8 col-lg-9">
                    <input name="password" type="password" class="form-control" id="currentPassword" required>
                  </div>
                </div>

                <div class="row mb-3">
                  <label for="newPassword" class="col-md-4 col-lg-3 col-form-label">新密碼</label>
                  <div class="col-md-8 col-lg-9">
                    <input name="newpassword" type="password" class="form-control" id="newPassword" required>
                  </div>
                </div>

                <div class="row mb-3">
                  <label for="renewPassword" class="col-md-4 col-lg-3 col-form-label">再次輸入新密碼</label>
                  <div class="col-md-8 col-lg-9">
                    <input name="renewpassword" type="password" class="form-control" id="renewPassword" required>
                  </div>
                </div>

                <div class="text-center">
                  <button type="submit" id="changeButton" name="action" value="change" class="btn btn-info">
                    變更密碼
                  </button>
                </div>
              </form>

            </div>
          </div>
        </div>
      </div>
     
    </section> -->

  </main>

  <!--BEGIN FOOTER-->
  <?php include_once "template_footer.php"; ?>
  <!--END FOOTER-->

</body>


</html>