diff --git a/add-asset.php b/add-asset.php index cdc5e1b..81ef23e 100644 --- a/add-asset.php +++ b/add-asset.php @@ -9,7 +9,7 @@ if (!can($_SESSION['user_role'], 'asset', 'create')) { } $allowed_fields_str = can($_SESSION['user_role'], 'asset', 'create'); -$allowed_fields = ($allowed_fields_str === '*') ? ['name', 'asset_tag', 'status', 'location', 'manufacturer', 'model', 'purchase_date'] : explode(',', $allowed_fields_str); +$allowed_fields = ($allowed_fields_str === '*') ? ['name', 'status', 'location', 'manufacturer', 'model', 'purchase_date'] : explode(',', $allowed_fields_str); $success_message = ''; $error_message = ''; @@ -19,28 +19,52 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { $placeholders = []; $columns = []; - foreach ($allowed_fields as $field) { - if (isset($_POST[$field])) { - $data[] = $_POST[$field]; - $columns[] = $field; - $placeholders[] = '?'; + // Generate new asset tag + try { + $pdo = db(); + $stmt = $pdo->query("SELECT asset_tag FROM assets WHERE asset_tag LIKE 'ASSET-%' ORDER BY CAST(SUBSTRING(asset_tag, 7) AS UNSIGNED) DESC LIMIT 1"); + $last_asset_tag = $stmt->fetchColumn(); + + if ($last_asset_tag) { + $last_number = (int) substr($last_asset_tag, 6); + $new_number = $last_number + 1; + } else { + $new_number = 1; } + + $new_asset_tag = 'ASSET-' . str_pad($new_number, 3, '0', STR_PAD_LEFT); + + $data = [$new_asset_tag]; + $columns = ['asset_tag']; + $placeholders = '?'; + + } catch (PDOException $e) { + $error_message = 'Error generating asset tag: ' . $e->getMessage(); } - if (empty($data)) { - $error_message = 'No data submitted.'; - } else { - try { - $pdo = db(); - $sql = sprintf("INSERT INTO assets (%s) VALUES (%s)", implode(', ', $columns), implode(', ', $placeholders)); - $stmt = $pdo->prepare($sql); - $stmt->execute($data); - - header("Location: index.php?success=asset_added"); - exit; + if (empty($error_message)) { + foreach ($allowed_fields as $field) { + if (isset($_POST[$field])) { + $data[] = $_POST[$field]; + $columns[] = $field; + $placeholders[] = '?'; + } + } - } catch (PDOException $e) { - $error_message = 'Database error: ' . $e->getMessage(); + if (count($data) <= 1) { // Only asset tag is present + $error_message = 'No data submitted.'; + } else { + try { + $sql = sprintf("INSERT INTO assets (%s) VALUES (%s)", implode(', ', $columns), implode(', ', array_fill(0, count($columns), '?'))); + $stmt = $pdo->prepare($sql); + $stmt->execute($data); + + header("Location: index.php?success=asset_added"); + exit; + + } catch (PDOException $e) { + $error_message = 'Database error: ' . $e->getMessage(); + } } } } @@ -85,12 +109,6 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') { - -