<?php include 'db_config.php'; ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Promotional Materials</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <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">
    <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>
  <link href='https://unpkg.com/boxicons@2.0.7/css/boxicons.min.css' rel='stylesheet'>
  <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>
    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;
        }
    .scan-result { font-size: 18px; font-weight: bold; margin: 10px 0; }
    .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">
                    <i class='fa-solid fa-bowl-food'></i>
                    <span class="links_name">Meals</span>
                </a>
            </li>
            <li>
                <a href="promotion_scanner.php" class="active">
                    <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">Promotions</span>
            </div>
            
        </nav>
        
    <div class="home-content">
        <div class="container">
                <br><br>
                <div class="form-container1">
                    <h2 style="text-align: center;">📋 Promotional Scanner</h2>
  <input type="text" id="barcode-input" autofocus style="position: absolute; left: -9999px;" />
  <div id="scanner" style="max-width: 500px; margin-bottom: 20px;"></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 to Excel
</button>

<?php
require 'db_config.php';

// Pagination settings
$limit = 20;
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($page < 1) $page = 1;
$offset = ($page - 1) * $limit;

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

// Fetch paginated results to display in the main table
$paginated_result = $conn->query("
    SELECT
        p.id,
        p.user_id,
        p.material_collected,
        p.collection_time,
        u.fullname
    FROM promotional_materials p
    LEFT JOIN users u ON p.user_id = u.id
    ORDER BY p.id DESC
    LIMIT $limit OFFSET $offset
");

// Fetch ALL records for the hidden export table
$all_result = $conn->query("
    SELECT
        p.id,
        p.user_id,
        p.material_collected,
        p.collection_time,
        u.fullname
    FROM promotional_materials p
    LEFT JOIN users u ON p.user_id = u.id
    ORDER BY p.id DESC
");
?>

<table id="promo-table" border="1" cellpadding="8" cellspacing="0">
    <thead>
        <tr>
            <th>ID</th>
            <th>User ID</th>
            <th>Full Name</th>
            <th>Collected</th>
            <th>Time</th>
        </tr>
    </thead>
    <tbody id="promo-table-body">
        <?php if ($paginated_result && $paginated_result->num_rows > 0): ?>
            <?php while ($row = $paginated_result->fetch_assoc()): ?>
                <tr>
                    <td><?= htmlspecialchars($row['id']) ?></td>
                    <td><?= htmlspecialchars($row['user_id']) ?></td>
                    <td><?= htmlspecialchars($row['fullname'] ?? 'Unknown') ?></td>
                    <td><?= htmlspecialchars($row['material_collected']) ?></td>
                    <td><?= htmlspecialchars($row['collection_time']) ?></td>
                </tr>
            <?php endwhile; ?>
        <?php else: ?>
            <tr><td colspan="5">No data found</td></tr>
        <?php endif; ?>
    </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="full-promo-table" style="display:none;">
    <thead>
        <tr>
            <th>ID</th>
            <th>User ID</th>
            <th>Full Name</th>
            <th>Collected</th>
            <th>Time</th>
        </tr>
    </thead>
    <tbody>
        <?php
        if ($all_result && $all_result->num_rows > 0) {
            while ($row = $all_result->fetch_assoc()) {
                echo "<tr>
                    <td>" . htmlspecialchars($row['id']) . "</td>
                    <td>" . htmlspecialchars($row['user_id']) . "</td>
                    <td>" . htmlspecialchars($row['fullname'] ?? 'Unknown') . "</td>
                    <td>" . htmlspecialchars($row['material_collected']) . "</td>
                    <td>" . htmlspecialchars($row['collection_time']) . "</td>
                </tr>";
            }
        }
        ?>
    </tbody>
</table>


 <div id="promo-modal" class="modal" style="display: none;">
  <div class="modal-content">
    <h3 class="modal-title">Select Promotional Items</h3>
    <form id="promo-form">
      <input type="hidden" name="user_id" id="modal-user-id">
      <div class="checkbox-group">
        <label><input type="checkbox" name="items[]" value="Shirt"> Shirt</label>
        <label><input type="checkbox" name="items[]" value="Cap"> Cap</label>
        <label><input type="checkbox" name="items[]" value="Bag"> Bag</label>
        <label><input type="checkbox" name="items[]" value="Mug"> Mug</label>
      </div>
      <div class="button-group">
        <button type="submit" class="confirm-btn">Confirm Collection</button>
        <button type="button" onclick="closeModal()" class="cancel-btn">Cancel</button>
      </div>
    </form>
  </div>
</div>

<style>
/* -------------------- Modal Background and Positioning -------------------- */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.6); /* Darken the background */
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000; /* Ensure the modal is on top of other content */
  font-family: 'Poppins', sans-serif; /* Consistent font */
}

/* -------------------- Modal Content Container -------------------- */
.modal-content {
  background: #ffffff;
  padding: 30px;
  border-radius: 10px;
  min-width: 320px; /* Set a minimum width for better mobile viewing */
  max-width: 500px; /* Limit the maximum width on larger screens */
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
  text-align: center;
  position: relative;
  animation: fadeIn 0.3s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: scale(0.9); }
  to { opacity: 1; transform: scale(1); }
}

/* -------------------- Modal Title -------------------- */
.modal-title {
  color: #333;
  margin-top: 0;
  margin-bottom: 20px;
  font-size: 1.5rem;
  font-weight: 600;
}

/* -------------------- Checkbox Group Styling -------------------- */
.checkbox-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-bottom: 25px;
}

.checkbox-group label {
  font-size: 1rem;
  color: #555;
  margin-bottom: 10px;
  cursor: pointer;
  display: flex;
  align-items: center;
}

.checkbox-group input[type="checkbox"] {
  margin-right: 10px;
  width: 18px;
  height: 18px;
}

/* -------------------- Button Styling -------------------- */
.button-group {
  display: flex;
  justify-content: space-around;
  gap: 15px; /* Space between buttons */
}

.confirm-btn, .cancel-btn {
  padding: 12px 25px;
  font-size: 1rem;
  font-weight: 500;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s ease;
  flex-grow: 1; /* Make buttons grow to fill space */
}

.confirm-btn {
  background-color: #28a745; /* Green color for success */
  color: white;
}

.confirm-btn:hover {
  background-color: #218838;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.cancel-btn {
  background-color: #dc3545; /* Red color for cancellation */
  color: white;
}

.cancel-btn:hover {
  background-color: #c82333;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
</style>

    </section>
  <!-- Hidden full export -->
  <div style="display:none;">
    <table id="full-promo-table">
      <thead>
        <tr><th>ID</th><th>User ID</th><th>Full Name</th><th>Collected</th><th>Time</th></tr>
      </thead>
      <tbody>
        <?php
        $exportRes = $conn->query("SELECT p.id, p.user_id, p.collection_time, u.fullname 
                                   FROM promotional_materials p
                                   JOIN users u ON p.user_id = u.id
                                   ORDER BY p.id DESC");
        while ($row = $exportRes->fetch_assoc()) {
          echo "<tr>
                  <td>{$row['id']}</td>
                  <td>{$row['user_id']}</td>
                  <td>{$row['fullname']}</td>
                  <td>Yes</td>
                  <td>{$row['collection_time']}</td>
                </tr>";
        }
        ?>
      </tbody>
    </table>
  </div>
</div>

<script>
    // Get references to the HTML elements
    const input = document.getElementById('barcode-input');
    const resultDiv = document.getElementById('scan-result');
    const tableBody = document.getElementById('promo-table-body');
    const exportBtn = document.getElementById('export-btn');

    // Get references for the modal and form
    const modal = document.getElementById('promo-modal');
    const modalForm = document.getElementById('promo-form');
    const modalUserIdInput = document.getElementById('modal-user-id');

    let lastScan = "", scanCooldown = false;

    // Functions for modal control
    function openModal(userId) {
        modalUserIdInput.value = userId;
        modal.style.display = 'flex';
    }

    function closeModal() {
        modal.style.display = 'none';
        modalForm.reset();
    }

    // Function to handle a new promotional material entry after a successful scan
    function addNewPromoEntry(entry) {
        // Create a new table row and insert it at the top
        const newRow = document.createElement('tr');
        newRow.innerHTML = `
            <td>New</td>
            <td>${entry.user_id}</td>
            <td>${entry.fullname}</td>
            <td>${entry.material_collected}</td>
            <td>${entry.collection_time}</td>
        `;
        // Insert the new row at the beginning of the table body
        tableBody.prepend(newRow);
    }

    // This function checks if a user has already collected materials via an AJAX call
    function checkAndShowForm(userId) {
        fetch('check_user.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `user_id=${encodeURIComponent(userId)}`
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'already_collected') {
                    resultDiv.textContent = "⚠️ Already Collected.";
                    resultDiv.className = 'scan-result error';
                } else if (data.status === 'ok') {
                    openModal(userId);
                } else {
                    resultDiv.textContent = data.message || "❌ User not found or error.";
                    resultDiv.className = 'scan-result error';
                }
            })
            .catch(error => {
                resultDiv.textContent = "❌ An error occurred while checking user.";
                resultDiv.className = 'scan-result error';
                console.error('Error:', error);
            });
    }

    // Handles form submission from the modal
    modalForm.onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(modalForm);
        fetch('process_promo.php', {
                method: 'POST',
                body: new URLSearchParams([...formData])
            })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    // Update the scan result message
                    resultDiv.textContent = data.message;
                    resultDiv.className = 'scan-result success';
                    // Add the new data to the table without a full page refresh
                    addNewPromoEntry(data);
                    // Close the modal
                    closeModal();
                } else {
                    resultDiv.textContent = data.message;
                    resultDiv.className = 'scan-result error';
                }
            })
            .catch(error => {
                resultDiv.textContent = "❌ An error occurred during submission.";
                resultDiv.className = 'scan-result error';
                console.error('Error:', error);
            });
    };

    // Main function to handle a scanned barcode/QR code
    function handleScan(userId) {
        // Prevent duplicate scans within the cooldown period
        if (!userId || scanCooldown || userId === lastScan) return;
        lastScan = userId;
        scanCooldown = true;

        checkAndShowForm(userId);

        // Reset cooldown after 2 seconds
        setTimeout(() => {
            scanCooldown = false;
            lastScan = "";
            resultDiv.textContent = ""; // Clear the result message
        }, 2000);
    }

    // Keyboard input for barcode scanners
    input.addEventListener("keydown", (e) => {
        if (e.key === "Enter") {
            handleScan(input.value.trim());
            input.value = ""; // Clear the input field
        }
    });

    // Make the input field focused for continuous scanning
    document.addEventListener("click", () => input.focus());

    // QR code scanner for mobile devices
    if (/Android|iPhone|iPad/i.test(navigator.userAgent)) {
        const qr = new Html5Qrcode("scanner");
        qr.start({
            facingMode: "environment"
        }, {
            fps: 10,
            qrbox: 250
        }, decodedText => handleScan(decodedText.trim()), () => {});
    }

    // Export to Excel functionality
    exportBtn.addEventListener('click', () => {
        const table = document.getElementById('full-promo-table');
        const wb = XLSX.utils.table_to_book(table, {
            sheet: "Promotional Materials"
        });
        XLSX.writeFile(wb, "Promotional_Materials_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>
