<?php include 'db_config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Attendance Scanner</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Meals Management</title>
    <link rel="stylesheet" href="../Css/styleUser.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;700&display=swap" rel="stylesheet">
    <!-- Boxicons CDN Link -->
    <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6Hty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
  <script src="https://unpkg.com/html5-qrcode@2.3.8/html5-qrcode.min.js"></script>
  <script src="../assets/js/xlsx.full.min.js"></script>
  <style>
    body {
      font-family: Arial, sans-serif;

    }
    #scanner {
      width: 100%;
      max-width: 500px;
      margin-bottom: 20px;
    }
    .scan-result {
      font-size: 18px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        th, td {
            padding: 12px;
            border: 1px solid #ccc;
            text-align: left;
        }
        th {
            background-color: #007BFF;
            color: white;
        }
    .success { color: green; }
    .error { color: red; }
  </style>
</head>
<body>
<div class="sidebar">
        <div class="logo-details">
            <i class='bx bx-desktop'></i>
            <span class="logo_name">Mips</span>
        </div>
        <ul class="nav-links">
            <li>
                <a href="dashboard.php">
                    <i class='bx bx-grid-alt'></i>
                    <span class="links_name">Dashboard</span>
                </a>
            </li>
            <li>
                <a href="index.php">
                    <i class='bx bx-box'></i>
                    <span class="links_name">Register</span>
                </a>
            </li>
            <li>
                <a href="users.php">
                    <i class='bx bx-list-ul'></i>
                    <span class="links_name">Participants</span>
                </a>
            </li>
            <li>
                <a href="attendance_scanner.php" class="active">
                    <i class='bx bxs-user-detail'></i>
                    <span class="links_name">Attendance</span>
                </a>
            </li>
            <li>
                <a href="meals_deduction.php">
                    <i class='fa-solid fa-bowl-food'></i>
                    <span class="links_name">Meals</span>
                </a>
            </li>
            <li>
                <a href="promotion_scanner.php">
                    <i class='bx bx-list-ul'></i>
                    <span class="links_name">Promotions</span>
                </a>
            </li>
            <li>
                <a href="sub_user.php">
                    <i class="fas fa-user"></i>
                    <span class="links_name">Create User</span>
                </a>
            </li>
            <li>
                <a href="Disubuser.php">
                    <i class="fas fa-user-check"></i>
                    <span class="links_name">Sub User</span>
                </a>
            </li>
                       <li class="log_out">
                <a href="logout.php">
                    <i class='bx bx-log-out'></i>
                    <span class="links_name">Log out</span>
                </a>
            </li>
        </ul>
    </div>
    <section class="home-section">
        <nav>
            <div class="sidebar-button">
                <i class='bx bx-menu sidebarBtn'></i>
                <span class="dashboard">Attendance</span>
            </div>
            
        </nav>
        <div class="home-content">
            <div class="container">
                <br><br>
                <div class="form-container1">
                    <h2 style="text-align: center;">📋 Attendance Scanner</h2>

<input type="text" id="barcode-input" autofocus style="position: absolute; left: -9999px;" />


<div id="scanner" style="display:none;"></div>

<div id="scan-result" class="scan-result"></div>

<button id="export-btn" style="
  margin: 10px;
  padding: 10px 20px;
  background-color: green;
  color: white;
  border: none;
  border-radius: 6px;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
"
onmouseover="this.style.backgroundColor='#056608'; this.style.transform='scale(1.03)'"
onmouseout="this.style.backgroundColor='green'; this.style.transform='scale(1)'">
  Export Attendance to Excel
</button>

<h3>Recent Attendance Records</h3>

<?php
// Set records per page
$limit = 20;

// Get current page number from URL, default to 1
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? intval($_GET['page']) : 1;

// Calculate the offset
$offset = ($page - 1) * $limit;

// Get total number of records
$totalResult = $conn->query("SELECT COUNT(*) AS total FROM attendance");
$totalRow = $totalResult->fetch_assoc();
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $limit);

// Fetch the current page data
$result = $conn->query("SELECT id, user_id, checkin_time, participant_type, fullname 
                        FROM attendance 
                        ORDER BY id DESC 
                        LIMIT $limit OFFSET $offset");
?>

<table border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th>ID</th>
      <th>User ID</th>
      <th>Check-in Time</th>
      <th>Participant Type</th>
      <th>Full Name</th>
    </tr>
  </thead>
  <tbody id="attendance-table-body">
    <?php while ($row = $result->fetch_assoc()) { ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= $row['user_id'] ?></td>
        <td><?= $row['checkin_time'] ?></td>
        <td><?= $row['participant_type'] ?></td>
        <td><?= $row['fullname'] ?></td>
      </tr>
    <?php } ?>
  </tbody>
</table>

<!-- Hidden full table for export -->
<div id="full-attendance-export" style="display: none;">
  <table id="full-attendance-table">
    <thead>
      <tr>
        <th>ID</th>
        <th>User ID</th>
        <th>Check-in Time</th>
        <th>Participant Type</th>
        <th>Full Name</th>
      </tr>
    </thead>
    <tbody>
      <?php
      $exportResult = $conn->query("SELECT id, user_id, checkin_time, participant_type, fullname FROM attendance ORDER BY id DESC");
      while ($row = $exportResult->fetch_assoc()) {
          echo "<tr>
                  <td>{$row['id']}</td>
                  <td>{$row['user_id']}</td>
                  <td>{$row['checkin_time']}</td>
                  <td>{$row['participant_type']}</td>
                  <td>{$row['fullname']}</td>
                </tr>";
      }
      ?>
    </tbody>
  </table>
</div>


<!-- Pagination Links -->
<div style="margin-top: 10px;">
  <?php if ($totalPages > 1): ?>
    <div style="display: flex; gap: 10px;">
      <?php if ($page > 1): ?>
        <a href="?page=<?= $page - 1 ?>">&laquo; Prev</a>
      <?php endif; ?>

      <?php for ($i = 1; $i <= $totalPages; $i++): ?>
        <a href="?page=<?= $i ?>" <?= ($i === $page) ? 'style="font-weight:bold;"' : '' ?>><?= $i ?></a>
      <?php endfor; ?>

      <?php if ($page < $totalPages): ?>
        <a href="?page=<?= $page + 1 ?>">Next &raquo;</a>
      <?php endif; ?>
    </div>
  <?php endif; ?>
</div>

    </section>
<script>
  const resultDiv = document.getElementById('scan-result');
  const tableBody = document.getElementById('attendance-table-body');
  const input = document.getElementById('barcode-input');
  let lastScan = "";
  let scanCooldown = false;

  function processScan(userId) {
    if (!userId || scanCooldown || userId === lastScan) return;
    lastScan = userId;
    scanCooldown = true;

    fetch('process_scan.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `user_id=${encodeURIComponent(userId)}&scan_type=attendance`
    })
    .then(res => res.json())
    .then(data => {
      const row = document.createElement('tr');
      const now = new Date().toLocaleString();

      if (data.status === 'success') {
        resultDiv.textContent = data.message;
        resultDiv.className = 'scan-result success';
        row.innerHTML = `
          <td>–</td>
          <td>${userId}</td>
          <td>${now}</td>
          <td>${data.participant_type}</td>
          <td>${data.fullname}</td>
        `;
        tableBody.prepend(row);
      } else {
        resultDiv.textContent = data.message;
        resultDiv.className = 'scan-result error';
      }
    })
    .catch(() => {
      resultDiv.textContent = "Error processing scan.";
      resultDiv.className = 'scan-result error';
    })
    .finally(() => {
      setTimeout(() => {
        scanCooldown = false;
        lastScan = "";
      }, 2000);
    });
  }

  // Utility to detect mobile devices
  function isMobile() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
  }

  // USB Barcode Scanner Input (PC only)
  if (!isMobile()) {
    input.focus();
    input.addEventListener("keydown", (e) => {
      if (e.key === "Enter") {
        const code = input.value.trim();
        if (code) processScan(code);
        input.value = "";
        setTimeout(() => input.focus(), 100);
      }
    });
    document.addEventListener("click", () => input.focus());
  }

  // Mobile camera QR scanner
  if (isMobile() && window.Html5Qrcode) {
    document.getElementById('scanner').style.display = 'block';
    const html5QrCode = new Html5Qrcode("scanner");
    html5QrCode.start(
      { facingMode: "environment" },
      { fps: 10, qrbox: 250 },
      (decodedText) => {
        processScan(decodedText.trim());
      },
      (errorMessage) => {
        // Optionally handle errors
      }
    ).catch(err => {
      resultDiv.textContent = "Unable to access camera. Please allow permission.";
      resultDiv.className = 'scan-result error';
    });
  }

  document.getElementById('export-btn').addEventListener('click', function () {
  const fullTable = document.getElementById('full-attendance-table');
  const wb = XLSX.utils.table_to_book(fullTable, { sheet: "Attendance" });

  wb.Props = {
    Title: "Attendance List",
    Author: "Mips",
    CreatedDate: new Date()
  };

  XLSX.writeFile(wb, "Attendance_List.xlsx");
});

let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".sidebarBtn");
sidebarBtn.onclick = function() {
  sidebar.classList.toggle("active");
  if(sidebar.classList.contains("active")){
  sidebarBtn.classList.replace("bx-menu" ,"bx-menu-alt-right");
}else
  sidebarBtn.classList.replace("bx-menu-alt-right", "bx-menu");
}
</script>



</body>
</html>
