<?php
include 'includes/auth.php';
include 'db.php';
include 'includes/header.php';

$id = intval($_GET['id'] ?? 0);
if(!$id){
    echo "<script>alert('Invalid item ID');window.location='perishable_items.php';</script>";
    exit;
}

// Fetch item info
$stmt = $conn->prepare("SELECT * FROM perishables WHERE id=?");
$stmt->bind_param("i", $id);
$stmt->execute();
$item = $stmt->get_result()->fetch_assoc();

if(!$item){
    echo "<script>alert('Item not found');window.location='perishable_items.php';</script>";
    exit;
}

// Handle form submission
$message = '';
if($_SERVER['REQUEST_METHOD'] === 'POST'){
    $name = $conn->real_escape_string(trim($_POST['name']));
    $unit = $conn->real_escape_string(trim($_POST['unit']));
  

    if($name === '' || $unit === '' <= 0){
        $message = "<div class='alert alert-danger'>All fields are required and quantity must be > 0.</div>";
    } else {
        $stmt = $conn->prepare("UPDATE perishables SET name=?, unit=? WHERE id=?");
        $stmt->bind_param("ssi", $name, $unit, $id);
        if($stmt->execute()){
            $message = "<div class='alert alert-success'>Item updated successfully!</div>";
            // Refresh item info
            $item['name'] = $name;
            $item['unit'] = $unit;
            
        } else {
            $message = "<div class='alert alert-danger'>Error updating item.</div>";
        }
    }
}
?>

<div class="container mt-4">
     <button class="btn btn-secondary btn-custom mb-3" onclick="history.back()">
     <i class="fa fa-arrow-left"></i> Back
 </button>
    <h4><i class="fa fa-edit"></i> Edit Perishable Item</h4>
    <hr>
    
    <?= $message ?>

    <form method="POST" class="row g-3">
        <div class="col-md-4">
            <label>Item Name</label>
            <input type="text" name="name" class="form-control" required value="<?= htmlspecialchars($item['name']) ?>">
        </div>

        <div class="col-md-4">
            <label>Unit</label>
            <select name="unit" class="form-control" required>
                <?php
                $units = ['kg', 'g', 'pieces', 'liters', 'ml'];
                foreach($units as $u){
                    $selected = ($item['unit'] === $u) ? 'selected' : '';
                    echo "<option value='$u' $selected>$u</option>";
                }
                ?>
            </select>
        </div>

        <div class="col-md-4">
            

        <div class="col-12 mt-3">
            <button type="submit" class="btn btn-primary"><i class="fa fa-save"></i> Save Changes</button>
            <a href="perishable_items.php" class="btn btn-secondary"><i class="fa fa-arrow-left"></i> Back</a>
        </div>
    </form>
</div>