<?php
include_once '../src/inc/db/function.php';
// 檢查表單是否提交
$user_id = 0;
$mact = "新增";
$now = date("Y-m-d H:i:s"); // 獲取當前時間
$mremoveDay = date("Y-m-d", strtotime($today . " +1 years"));
$file_names = [];
$error = "";
//print_r($_REQUEST);
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_REQUEST['action']) && !empty($_REQUEST['action'])) {

  $mcsrfToken = $_POST['csrfToken'] ?? null;
  if ($mcsrfToken != $_SESSION['csrfToken']) {
    echo "<script>alert('驗證碼錯誤。');</script>";
    exit;
  }

  if ($_REQUEST['action'] == "Delete" && isset($_POST['user_id']) && $_POST['user_id'] > 0) {

    // 如果有 user_id，則進行更新
    $mrid = intval($_POST['user_id']);  // 使用 intval() 轉換為整數，防止 SQL 注入

    $sql = "DELETE FROM users WHERE user_id = :mrid";
    $stmt = $conn->prepare($sql);
    $stmt->bindValue(':mrid', $mrid);

    // 執行刪除並檢查結果
    if ($stmt->execute()) {
      // 刪除成功後，跳轉到公告列表頁面
      header('Location: users_list.php');
      exit;
    } else {
      echo "<script>alert('刪除操作失敗，請再試一次。'); window.location.href = 'users_list.php';</script>";
    }
    exit;
  }

  if (isset($_POST['user_id']) && $_POST['user_id'] > 0) {
    // 如果有 user_id，則進行更新
    $res = Users_Update($_POST);
    if ($res) {
      header('Location: users_list.php');
    } else {
      echo "<script>alert('更新失敗。');</script>";
    }
  } else {
    $account = filter_input(INPUT_POST, 'userNo');
    $email = filter_input(INPUT_POST, 'email');
    $message = "";
    $res=false;
    $stmt = $conn->prepare("SELECT * FROM users WHERE userNo = ? OR email = ? limit 1");
    $stmt->execute([$account, $email]);
    if ($stmt->fetch(PDO::FETCH_ASSOC)) {
      $message = "該帳號或 email 已存在!";
    } else {
     // print_r($_POST);
       $res = Users_Insert($_POST);
    }  
   
    if ($res) {
      header('Location: users_list.php');
    } else {
      echo "<script>alert('新增失敗。{$message}');</script>";
    }
  }
}

if (isset($_REQUEST['rid']) && $_REQUEST['rid'] > 0) {
  $mact = "修改";
  $user_id = $_REQUEST['rid'];

  // 從資料庫中讀取詳細資料
  $sql = "SELECT * FROM users WHERE user_id = :user_id";
  $stmt = $conn->prepare($sql);
  $stmt->bindParam(':user_id', $user_id);
  $stmt->execute();
  $data = $stmt->fetch(PDO::FETCH_ASSOC);

  if (!$data) {
    echo "<script>alert('資料不存在！'); window.location.href = 'users_list.php';</script>";
    exit;
  }
}
?>
<!DOCTYPE html>

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

  <!-- <title>帳號管理  </title> -->

  <?php include_once "admin_css.php"; ?>
  <!-- Change Password -->
  <script>
    window.onload = function() {
      // 检查 PHP 变量是否包含错误消息
      var errorMessage = "<?php echo $error; ?>";
      // 如果错误消息不为空，则显示警报消息
      if (errorMessage !== '') {
        alert(errorMessage);
      }
    };

    function escapeHtml(unsafe) {
      return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
    }

    $(document).ready(function() {

      if ($("#rid").val() > 0) { // 如果是修改模式
        $("#saveButton").val("update");
        $("#deleteButton").css("display", "block");
      } else { // 如果是新增模式
        $("#saveButton").val("insert");
        $("#deleteButton").css("display", "none");
      }

    });
  </script>
</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"><a href="users_list.php">帳號管理</a></li>
          <li class="breadcrumb-item active"><?= $mact ?></li>
        </ol>
      </nav>
      <span class="float: right;">
        <a href="#" onclick="window.history.back();" 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 dashboard">
      <div class="card card-body">
        <form method="POST" action="" class="mt-2 mb-4" id="form1" enctype="multipart/form-data">
          <input type='hidden' id="rid" name='user_id' value='<?= $user_id ?>'>
          <input type="hidden" name="csrfToken" value="<?= $_SESSION['csrfToken'] ?? '' ?>">
          <div class="row mb-3">
            <label for="userNo" class="form-label col-md-2">帳號</label>
            <div class="col-md-4">
              <input type="text" class="form-control" id="userNo" name="userNo" value="<?php echo htmlspecialchars($data['userNo'] ?? ''); ?>" required>
            </div>
            <label for="userName" class="form-label col-md-2">姓名</label>
            <div class="col-md-4">
              <input type="text" class="form-control" id="userName" name="userName" value="<?php echo htmlspecialchars($data['userName'] ?? ''); ?>" required>
            </div>
          </div>
          <div class="row mb-3">
            <label for="email " class="form-label col-md-2">電子信箱</label>
            <div class="col-md-10">
              <input type="email" class="form-control" id="email" name="email" value="<?php echo htmlspecialchars($data['email'] ?? ''); ?>" placeholder="name@example.com" required>
            </div>
          </div>
          <div class="row mb-3">
            <label for="department" class="form-label col-md-2">服務單位</label>
            <div class="col-md-4">
              <input type="text" class="form-control" id="department" name="department" value="<?php echo htmlspecialchars($data['department'] ?? ''); ?>">
            </div>
            <label for="userStatus" class="form-label col-md-2">啟用狀態</label>
            <div class="col-md-4">
              <select class="form-select" id="userStatus" name="userStatus">
                <option value="Y" <?php echo (isset($data['userStatus']) && $data['userStatus'] == 'Y') ? 'selected' : ''; ?>>是</option>
                <option value="N" <?php echo (isset($data['userStatus']) && $data['userStatus'] == 'N') ? 'selected' : ''; ?>>否</option>
                <option value="D" <?php echo (isset($data['userStatus']) && $data['userStatus'] == 'D') ? 'selected' : ''; ?>>停用</option>
              </select>
            </div>
          </div>
          <div class="row mb-3">
            <label for="userRole" class="form-label col-md-2">帳號權限</label>
            <div class="col-md-4">
              <select class="form-select" id="userRole" name="userRole">
                <option value="user" <?php echo (isset($data['userRole']) && $data['userRole'] == 'user') ? 'selected' : ''; ?>>使用者</option>
                <option value="admin" <?php echo (isset($data['userRole']) && $data['userRole'] == 'admin') ? 'selected' : ''; ?>>管理者</option>
              </select>
            </div>
            <?php if ($user_id > 0) { ?>
              <label for="create_date" class="form-label col-md-2">申請日期</label>
              <div class="col-md-4">
                <?php echo $data['create_date'] ?? $today; ?>
              </div>
            <?php } else { ?>
              <label for="userPassword" class="col-md-2 col-form-label">密碼</label>
              <div class="col-md-4">
                <input type="password" class="form-control" id="userPassword" name="userPassword" required>
              </div>
            <?php } ?>
          </div>
          <div class="row mb-3">
            <label for="startDay" class="form-label col-md-2">啟用日期</label>
            <div class="col-md-4">              
              <input type="date" class="form-control" id="startDay" name="startDay" value="<?= $data['startDay'] ?? '' ?>" required>
            </div>
            <label for="endDay" class="form-label col-md-2">停用日期</label>
            <div class="col-md-4">
              <input type="date" class="form-control" id="endDay" name="endDay" value="<?= $data['endDay'] ?? ''; ?>">
            </div>
          </div>
          <div class="row ">
            <div class="col-md-3">
              <a class="btn btn-secondary w-50" id="cancelButton" href="users_list.php" role="button">取消</a>
            </div>
            <div class="col-md-3">
              <!-- <button type="button" id="deleteButton" name="btn_del" class="btn btn-danger w-50" onclick="deleteUser();">
                刪除
              </button> -->
            </div>
            <div class="col-md-6 text-center">
              <button type="submit" id="saveButton" name="action" value="<?= $mact ?>" class="btn btn-primary w-50">
                <?= $mact ?>存檔
              </button>
            </div>
          </div>
        </form>
      </div>


      <!-- <div class="card info-card sales-card">
        <div class="card-body">
          <form method="POST" action="" class="mt-4 mb-4" id="form1">
            <input type="hidden" id="act" name="act" value="" />
            <input type='hidden' id="rid" name='rid' value=''>
            <input type="hidden" name="csrfToken" value="">
            <div class="row mb-3">
              <label for="txt_mod_code" class="col-md-2 col-form-label">帳號</label>
              <div class="col-md-10">
                <input type="text" class="form-control" id="txt_mod_code" name="mod_code" required>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_mod_name" class="col-md-2 col-form-label">密碼</label>
              <div class="col-md-10">
                <input type="password" class="form-control" id="txt_mod_name" name="mod_name" required>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_mod_path" class="col-md-2 col-form-label">email</label>
              <div class="col-md-10">
                <input type="text" class="form-control" id="txt_mod_path" name="mod_path" required>
              </div>
            </div>

            <div class="row mb-3">
              <label for="txt_mod_status" class="col-md-2 col-form-label">啟用狀態</label>
              <div class="col-md-4">
                <select class="form-select" id="txt_mod_status" name="mod_status">
                  <option value="Y">是</option>
                  <option value="N">否</option>
                </select>
              </div>

              <label for="txt_mod_icon" class="col-md-2 col-form-label">單位</label>
              <div class="col-md-4">
                <input type="text" class="form-control" id="txt_mod_icon" name="mod_icon">
              </div>
            </div>

            <?php //if ($add == "update") { 
            ?>
            <div class="row mb-3 ">
              <label for="txt_ModiUser" class="col-md-2 col-form-label">操作員：</label>
              <div class="col-md-4">
                <input class="form-control" type="text" id="txt_ModiUser" name="ModiUser" readonly />
              </div>
              <label for="txt_ModiUser" class="col-md-2 col-form-label">異動時間：</label>
              <div class="col-md-4">
                <input class="form-control" type="text" id="txt_ModiDate" name="ModiDate" readonly />
              </div>
            </div>
            <?php //} 
            ?>
            <hr>
            <div class="row ">
              <div class="col-md-3">
                <a class="btn btn-secondary w-100" id="cancelButton" href="users_list.php" role="button">取消</a>
              </div>
              <div class="col-md-3">
                <button type="button add" id="deleteButton" name="action" value="" class="btn btn-danger" onclick="deleteDialog()">
                  刪除
                </button>
              </div>
              <div class="col-md-6 text-center">
                <button type="submit" id="saveButton" name="action" value="" class="btn btn-info">
                  儲存
                </button>
              </div>
            </div>

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

  </main><!-- End #main -->

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


  <script>
    showSidebar("sidebar", "users_list");
    $(document).ready(function() {

      if ($("#rid").val() > 0) {
        $("#userNo").attr("readonly", "true");
      }

      // $("#btn_register").prop("disabled", true);
      $('#saveButton').click(function(event) {

        // 檢查帳號是否為空
        if ($('#userNo').val() == '' || $('#userName').val() == '' || $('#email ').val() == '') {
          alert('請輸入必填欄位');
          event.preventDefault(); // 阻止表單提交
          return;
        }

        // 檢查密碼是否為空
        if ($('#rid').val() == 0) { // 新增
          if ($('#userPassword').val() === '') {
            alert('請輸入密碼');
            event.preventDefault(); // 阻止表單提交          
            return;
          }
          if ($('#userPassword').val().length < 4) {
            alert('密碼必須至少包含 4 個字元');
            event.preventDefault(); // 阻止表單提交
            return;
          }
        }
      });
    });

    function deleteUser() {
      // 確認使用者是否要刪除
      if (confirm('確定要刪除此帳號嗎？')) {
        var mrid = $('#rid').val();
        if (!mrid || mrid == 0) {
          alert('無效的 ID');
          return;
        }
        // 提交表單進行刪除
        $('#saveButton').val('Delete').trigger('click');
        console.log("deleteUser", mrid);
      }
    }
  </script>

</body>

</html>