-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhc_dash.php
More file actions
419 lines (370 loc) · 19.3 KB
/
Copy pathhc_dash.php
File metadata and controls
419 lines (370 loc) · 19.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php
/**
* Holding Cage Dashboard Script
*
* This script displays the holding cage dashboard for logged-in users. It includes functionalities such as
* adding new cages, printing cage cards, searching cages, and pagination. The page content is dynamically
* loaded using JavaScript and AJAX.
*
*/
// Start a new session or resume the existing session
require 'session_config.php';
// Include the database connection file
require 'dbcon.php';
// Check if the user is not logged in, redirect them to index.php with the current URL for redirection after login
if (!isset($_SESSION['username'])) {
$currentUrl = urlencode($_SERVER['REQUEST_URI']);
header("Location: index.php?redirect=$currentUrl");
exit; // Exit to ensure no further code is executed
}
// CSRF token for state-changing requests submitted from this page (archive/restore/delete).
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
// Include the header file
require 'header.php';
?>
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags for character encoding and responsive design -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- FontAwesome for icons -->
<!-- Font Awesome loaded via header.php -->
<!-- Bootstrap 5 CSS is already loaded via header.php -->
<script>
// State variables for pagination, sorting, archive filtering, and visible columns
var currentLimit = 10;
var currentSort = 'cage_id_asc';
var showArchived = '0';
// Available optional columns for holding dashboard (max 2 visible at a time)
var allColumns = ['strain', 'sex', 'age'];
var visibleColumns = ['strain', 'age']; // default: show strain and age
// Initialize tooltips when the document is ready
var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
return new bootstrap.Tooltip(tooltipTriggerEl)
})
// Submit a state-changing action to hc_drop.php as a POST with the CSRF token.
var HC_DROP_CSRF = <?= json_encode($_SESSION['csrf_token']); ?>;
function postToDrop(id, action) {
var form = document.createElement('form');
form.method = 'POST';
form.action = 'hc_drop.php';
var fields = { id: id, action: action, confirm: 'true', csrf_token: HC_DROP_CSRF };
for (var k in fields) {
var input = document.createElement('input');
input.type = 'hidden';
input.name = k;
input.value = fields[k];
form.appendChild(input);
}
document.body.appendChild(form);
form.submit();
}
// Confirm archive function with a dialog
function confirmDeletion(id) {
if (confirm("Are you sure you want to archive cage '" + id + "'?")) {
postToDrop(id, 'archive');
}
}
// Confirm restore function
function confirmRestore(id) {
if (confirm("Restore cage '" + id + "' back to active?")) {
postToDrop(id, 'restore');
}
}
// Confirm permanent delete function
function confirmPermanentDelete(id) {
if (confirm("PERMANENTLY delete cage '" + id + "' and ALL related data?\n\nThis action CANNOT be undone.")) {
if (confirm("Are you absolutely sure? This will permanently remove all data for cage '" + id + "'.")) {
postToDrop(id, 'permanent_delete');
}
}
}
// Fetch data function to load data dynamically
function fetchData(page = 1, search = '') {
var xhr = new XMLHttpRequest();
var url = 'hc_fetch_data.php?page=' + page
+ '&search=' + encodeURIComponent(search)
+ '&limit=' + currentLimit
+ '&sort=' + currentSort
+ '&show_archived=' + showArchived
+ '&columns=' + encodeURIComponent(visibleColumns.join(','));
xhr.open('GET', url, true);
xhr.onload = function() {
if (xhr.status === 200) {
try {
var response = JSON.parse(xhr.responseText);
if (response.tableRows !== undefined && response.paginationLinks !== undefined) {
document.getElementById('tableBody').innerHTML = response.tableRows;
document.getElementById('paginationLinks').innerHTML = response.paginationLinks;
document.getElementById('searchInput').value = search;
// Show search result info
var infoEl = document.getElementById('searchResultInfo');
if (search && search.trim() !== '') {
var count = response.totalRecords || 0;
if (count === 0) {
infoEl.innerHTML = '<span class="text-warning"><i class="fas fa-exclamation-circle"></i> No results found for "<strong>' + search.replace(/</g, '<') + '</strong>"</span>';
} else {
infoEl.innerHTML = '<span class="text-muted"><i class="fas fa-check-circle"></i> ' + count + ' cage' + (count !== 1 ? 's' : '') + ' found</span>';
}
infoEl.style.display = 'block';
} else {
infoEl.style.display = 'none';
}
// Re-initialize tooltips on dynamically loaded content
document.querySelectorAll('#tableBody [data-bs-toggle="tooltip"]').forEach(function(el) {
new bootstrap.Tooltip(el);
});
// Update the URL with all current parameters
const newUrl = new URL(window.location.href);
newUrl.searchParams.set('page', page);
newUrl.searchParams.set('search', search);
newUrl.searchParams.set('limit', currentLimit);
newUrl.searchParams.set('sort', currentSort);
newUrl.searchParams.set('show_archived', showArchived);
newUrl.searchParams.set('columns', visibleColumns.join(','));
// Update table headers based on visible columns
updateTableHeaders();
window.history.replaceState({
path: newUrl.href
}, '', newUrl.href);
} else {
console.error('Invalid response format:', response);
}
} catch (e) {
console.error('Error parsing JSON response:', e);
}
} else {
console.error('Request failed. Status:', xhr.status);
}
};
xhr.onerror = function() {
console.error('Request failed. An error occurred during the transaction.');
};
xhr.send();
}
// Change page size and re-fetch from page 1
function changeLimit(newLimit) {
currentLimit = parseInt(newLimit);
var searchQuery = document.getElementById('searchInput').value;
fetchData(1, searchQuery);
}
// Change sort and re-fetch
function changeSort(value) {
currentSort = value;
var searchQuery = document.getElementById('searchInput').value;
fetchData(1, searchQuery);
}
// Toggle a column on/off (max 2 optional columns)
function toggleColumn(col, checkbox) {
if (checkbox.checked) {
if (visibleColumns.length >= 2) {
checkbox.checked = false;
alert('Maximum 2 columns allowed. Uncheck one first.');
return;
}
visibleColumns.push(col);
} else {
visibleColumns = visibleColumns.filter(function(c) { return c !== col; });
}
var searchQuery = document.getElementById('searchInput').value;
fetchData(1, searchQuery);
}
// Update table headers to match visible columns
function updateTableHeaders() {
var columnLabels = { 'strain': 'Strain', 'sex': 'Sex', 'age': 'Age' };
var headerRow = document.querySelector('#mouseTable thead tr');
var html = '<th>Cage ID</th>';
visibleColumns.forEach(function(col) {
html += '<th>' + (columnLabels[col] || col) + '</th>';
});
html += '<th style="width: 220px;">Action</th>';
headerRow.innerHTML = html;
}
// Sync column checkboxes with state
function syncColumnCheckboxes() {
document.querySelectorAll('.col-toggle-check').forEach(function(cb) {
cb.checked = visibleColumns.indexOf(cb.value) !== -1;
});
}
// Toggle archive view and re-fetch
function toggleArchive() {
showArchived = (showArchived === '0') ? '1' : '0';
var btn = document.getElementById('archiveToggleBtn');
if (showArchived === '1') {
btn.innerHTML = '<i class="fas fa-box-open me-1"></i> Show Active';
btn.classList.remove('btn-outline-secondary');
btn.classList.add('btn-outline-warning');
} else {
btn.innerHTML = '<i class="fas fa-archive me-1"></i> Show Archived';
btn.classList.remove('btn-outline-warning');
btn.classList.add('btn-outline-secondary');
}
var searchQuery = document.getElementById('searchInput').value;
fetchData(1, searchQuery);
}
// Search function with debounce to avoid excessive requests
var searchTimeout = null;
function searchCages() {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(function() {
var searchQuery = document.getElementById('searchInput').value;
fetchData(1, searchQuery);
}, 300);
}
// Fetch initial data when the DOM content is loaded
document.addEventListener('DOMContentLoaded', function() {
const urlParams = new URLSearchParams(window.location.search);
const page = urlParams.get('page') || 1;
const search = urlParams.get('search') || '';
currentLimit = parseInt(urlParams.get('limit')) || 10;
currentSort = urlParams.get('sort') || 'cage_id_asc';
showArchived = urlParams.get('show_archived') || '0';
var colsParam = urlParams.get('columns');
if (colsParam) {
visibleColumns = colsParam.split(',').filter(function(c) { return allColumns.indexOf(c) !== -1; });
}
// Sync UI controls with URL params
document.getElementById('pageSizeSelect').value = currentLimit;
document.getElementById('sortSelect').value = currentSort;
syncColumnCheckboxes();
if (showArchived === '1') {
var btn = document.getElementById('archiveToggleBtn');
btn.innerHTML = '<i class="fas fa-box-open me-1"></i> Show Active';
btn.classList.remove('btn-outline-secondary');
btn.classList.add('btn-outline-warning');
}
fetchData(page, search);
});
</script>
<title>Dashboard Holding Cage | <?php echo htmlspecialchars($labName); ?></title>
<style>
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.container {
max-width: 900px;
background-color: var(--bs-tertiary-bg);
padding: 20px;
border-radius: 8px;
margin-top: 20px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.table-wrapper {
margin-bottom: 50px;
overflow-x: auto;
}
/* Action icon/button styles handled by unified styles in header.php */
@media (max-width: 768px) {
.table-wrapper th,
.table-wrapper td {
padding: 12px 8px;
text-align: center;
}
}
</style>
</head>
<body>
<div class="container content mt-4">
<!-- Include message file for displaying messages -->
<?php include('message.php'); ?>
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header d-flex flex-column flex-md-row justify-content-between align-items-center">
<h1 class="mb-0">Holding Cage Dashboard</h1>
<div class="action-icons mt-3 mt-md-0">
<?php if ($uiCanAddCage): ?>
<!-- Add new cage button with tooltip -->
<a href="hc_addn.php" class="btn btn-primary btn-icon" data-bs-toggle="tooltip" data-bs-placement="top" title="Add New Cage">
<i class="fas fa-plus"></i>
</a>
<?php endif; ?>
<!-- Print cage card button with tooltip -->
<a href="slct_crd.php" class="btn btn-success btn-icon" data-bs-toggle="tooltip" data-bs-placement="top" title="Print Cage Card">
<i class="fas fa-print"></i>
</a>
<?php if ($uiCanAddNote): ?>
<!-- Maintenance button with tooltip -->
<a href="maintenance.php?from=hc_dash" class="btn btn-warning btn-icon" data-bs-toggle="tooltip" data-bs-placement="top" title="Cage Maintenance">
<i class="fas fa-wrench"></i>
</a>
<?php endif; ?>
</div>
</div>
<div class="card-body">
<!-- Holding Cage Search Box -->
<div class="input-group mb-3">
<input type="text" id="searchInput" class="form-control" placeholder="Search by Cage ID, Strain, or Sex" onkeyup="searchCages()"> <!-- Call search function on keyup -->
<button class="btn btn-primary" type="button" onclick="searchCages()"><i class="fas fa-search"></i> Search</button>
</div>
<div id="searchResultInfo" class="mb-2" style="display:none;"></div>
<!-- Controls row: page size, sort toggle, archive toggle -->
<div class="d-flex flex-wrap align-items-center gap-2 mb-3">
<div class="d-flex align-items-center">
<label for="pageSizeSelect" class="form-label mb-0 me-2 text-nowrap" style="font-size: 0.875rem;">Show</label>
<select id="pageSizeSelect" class="form-select form-select-sm" style="width: auto;" onchange="changeLimit(this.value)">
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
<option value="50">50</option>
</select>
</div>
<select id="sortSelect" class="form-select form-select-sm" style="width: auto;" onchange="changeSort(this.value)">
<option value="cage_id_asc">Cage ID (A-Z)</option>
<option value="cage_id_desc">Cage ID (Z-A)</option>
<option value="created_at_desc">Date Added (Newest)</option>
<option value="created_at_asc">Date Added (Oldest)</option>
<option value="dob_desc">DOB (Newest)</option>
<option value="dob_asc">DOB (Oldest)</option>
</select>
<div class="dropdown">
<button class="btn btn-sm btn-outline-info dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-columns me-1"></i> Columns
</button>
<ul class="dropdown-menu">
<li><label class="dropdown-item"><input type="checkbox" class="col-toggle-check form-check-input me-2" value="strain" checked onchange="toggleColumn('strain', this)"> Strain</label></li>
<li><label class="dropdown-item"><input type="checkbox" class="col-toggle-check form-check-input me-2" value="sex" onchange="toggleColumn('sex', this)"> Sex</label></li>
<li><label class="dropdown-item"><input type="checkbox" class="col-toggle-check form-check-input me-2" value="age" checked onchange="toggleColumn('age', this)"> Age</label></li>
</ul>
</div>
<button id="archiveToggleBtn" class="btn btn-sm btn-outline-secondary" onclick="toggleArchive()">
<i class="fas fa-archive me-1"></i> Show Archived
</button>
</div>
<div class="table-wrapper" id="tableContainer">
<table class="table" id="mouseTable">
<thead>
<tr>
<th>Cage ID</th>
<th>Strain</th>
<th>Sex</th>
<th>Age</th>
<th style="width: 220px;">Action</th>
</tr>
</thead>
<tbody id="tableBody">
<!-- Table rows will be inserted here by JavaScript -->
</tbody>
</table>
</div>
<!-- Pagination -->
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center" id="paginationLinks">
<!-- Pagination links will be inserted here by JavaScript -->
</ul>
</nav>
</div>
</div>
</div>
</div>
</div>
<?php include 'footer.php'; ?> <!-- Include footer file -->
<!-- Bootstrap 5 JS and jQuery already loaded via header.php -->
</body>
</html>