34628-vm/view_crop.php
2025-10-03 14:17:07 +00:00

190 lines
7.3 KiB
PHP

<?php
session_start();
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit;
}
require_once 'db/config.php';
include 'includes/header.php';
include 'includes/sidebar.php';
$crop_id = $_GET['id'] ?? null;
$error = '';
$success = '';
if (!$crop_id) {
header('Location: crops.php');
exit;
}
$pdo = db();
// Handle Input Application
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['add_input'])) {
$product_id = $_POST['product_id'] ?? null;
$quantity = $_POST['quantity'] ?? 0;
$application_date = $_POST['application_date'] ?? '';
if (empty($product_id) || empty($quantity) || empty($application_date) || $quantity <= 0) {
$error = 'Por favor, preencha todos os campos para adicionar o insumo.';
} else {
try {
$pdo->beginTransaction();
// 1. Check if there is enough stock
$stmt = $pdo->prepare('SELECT quantity FROM products WHERE id = ?');
$stmt->execute([$product_id]);
$stock_quantity = $stmt->fetchColumn();
if ($stock_quantity < $quantity) {
throw new Exception('Quantidade em estoque insuficiente.');
}
// 2. Add to crop_inputs
$stmt = $pdo->prepare('INSERT INTO crop_inputs (crop_id, product_id, quantity, application_date, user_id) VALUES (?, ?, ?, ?, ?)');
$stmt->execute([$crop_id, $product_id, $quantity, $application_date, $_SESSION['user_id']]);
// 3. Update product stock (create a stock movement)
$stmt = $pdo->prepare('UPDATE products SET quantity = quantity - ? WHERE id = ?');
$stmt->execute([$quantity, $product_id]);
// 4. Log the stock movement
$notes = "Aplicação na lavoura ID: $crop_id";
$stmt = $pdo->prepare('INSERT INTO stock_movements (product_id, type, quantity, user_id, notes) VALUES (?, 'saída', ?, ?, ?)');
$stmt->execute([$product_id, $quantity, $_SESSION['user_id'], $notes]);
$pdo->commit();
$success = 'Insumo aplicado com sucesso!';
} catch (Exception $e) {
$pdo->rollBack();
$error = 'Erro ao aplicar insumo: ' . $e->getMessage();
}
}
}
// Fetch crop details
try {
$stmt = $pdo->prepare('SELECT * FROM crops WHERE id = ?');
$stmt->execute([$crop_id]);
$crop = $stmt->fetch();
if (!$crop) {
header('Location: crops.php');
exit;
}
// Fetch applied inputs
$stmt = $pdo->prepare('
SELECT ci.*, p.name as product_name, p.unit
FROM crop_inputs ci
JOIN products p ON ci.product_id = p.id
WHERE ci.crop_id = ?
ORDER BY ci.application_date DESC
');
$stmt->execute([$crop_id]);
$applied_inputs = $stmt->fetchAll();
// Fetch products for the dropdown
$products = $pdo->query('SELECT id, name, unit, quantity FROM products WHERE quantity > 0 ORDER BY name')->fetchAll();
} catch (PDOException $e) {
$error = "Erro ao buscar dados da lavoura: " . $e->getMessage();
$crop = null;
$applied_inputs = [];
$products = [];
}
?>
<header class="top-bar">
<h1>Detalhes da Lavoura: <?php echo htmlspecialchars($crop['name'] ?? ''); ?></h1>
</header>
<main class="content">
<?php if ($error): ?><p class="error"><?php echo $error; ?></p><?php endif; ?>
<?php if ($success): ?><p class="success"><?php echo $success; ?></p><?php endif; ?>
<div class="card">
<div class="card-header">Informações Gerais</div>
<?php if ($crop): ?>
<p><strong>Cultura:</strong> <?php echo htmlspecialchars($crop['name']); ?></p>
<p><strong>Área:</strong> <?php echo htmlspecialchars($crop['area']); ?> ha</p>
<p><strong>Data de Início:</strong> <?php echo htmlspecialchars(date('d/m/Y', strtotime($crop['start_date']))); ?></p>
<p><strong>Data de Colheita:</strong> <?php echo $crop['end_date'] ? htmlspecialchars(date('d/m/Y', strtotime($crop['end_date']))) : 'Em andamento'; ?></p>
<?php else: ?>
<p>Lavoura não encontrada.</p>
<?php endif; ?>
</div>
<div class="card">
<div class="card-header">Aplicar Insumo</div>
<form action="view_crop.php?id=<?php echo $crop_id; ?>" method="POST">
<div class="form-group">
<label for="product_id">Insumo</label>
<select id="product_id" name="product_id" required>
<option value="">Selecione um insumo</option>
<?php foreach ($products as $product): ?>
<option value="<?php echo htmlspecialchars($product['id']); ?>">
<?php echo htmlspecialchars($product['name'] . ' (' . $product['quantity'] . ' ' . $product['unit'] . ' em estoque)'); ?>
</option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="quantity">Quantidade Aplicada</label>
<input type="number" step="0.01" id="quantity" name="quantity" required>
</div>
<div class="form-group">
<label for="application_date">Data da Aplicação</label>
<input type="date" id="application_date" name="application_date" required>
</div>
<button type="submit" name="add_input" class="btn">Adicionar Insumo</button>
</form>
</div>
<div class="card">
<div class="card-header">Histórico de Insumos Aplicados</div>
<table>
<thead>
<tr>
<th>Data</th>
<th>Produto</th>
<th>Quantidade</th>
</tr>
</thead>
<tbody>
<?php if (empty($applied_inputs)): ?>
<tr><td colspan="3">Nenhum insumo aplicado ainda.</td></tr>
<?php else: ?>
<?php foreach ($applied_inputs as $input): ?>
<tr>
<td><?php echo htmlspecialchars(date('d/m/Y', strtotime($input['application_date']))); ?></td>
<td><?php echo htmlspecialchars($input['product_name']); ?></td>
<td><?php echo htmlspecialchars($input['quantity'] . ' ' . $input['unit']); ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>
</div>
<br>
<a href="crops.php">Voltar para Lavouras</a>
</main>
<style>
.form-group { margin-bottom: 15px; }
.form-group label { display: block; margin-bottom: 5px; }
.form-group input, .form-group select { width: 100%; padding: 8px; box-sizing: border-box; }
.btn { background-color: #27ae60; color: white; padding: 10px 15px; border: none; border-radius: 4px; cursor: pointer; }
.error { color: red; background-color: #fdd; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
.success { color: green; background-color: #dfd; padding: 10px; border-radius: 4px; margin-bottom: 15px; }
table { width: 100%; border-collapse: collapse; margin-top: 20px; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
<?php include 'includes/footer.php'; ?>