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

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

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

$siteId = getCurrentSiteId();
$errors = [];
$formData = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formData = [
        'item_code' => sanitize($_POST['item_code'] ?? ''),
        'item_name' => sanitize($_POST['item_name'] ?? ''),
        'item_category' => sanitize($_POST['item_category'] ?? ''),
        'unit' => sanitize($_POST['unit'] ?? 'kg'),
    ];
    
    // Validation
    if (empty($formData['item_code'])) {
        $errors[] = 'Item code is required.';
    }
    
    if (empty($formData['item_name'])) {
        $errors[] = 'Item name is required.';
    }
    
    if (empty($errors)) {
        try {
            $db = getDB();
            
            // Check if code already exists
            $stmt = $db->prepare("SELECT item_id FROM inventory_items WHERE site_id = ? AND item_code = ?");
            $stmt->execute([$siteId, $formData['item_code']]);
            if ($stmt->fetch()) {
                $errors[] = 'Item code already exists.';
            } else {
                $stmt = $db->prepare("
                    INSERT INTO inventory_items (
                        site_id, item_code, item_name, item_category, unit
                    ) VALUES (?, ?, ?, ?, ?)
                ");
                $stmt->execute([
                    $siteId,
                    $formData['item_code'],
                    $formData['item_name'],
                    $formData['item_category'] ?: null,
                    $formData['unit']
                ]);
                
                logAudit('CREATE', 'inventory_items', $db->lastInsertId());
                
                redirect(BASE_URL . '/admin/inventory_items.php', 'Inventory item created successfully.');
            }
            
        } catch (Exception $e) {
            error_log("Error creating inventory item: " . $e->getMessage());
            $errors[] = 'An error occurred while creating inventory item. Please try again.';
        }
    }
}

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

<div class="card">
    <div class="card-header">
        <h2 class="card-title">Add 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" for="item_code">Item Code *</label>
                <input type="text" id="item_code" name="item_code" class="form-control" required
                       value="<?php echo htmlspecialchars($formData['item_code'] ?? ''); ?>"
                       placeholder="e.g., RICE, DAL, OIL">
            </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'] ?? ''); ?>"
                       placeholder="e.g., Basmati Rice, Toor Dal">
            </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'] ?? ''); ?>"
                       placeholder="e.g., Grains, Pulses, Spices">
            </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'] ?? 'kg') === 'kg' ? 'selected' : ''; ?>>kg</option>
                    <option value="g" <?php echo ($formData['unit'] ?? '') === 'g' ? 'selected' : ''; ?>>g</option>
                    <option value="ltr" <?php echo ($formData['unit'] ?? '') === 'ltr' ? 'selected' : ''; ?>>ltr</option>
                    <option value="ml" <?php echo ($formData['unit'] ?? '') === 'ml' ? 'selected' : ''; ?>>ml</option>
                    <option value="pcs" <?php echo ($formData['unit'] ?? '') === 'pcs' ? 'selected' : ''; ?>>pcs</option>
                    <option value="pack" <?php echo ($formData['unit'] ?? '') === 'pack' ? 'selected' : ''; ?>>pack</option>
                </select>
            </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">Create Inventory Item</button>
        </div>
    </form>
</div>

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

