35512-vm/index.php
2025-11-08 20:43:02 +00:00

315 lines
14 KiB
PHP

<?php
session_start();
require_once 'db/config.php';
require_once 'auth-check.php';
require_once 'auth-helpers.php';
// Get allowed fields for the current user
$allowed_fields_str = can($_SESSION['user_role_id'], 'asset', 'read');
$allowed_fields = [];
if ($allowed_fields_str === '*') {
// Wildcard means all fields
try {
$pdo = db();
$stmt = $pdo->query("SHOW COLUMNS FROM assets");
$allowed_fields = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
// Handle error, maybe log it
$allowed_fields = [];
}
} elseif ($allowed_fields_str) {
$allowed_fields = explode(',', $allowed_fields_str);
}
// Function to count total assets
function count_assets($search = '', $status = '') {
$sql = "SELECT COUNT(*) FROM assets";
$where = [];
$params = [];
if (!empty($search)) {
$where[] = "name LIKE :search";
$params[':search'] = "%$search%";
}
if (!empty($status)) {
$where[] = "status = :status";
$params[':status'] = $status;
}
if (!empty($where)) {
$sql .= " WHERE " . implode(' AND ', $where);
}
try {
$pdo = db();
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
return $stmt->fetchColumn();
} catch (PDOException $e) {
return 0;
}
}
// Function to execute query and return results
function get_assets($fields, $search = '', $status = '', $limit = 10, $offset = 0, $sort_by = 'created_at', $sort_order = 'DESC') {
if (empty($fields)) {
return []; // No read permission
}
// Always include id for edit/delete links
if (!in_array('id', $fields)) {
$fields[] = 'id';
}
$select_fields = [];
$join_users = in_array('assigned_to', $fields);
foreach ($fields as $field) {
if ($field === 'assigned_to') {
// Use a different alias for the user name to avoid conflict with the original column name
$select_fields[] = 'users.name AS assigned_to_name';
}
// Always select the original assigned_to field for reference if needed
$select_fields[] = 'assets.' . $field;
}
// Remove duplicates that might be caused by adding assets.id and assets.assigned_to
$select_fields = array_unique($select_fields);
$select_fields_sql = implode(', ', $select_fields);
$sql = "SELECT $select_fields_sql FROM assets";
if ($join_users) {
$sql .= " LEFT JOIN users ON assets.assigned_to = users.id";
}
$where = [];
$params = [];
if (!empty($search)) {
// Assuming 'name' is a field that can be searched.
if (in_array('name', $fields)) {
$where[] = "assets.name LIKE :search";
$params[':search'] = "%$search%";
}
}
if (!empty($status)) {
if (in_array('status', $fields)) {
$where[] = "assets.status = :status";
$params[':status'] = $status;
}
}
if (!empty($where)) {
$sql .= " WHERE " . implode(' AND ', $where);
}
// Whitelist sortable columns
$sortable_columns = array_merge($fields, ['created_at']);
if ($sort_by === 'assigned_to') {
$sort_by = 'assigned_to_name'; // Sort by the alias
} elseif (in_array($sort_by, $fields)) {
$sort_by = 'assets.' . $sort_by;
} elseif (!in_array($sort_by, $sortable_columns)) {
$sort_by = 'assets.created_at';
}
$sort_order = strtoupper($sort_order) === 'ASC' ? 'ASC' : 'DESC';
$sql .= " ORDER BY $sort_by $sort_order LIMIT :limit OFFSET :offset";
$params[':limit'] = $limit;
$params[':offset'] = $offset;
try {
$pdo = db();
$stmt = $pdo->prepare($sql);
// Bind parameters separately to handle integer binding for LIMIT and OFFSET
foreach ($params as $key => &$val) {
if ($key === ':limit' || $key === ':offset') {
$stmt->bindParam($key, $val, PDO::PARAM_INT);
} else {
$stmt->bindParam($key, $val);
}
}
$stmt->execute();
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
return ['error' => 'Database error: ' . $e->getMessage()];
}
}
$search = $_GET['search'] ?? '';
$status = $_GET['status'] ?? '';
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$limit = 10;
$offset = ($page - 1) * $limit;
$sort_by = $_GET['sort_by'] ?? 'created_at';
$sort_order = $_GET['sort_order'] ?? 'DESC';
$total_assets = count_assets($search, $status);
$total_pages = ceil($total_assets / $limit);
$assets = get_assets($allowed_fields, $search, $status, $limit, $offset, $sort_by, $sort_order);
function getStatusClass($status) {
switch (strtolower($status)) {
case 'in service':
return 'status-in-service';
case 'under repair':
return 'status-under-repair';
case 'retired':
return 'status-retired';
default:
return '';
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>IC-Inventory</title>
<meta name="description" content="Built with Flatlogic Generator">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<script src="https://unpkg.com/feather-icons"></script>
</head>
<body>
<div class="wrapper">
<?php require_once 'templates/sidebar.php'; ?>
<main id="content">
<div class="header">
<h1>Asset Dashboard</h1>
<div>
<?php if (can($_SESSION['user_role_id'], 'asset', 'create')): ?>
<a href="add-asset.php" class="btn btn-primary">Add New Asset</a>
<?php endif; ?>
<div class="theme-switcher" id="theme-switcher">
<i data-feather="moon"></i>
</div>
</div>
</div>
<?php if (isset($_GET['success']) && $_GET['success'] === 'asset_added'): ?>
<div class="alert alert-success">Asset successfully added!</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'asset_updated'): ?>
<div class="alert alert-success">Asset successfully updated!</div>
<?php elseif (isset($_GET['success']) && $_GET['success'] === 'asset_deleted'): ?>
<div class="alert alert-success">Asset successfully deleted!</div>
<?php elseif (isset($_GET['error']) && $_GET['error'] === 'access_denied'): ?>
<div class="alert alert-danger">You do not have permission to access that page.</div>
<?php endif; ?>
<div class="surface p-4">
<form method="get" class="row g-3 mb-4">
<div class="col-md-4">
<input type="text" name="search" class="form-control" placeholder="Search by asset name..." value="<?php echo htmlspecialchars($search); ?>">
</div>
<div class="col-md-3">
<select name="status" class="form-select">
<option value="">All Statuses</option>
<option value="In Service" <?php echo ($status === 'In Service') ? 'selected' : ''; ?>>In Service</option>
<option value="Under Repair" <?php echo ($status === 'Under Repair') ? 'selected' : ''; ?>>Under Repair</option>
<option value="Retired" <?php echo ($status === 'Retired') ? 'selected' : ''; ?>>Retired</option>
</select>
</div>
<div class="col-md-2">
<button type="submit" class="btn btn-primary">Filter</button>
</div>
</form>
<?php if (isset($assets['error'])): ?>
<div class="alert alert-danger">
<?php echo htmlspecialchars($assets['error']); ?>
</div>
<?php elseif (empty($assets)): ?>
<div class="text-center p-5">
<h4>No assets found.</h4>
<?php if (can($_SESSION['user_role_id'], 'asset', 'create')): ?>
<p>Get started by adding your first company asset.</p>
<a href="add-asset.php" class="btn btn-primary">Add Asset</a>
<?php endif; ?>
</div>
<?php else: ?>
<div class="table-responsive">
<table class="table asset-table">
<thead>
<tr>
<?php
$new_sort_order = ($sort_order === 'DESC') ? 'ASC' : 'DESC';
foreach ($allowed_fields as $field): if($field === 'id') continue;
?>
<th>
<a href="?page=<?php echo $page; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&sort_by=<?php echo $field; ?>&sort_order=<?php echo $new_sort_order; ?>">
<?php echo ucfirst(str_replace('_', ' ', $field)); ?>
<?php if ($sort_by === $field): ?>
<i data-feather="<?php echo ($sort_order === 'DESC') ? 'arrow-down' : 'arrow-up'; ?>"></i>
<?php endif; ?>
</a>
</th>
<?php endforeach; ?>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($assets as $asset): ?>
<tr>
<?php foreach ($allowed_fields as $field): if($field === 'id') continue; ?>
<td>
<?php if ($field === 'status'): ?>
<span class="status <?php echo getStatusClass($asset[$field]); ?>"><?php echo htmlspecialchars($asset[$field]); ?></span>
<?php elseif ($field === 'assigned_to'): ?>
<?php echo htmlspecialchars($asset['assigned_to_name'] ?? ($asset['assigned_to'] ?? '')); ?>
<?php else: ?>
<?php echo htmlspecialchars($asset[$field] ?? ''); ?>
<?php endif; ?>
</td>
<?php endforeach; ?>
<td>
<?php if (can($_SESSION['user_role_id'], 'asset', 'update')): ?>
<a href="edit-asset.php?id=<?php echo $asset['id']; ?>" class="btn btn-sm btn-outline-primary">Edit</a>
<?php endif; ?>
<?php if (can($_SESSION['user_role_id'], 'asset', 'delete')): ?>
<a href="delete-asset.php?id=<?php echo $asset['id']; ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Are you sure you want to delete this asset?');">Delete</a>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
<nav aria-label="Page navigation">
<ul class="pagination justify-content-center">
<?php if ($page > 1): ?>
<li class="page-item"><a class="page-link" href="?page=<?php echo $page - 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&sort_by=<?php echo $sort_by; ?>&sort_order=<?php echo $sort_order; ?>">Previous</a></li>
<?php endif; ?>
<?php for ($i = 1; $i <= $total_pages; $i++): ?>
<li class="page-item <?php echo ($i == $page) ? 'active' : ''; ?>"><a class="page-link" href="?page=<?php echo $i; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&sort_by=<?php echo $sort_by; ?>&sort_order=<?php echo $sort_order; ?>"><?php echo $i; ?></a></li>
<?php endfor; ?>
<?php if ($page < $total_pages): ?>
<li class="page-item"><a class="page-link" href="?page=<?php echo $page + 1; ?>&search=<?php echo urlencode($search); ?>&status=<?php echo urlencode($status); ?>&sort_by=<?php echo $sort_by; ?>&sort_order=<?php echo $sort_order; ?>">Next</a></li>
<?php endif; ?>
</ul>
</nav>
<?php endif; ?>
</div>
</main>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
<script>
feather.replace();
</script>
</body>
</html>