<?php
/**
 * Enterprise HRM ERP System - Edit Inventory Item
 */

require_once __DIR__ . '/../includes/init.php';
require_once __DIR__ . '/check_admin_access.php';

$pageTitle = 'Edit Inventory Item';
$currentModule = 'settings';

$siteId = getCurrentSiteId();
$itemId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($itemId <= 0) {
    redirect(BASE_URL . '/admin/inventory_items.php', 'Invalid item ID.', 'error');
}

// Get item
try {
    $db = getDB();
    $stmt = $db->prepare("SELECT * FROM inventory_items WHERE item_id = ? AND site_id = ?");
    $stmt->execute([$itemId, $siteId]);
    $item = $stmt->fetch();
    
    if (!$item) {
        redirect(BASE_URL . '/admin/inventory_items.php', 'Inventory item not found.', 'error');
    }
    
    $formData = $item;
    
} catch (Exception $e) {
    error_log("Error loading item: " . $e->getMessage());
    redirect(BASE_URL . '/admin/inventory_items.php', 'Error loading inventory item data.', 'error');
}

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'item_name' => sanitize($_POST['item_name'] ?? ''),
        'item_category' => sanitize($_POST['item_category'] ?? ''),
        'unit' => sanitize($_POST['unit'] ?? 'kg'),
        'is_active' => isset($_POST['is_active']) ? 1 : 0,
    ];
    
    // Validation
    if (empty($formData['item_name'])) {
        $errors[] = 'Item name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            $stmt = $db->prepare("
                UPDATE inventory_items SET
                    item_name = ?,
                    item_category = ?,
                    unit = ?,
                    is_active = ?,
                    updated_at = NOW()
                WHERE item_id = ? AND site_id = ?
            ");
            $stmt->execute([
                $formData['item_name'],
                $formData['item_category'] ?: null,
                $formData['unit'],
                $formData['is_active'],
                $itemId,
                $siteId
            ]);
            
            logAudit('UPDATE', 'inventory_items', $itemId);
            
            redirect(BASE_URL . '/admin/inventory_items.php', 'Inventory item updated successfully.');
            
        } catch (Exception $e) {
            error_log("Error updating item: " . $e->getMessage());
            $errors[] = 'An error occurred while updating inventory item. Please try again.';
        }
    }
}

include __DIR__ . '/../includes/header.php';
?>

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Edit Inventory Item</h2>
        <a href="<?php echo BASE_URL; ?>/admin/inventory_items.php" class="btn btn-secondary">Back to Inventory Items</a>
    </div>
    
    <?php if (!empty($errors)): ?>
    <div class="alert alert-error">
        <ul style="margin: 0; padding-left: 20px;">
            <?php foreach ($errors as $error): ?>
            <li><?php echo htmlspecialchars($error); ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <form method="POST" style="margin-top: 20px;">
        <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px;">
            <div class="form-group">
                <label class="form-label">Item Code</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($item['item_code']); ?>" disabled>
            </div>
            
            <div class="form-group">
                <label class="form-label" for="item_name">Item Name *</label>
                <input type="text" id="item_name" name="item_name" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['item_name'] ?? $item['item_name']); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="item_category">Category</label>
                <input type="text" id="item_category" name="item_category" class="form-control"
                       value="<?php echo htmlspecialchars($formData['item_category'] ?? $item['item_category'] ?? ''); ?>">
            </div>
            
            <div class="form-group">
                <label class="form-label" for="unit">Unit *</label>
                <select id="unit" name="unit" class="form-control" required>
                    <option value="kg" <?php echo ($formData['unit'] ?? $item['unit']) === 'kg' ? 'selected' : ''; ?>>kg</option>
                    <option value="g" <?php echo ($formData['unit'] ?? $item['unit']) === 'g' ? 'selected' : ''; ?>>g</option>
                    <option value="ltr" <?php echo ($formData['unit'] ?? $item['unit']) === 'ltr' ? 'selected' : ''; ?>>ltr</option>
                    <option value="ml" <?php echo ($formData['unit'] ?? $item['unit']) === 'ml' ? 'selected' : ''; ?>>ml</option>
                    <option value="pcs" <?php echo ($formData['unit'] ?? $item['unit']) === 'pcs' ? 'selected' : ''; ?>>pcs</option>
                    <option value="pack" <?php echo ($formData['unit'] ?? $item['unit']) === 'pack' ? 'selected' : ''; ?>>pack</option>
                </select>
            </div>
            
            <div class="form-group">
                <label style="display: flex; align-items: center; gap: 10px; cursor: pointer;">
                    <input type="checkbox" id="is_active" name="is_active" value="1" 
                           <?php echo ($formData['is_active'] ?? $item['is_active']) ? 'checked' : ''; ?>>
                    <span>Active</span>
                </label>
            </div>
        </div>
        
        <div style="margin-top: 30px; text-align: right; padding-top: 20px; border-top: 1px solid var(--border-color);">
            <a href="<?php echo BASE_URL; ?>/admin/inventory_items.php" class="btn btn-secondary">Cancel</a>
            <button type="submit" class="btn btn-primary">Update Inventory Item</button>
        </div>
    </form>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>

