<?php
session_start();
require_once 'includes/auth.php';
requireTechnician();
require_once 'config/db.php';
date_default_timezone_set('Asia/Dhaka');
$user_id = (int) $_SESSION['user_id'];
$entry_id = (int) ($_GET['id'] ?? $_POST['entry_id'] ?? 0);
$error = '';
$success = '';
// Load the entry — must belong to this technician and be a 'deducted' type
$entry_stmt = $pdo->prepare("
SELECT st.id, st.product_id, st.quantity, st.notes, st.created_at,
p.name AS product_name, p.unit, p.current_stock
FROM stock_transactions st
JOIN products p ON p.id = st.product_id
WHERE st.id = ? AND st.user_id = ? AND st.type = 'deducted'
");
$entry_stmt->execute([$entry_id, $user_id]);
$entry = $entry_stmt->fetch();
if (!$entry) {
// Either doesn't exist or doesn't belong to this tech
header('Location: tech_dashboard.php');
exit;
}
// Fetch all products for the dropdown (names + unit only — no stock)
$all_products = $pdo->query("SELECT id, name, unit FROM products ORDER BY name ASC")->fetchAll();
// Sticky form values (pre-fill from entry on first load)
$form = [
'product_id' => $entry['product_id'],
'quantity' => $entry['quantity'],
'notes' => $entry['notes'],
];
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['entry_id'])) {
$form['product_id'] = (int) ($_POST['product_id'] ?? 0);
$form['quantity'] = trim($_POST['quantity'] ?? '');
$form['notes'] = trim($_POST['notes'] ?? '');
$new_qty = (int) $form['quantity'];
$new_product_id = $form['product_id'];
if ($new_product_id <= 0) {
$error = 'Please select a product.';
} elseif ($new_qty <= 0) {
$error = 'Quantity must be a positive number.';
} else {
// Fetch both old and new product with a lock to prevent race conditions
$old_prod_stmt = $pdo->prepare("SELECT id, name, unit, current_stock FROM products WHERE id = ?");
$old_prod_stmt->execute([$entry['product_id']]);
$old_product = $old_prod_stmt->fetch();
$new_prod_stmt = $pdo->prepare("SELECT id, name, unit, current_stock FROM products WHERE id = ?");
$new_prod_stmt->execute([$new_product_id]);
$new_product = $new_prod_stmt->fetch();
if (!$new_product) {
$error = 'Selected product not found.';
} else {
$same_product = ((int) $entry['product_id'] === $new_product_id);
$old_qty = (int) $entry['quantity'];
if ($same_product) {
// Same product: calculate net stock change
$stock_change = $new_qty - $old_qty; // positive = need to deduct more, negative = restore some
// Available stock = current + what we already took (can be reclaimed)
$available = $new_product['current_stock'] + $old_qty;
if ($new_qty > $available) {
$error = 'Quantity exceeds available stock. Please contact your admin.';
}
} else {
// Different product: restore old product's stock, deduct from new product
$available_new = $new_product['current_stock'];
if ($new_qty > $available_new) {
$error = 'Not enough stock for the newly selected product. Please contact your admin.';
}
}
if ($error === '') {
// All validations passed — update inside a transaction
$pdo->beginTransaction();
try {
if ($same_product) {
if ($stock_change !== 0) {
// Adjust stock by the difference
$pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?")
->execute([$stock_change, $new_product_id]);
}
} else {
// Restore old product stock
$pdo->prepare("UPDATE products SET current_stock = current_stock + ? WHERE id = ?")
->execute([$old_qty, $entry['product_id']]);
// Deduct from new product
$pdo->prepare("UPDATE products SET current_stock = current_stock - ? WHERE id = ?")
->execute([$new_qty, $new_product_id]);
}
// Update the transaction record
$pdo->prepare(
"UPDATE stock_transactions
SET product_id = ?, quantity = ?, notes = ?, is_edited = 1, edited_at = NOW()
WHERE id = ? AND user_id = ?"
)->execute([$new_product_id, $new_qty, $form['notes'], $entry_id, $user_id]);
$pdo->commit();
$success = "Entry updated successfully.";
// Reload entry data to reflect changes
$entry_stmt->execute([$entry_id, $user_id]);
$entry = $entry_stmt->fetch();
$form = [
'product_id' => $entry['product_id'],
'quantity' => $entry['quantity'],
'notes' => $entry['notes'],
];
} catch (Exception $ex) {
$pdo->rollBack();
$error = 'Update failed. Please try again.';
}
}
}
}
}
include 'includes/header.php';
?>
<div class="row mb-3">
<div class="col">
<h4 class="page-title"><i class="bi bi-pencil-square me-2 text-primary"></i>Edit My Entry</h4>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item"><a href="tech_dashboard.php">My Dashboard</a></li>
<li class="breadcrumb-item active">Edit Entry</li>
</ol>
</nav>
</div>
</div>
<div class="row justify-content-center">
<div class="col-md-7 col-lg-6">
<!-- Original entry info card -->
<div class="card mb-4 border-warning">
<div class="card-body py-3 d-flex align-items-center gap-3">
<i class="bi bi-info-circle text-warning fs-4"></i>
<div>
<div class="small text-muted">Original entry submitted:</div>
<strong><?= htmlspecialchars($entry['product_name']) ?></strong>
— <?= $entry['quantity'] ?> <?= htmlspecialchars($entry['unit']) ?>(s)
on <?= date('d M Y', strtotime($entry['created_at'])) ?>
at <?= date('h:i A', strtotime($entry['created_at'])) ?>
</div>
</div>
</div>
<div class="card">
<div class="card-header bg-warning text-dark fw-semibold">
<i class="bi bi-pencil me-1"></i> Correct This Entry
</div>
<div class="card-body">
<?php if ($success !== ''): ?>
<div class="alert alert-success d-flex align-items-start gap-2">
<i class="bi bi-check-circle-fill mt-1"></i>
<div>
<?= htmlspecialchars($success) ?>
<div class="mt-2 d-flex gap-2 flex-wrap">
<a href="tech_dashboard.php" class="btn btn-sm btn-success">Back to Dashboard</a>
<a href="tech_usage.php" class="btn btn-sm btn-outline-secondary">Submit New</a>
</div>
</div>
</div>
<?php endif; ?>
<?php if ($error !== ''): ?>
<div class="alert alert-danger d-flex align-items-center gap-2">
<i class="bi bi-exclamation-triangle-fill"></i>
<?= htmlspecialchars($error) ?>
</div>
<?php endif; ?>
<form method="POST" action="" novalidate>
<input type="hidden" name="entry_id" value="<?= $entry_id ?>">
<div class="mb-3">
<label for="product_id" class="form-label fw-semibold">
Product <span class="text-danger">*</span>
</label>
<select class="form-select" id="product_id" name="product_id" required>
<option value="">-- Select Product --</option>
<?php foreach ($all_products as $p): ?>
<option value="<?= $p['id'] ?>"
data-unit="<?= htmlspecialchars($p['unit']) ?>"
<?= (int) $form['product_id'] === (int) $p['id'] ? 'selected' : '' ?>>
<?= htmlspecialchars($p['name']) ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="mb-3">
<label for="quantity" class="form-label fw-semibold">
Correct Quantity <span class="text-danger">*</span>
</label>
<div class="input-group">
<input type="number"
class="form-control"
id="quantity"
name="quantity"
value="<?= (int) $form['quantity'] ?>"
min="1"
required>
<span class="input-group-text" id="unit-label">unit(s)</span>
</div>
</div>
<div class="mb-4">
<label for="notes" class="form-label fw-semibold">Notes / Reason</label>
<input type="text"
class="form-control"
id="notes"
name="notes"
value="<?= htmlspecialchars($form['notes']) ?>"
placeholder="e.g., House #5 Mirpur, Customer: Rahim">
</div>
<div class="d-grid gap-2">
<button type="submit" class="btn btn-warning fw-semibold text-dark py-2">
<i class="bi bi-check-circle me-1"></i> Save Changes
</button>
<a href="tech_dashboard.php" class="btn btn-outline-secondary">Cancel</a>
</div>
</form>
</div>
</div>
</div>
</div>
<script>
(function () {
const select = document.getElementById('product_id');
const unitLabel = document.getElementById('unit-label');
if (!select || !unitLabel) return;
function updateUnit() {
const opt = select.options[select.selectedIndex];
unitLabel.textContent = opt.dataset.unit ? opt.dataset.unit + '(s)' : 'unit(s)';
}
select.addEventListener('change', updateUnit);
updateUnit();
}());
</script>
<?php include 'includes/footer.php'; ?>