<?php
include_once '../src/inc/db/function.php';
$mkey = $_REQUEST['mkey'] ?? '';
$mkey = '%' . $mkey . '%'; // 添加通配符到查詢字串中
// 設定每頁顯示的資料數量
$itemsPerPage = 10; // 每頁顯示 10 筆資料

// 取得當前頁碼，若無設定則預設為第 1 頁
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;
$page = max(1, $page); // 確保頁碼不小於 1
// 計算總筆數
$sqlTotal = "SELECT COUNT(*) FROM users WHERE userNo LIKE '{$mkey}' OR userName LIKE '{$mkey}' OR department LIKE '{$mkey}' ";
$totalItems = $conn->query($sqlTotal)->fetchColumn();

// 計算總頁數
$totalPages = ceil($totalItems / $itemsPerPage);

// 計算查詢起始位置（OFFSET）
$offset = ($page - 1) * $itemsPerPage;

// 查詢目前頁面所需的資料
$sql = 'SELECT user_id,userNo, email,userName, department,userStatus,create_date FROM users';
$sql .= ' WHERE userNo LIKE :mkey OR userName LIKE :mkey OR department LIKE :mkey';
$sql .= ' LIMIT :limit OFFSET :offset';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':mkey', $mkey, PDO::PARAM_STR);
$stmt->bindValue(':limit', $itemsPerPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
$stmt->execute();
$data_list = $stmt->fetchAll(PDO::FETCH_ASSOC);

// 計算顯示的頁碼範圍
$displayPages = 3; // 每次最多顯示的頁碼數量
$startPage = max(1, $page - floor($displayPages / 2));
$endPage = min($totalPages, $startPage + $displayPages - 1);

// 確保顯示頁碼範圍不超過總頁數
if ($endPage - $startPage + 1 < $displayPages) {
    $startPage = max(1, $endPage - $displayPages + 1);
}


// 查詢資料庫中所有公告
/* $sql = "SELECT user_id,userNo, email,userName, department,userStatus,create_date FROM users ORDER BY create_date Desc";
$stmt = $conn->prepare($sql);
$stmt->execute();
$data_list = $stmt->fetchAll(PDO::FETCH_ASSOC);
 */
?>
<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <meta content="width=device-width, initial-scale=1.0" name="viewport">
  <?php include_once "admin_css.php"; ?>
  <!-- <title> 帳號管理</title> -->

</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="#" onclick="window.history.back();" class="btn btn-sm  btn-outline-primary"><i class="bi bi-arrow-90deg-left"></i> 回上一頁</a>
      </span>
    </div>

    <section class="section dashboard">
      <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>
      <div class="row mb-3" style="background-color: #EAF5FF; height: 66px; border-radius: 8px; display: flex; flex-direction: column; justify-content: center;  text-align: left;">
        <form method="GET" action="" id="form-search">
          <div class="input-group" style="width: 50%;">
            <input type="text" name="mkey" class="form-control" placeholder="請輸入關鍵字搜尋...">
            <button type="submit" class="input-group-text" title="Search"><i class="bi bi-search"></i></button>
          </div>
        </form>
      </div>

      <!-- BRGIN DATATABLE -->
      <table class="table table-hover table-responsive table-bordered">
        <thead>
          <tr class="table-primary">
            <th style="width:60px;">
              <a href="users_edit.php" class="btn btn-sm btn-primary" title="新增">
                <i class="bi bi-plus-lg"></i></a>
            </th>
            <th style="width:10%;">帳號</th>
            <th style="width:10%;">姓名</th>
            <th>電子信箱</th>
            <th style="width:10%;">服務單位</th>
            <th style="width:10%;">申請日期</th>
            <th style="width:10%;">啟用狀態</th>
          </tr>
        </thead>
        <tbody>
          <?php if (count($data_list) > 0): ?>
            <?php foreach ($data_list as $data): ?>
              <tr>
                <th>
                  <a href="users_edit.php?rid=<?php echo $data['user_id']??0; ?>" class="btn btn-sm btn-primary" title="編輯">
                    <i class="bi bi-pencil-square"></i></a>

                </th>
                <td class=" text-center"><?php echo htmlspecialchars($data['userNo'] ?? ''); ?></td>
                <td>
                  <?php echo htmlspecialchars($data['userName'] ?? ''); ?>
                </td>
                <td><?php echo htmlspecialchars($data['email'] ?? ''); ?></td>
                <td><?php echo htmlspecialchars($data['department'] ?? ''); ?></td>
                <td>
                  <?= !empty($data['create_date']) ? date('Y-m-d', strtotime($data['create_date'])) : ''; ?>
                </td>
                <td class=" text-center"><?php echo htmlspecialchars($data['userStatus'] ?? ''); ?></td>
              </tr>
            <?php endforeach; ?>
          <?php else: ?>
            <tr>
              <td colspan="6" class="text-center">目前沒有資料。</td>
            </tr>
          <?php endif; ?>
        </tbody>
      </table>
      <!-- END DATATABLE -->
      <!-- 分頁導航 -->
      <div style="display: flex; justify-content: center; align-items: center; margin-top: 30px;">
        <span>共 <?php echo $totalPages; ?> 頁， 每頁 <?php echo $itemsPerPage; ?> 筆</span><!-- ，共 <?php echo $totalItems; ?> 筆資料</span>&nbsp;&nbsp; -->
        <nav aria-label="Page navigation" class="ms-4">
          <ul class="pagination">
            <?php if ($startPage > 1) : ?>
              <li class="page-item"><a class="page-link" href="?page=1">1</a></li>
              <li class="page-item disabled"><span class="page-link">...</span></li>
            <?php endif; ?>

            <?php for ($i = $startPage; $i <= $endPage; $i++) : ?>
              <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
              </li>
            <?php endfor; ?>

            <?php if ($endPage < $totalPages) : ?>
              <li class="page-item disabled"><span class="page-link">...</span></li>
              <li class="page-item"><a class="page-link" href="?page=<?php echo $totalPages; ?>"><?php echo $totalPages; ?></a></li>
            <?php endif; ?>
          </ul>
        </nav>
      </div>
    </section>

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

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

  <script>
    showSidebar("sidebar", "users_list");

    function changeToEdit() {

      window.location.href = "data_edit.php";

    }
  </script>

</body>

</html>