<?php include 'db_config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Meals Deduction Scanner</title>
  <meta charset="UTF-8">
    <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">
                    <i class='bx bxs-user-detail'></i>
                    <span class="links_name">Attendance</span>
                </a>
            </li>
            <li>
                <a href="meals_deduction.php" class="active">
                    <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">Meals</span>
            </div>
            
        </nav>
        <div class="home-content">
            <div class="container">
                <br><br>
                <div class="form-container1">
                    <h2 style="text-align: center;">🍽️ Meals Deduction 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 Meals to Excel
</button>



<h3>Recent Meals Deductions</h3>

<?php
// Fetch total meals allocated from users table
$totalMealsAllocated = 0;
$allocQuery = $conn->query("SELECT SUM(meals_allocated) AS total_allocated FROM users");
if ($allocQuery && $allocQuery->num_rows > 0) {
    $alloc = $allocQuery->fetch_assoc();
    $totalMealsAllocated = $alloc['total_allocated'];
}

// Fetch total meals used from meal_deductions table
$totalMealsUsed = 0;
$usedQuery = $conn->query("SELECT COUNT(*) AS total_used FROM meal_deductions");
if ($usedQuery && $usedQuery->num_rows > 0) {
    $used = $usedQuery->fetch_assoc();
    $totalMealsUsed = $used['total_used'];
}

// Calculate total meals remaining
$totalMealsRemaining = $totalMealsAllocated - $totalMealsUsed;
?>

<div style="margin-bottom: 10px; font-weight: bold;">
  Total Meals Allocated: <?php echo $totalMealsAllocated; ?> |
  Total Meals Used: <?php echo $totalMealsUsed; ?> |
  Total Meals Remaining: <?php echo $totalMealsRemaining; ?>
</div>
<?php
$limit = 20; // number of rows per page
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

// Count total records
$totalResult = $conn->query("SELECT COUNT(*) as total FROM meal_deductions");
$totalRow = $totalResult->fetch_assoc();
$totalRecords = $totalRow['total'];
$totalPages = ceil($totalRecords / $limit);

// Fetch paginated results
$result = $conn->query("SELECT id, user_id, name, time, meal_type FROM meal_deductions ORDER BY id DESC LIMIT $limit OFFSET $offset");
?>
<table id="meals-table" border="1" cellpadding="8" cellspacing="0">
  <thead>
    <tr>
      <th>ID</th>
      <th>User ID</th>
      <th>Time</th>
      <th>Meal</th>
      <th>Full Name</th>
    </tr>
  </thead>
  <tbody id="meals-table-body">
    <?php while ($row = $result->fetch_assoc()): ?>
      <tr>
        <td><?= $row['id'] ?></td>
        <td><?= $row['user_id'] ?></td>
        <td><?= $row['time'] ?></td>
        <td><?= $row['meal_type'] ?></td>
        <td><?= $row['name'] ?></td>
      </tr>
    <?php endwhile; ?>
  </tbody>
</table>

<div style="margin-top: 15px;">
  <?php if ($page > 1): ?>
    <a href="?page=<?= $page - 1 ?>">« 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 »</a>
  <?php endif; ?>
</div>

<table id="meals-table-full" style="display:none;">
  <thead>
    <tr>
      <th>ID</th>
      <th>User ID</th>
      <th>Time</th>
      <th>Meal</th>
      <th>Full Name</th>
    </tr>
  </thead>
  <tbody>
    <?php
      $all_result = $conn->query("SELECT id, user_id, name, time, meal_type FROM meal_deductions ORDER BY id DESC");
      while ($row = $all_result->fetch_assoc()) {
        echo "<tr>
                <td>{$row['id']}</td>
                <td>{$row['user_id']}</td>
                <td>{$row['time']}</td>
                <td>{$row['meal_type']}</td>
                <td>{$row['name']}</td>
              </tr>";
      }
    ?>
  </tbody>
</table>



                </div>
</section>
<script>
  const resultDiv = document.getElementById('scan-result');
  const tableBody = document.getElementById('meals-table');
  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_meal.php', {
      method: 'POST',
      headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
      body: `user_id=${encodeURIComponent(userId)}&scan_type=meal`
    })
    .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);
    });
  }

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

  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());
  }

  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) => {}
    ).catch(err => {
      resultDiv.textContent = "Unable to access camera. Please allow permission.";
      resultDiv.className = 'scan-result error';
    });
  }

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

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

  XLSX.writeFile(wb, "Meals_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>
