<?php
$pageTitle = 'Menu Item';
require_once __DIR__ . '/includes/header.php';

$editId = (int)($_GET['id'] ?? 0);
$item = null;
$linkedAddons = [];

if ($editId) {
    $item = $db->query("SELECT * FROM menu_items WHERE id = ? AND restaurant_id = ?", [$editId, $restaurantId])->fetch();
    if (!$item) {
        redirect($baseUrl . '/restaurant-admin/items.php');
        exit;
    }
    $pageTitle = 'Edit Item';
    $linkedAddonResult = $db->query("SELECT addon_group_id FROM item_addon_groups WHERE menu_item_id = ?", [$editId])->fetchAll();
    $linkedAddons = array_column($linkedAddonResult, 'addon_group_id');
} else {
    $pageTitle = 'Add Item';
}

$categories = $db->query("SELECT id, name FROM categories WHERE restaurant_id = ? AND status = 1 ORDER BY sort_order ASC, name ASC", [$restaurantId])->fetchAll();
$addonGroups = $db->query("SELECT id, name FROM addon_groups WHERE restaurant_id = ? AND status = 1 ORDER BY sort_order ASC, name ASC", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0"><?php echo $editId ? 'Edit Menu Item' : 'Add Menu Item'; ?></h6>
        <small class="text-muted"><?php echo $editId ? 'Update item details' : 'Create a new menu item'; ?></small>
    </div>
    <a href="<?php echo $baseUrl; ?>/restaurant-admin/items.php" class="btn btn-outline-secondary btn-sm"><i class="fas fa-arrow-left me-1"></i>Back to Items</a>
</div>

<form id="itemForm" class="ajax-form" action="<?php echo $baseUrl; ?>/restaurant-admin/item_save.php" method="POST" enctype="multipart/form-data">
    <?php echo $csrf->field(); ?>
    <input type="hidden" name="action" value="<?php echo $editId ? 'edit' : 'add'; ?>">
    <input type="hidden" name="item_id" value="<?php echo $editId; ?>">

    <div class="row">
        <div class="col-lg-8">
            <div class="form-card">
                <div class="card-title"><i class="fas fa-info-circle me-2"></i>Basic Information</div>
                <div class="row">
                    <div class="col-md-8 mb-3">
                        <label class="form-label">Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="name" value="<?php echo sanitize($item['name'] ?? ''); ?>" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Category <span class="text-danger">*</span></label>
                        <select class="form-select" name="category_id" required>
                            <option value="">Select</option>
                            <?php foreach ($categories as $cat): ?>
                            <option value="<?php echo $cat['id']; ?>" <?php echo ($item['category_id'] ?? '') == $cat['id'] ? 'selected' : ''; ?>><?php echo sanitize($cat['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Slug</label>
                        <input type="text" class="form-control" name="slug" id="slug" value="<?php echo sanitize($item['slug'] ?? ''); ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Sort Order</label>
                        <input type="number" class="form-control" name="sort_order" value="<?php echo $item['sort_order'] ?? 0; ?>">
                    </div>
                    <div class="col-12 mb-3">
                        <label class="form-label">Short Description</label>
                        <input type="text" class="form-control" name="short_description" maxlength="500" value="<?php echo sanitize($item['short_description'] ?? ''); ?>">
                    </div>
                    <div class="col-12 mb-3">
                        <label class="form-label">Full Description</label>
                        <textarea class="form-control" name="full_description" rows="4"><?php echo sanitize($item['full_description'] ?? ''); ?></textarea>
                    </div>
                </div>
            </div>

            <div class="form-card">
                <div class="card-title"><i class="fas fa-dollar-sign me-2"></i>Pricing & Inventory</div>
                <div class="row">
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Regular Price <span class="text-danger">*</span></label>
                        <input type="number" step="0.01" class="form-control" name="regular_price" value="<?php echo $item['regular_price'] ?? ''; ?>" required>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Offer Price</label>
                        <input type="number" step="0.01" class="form-control" name="offer_price" value="<?php echo $item['offer_price'] ?? ''; ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Cost Price</label>
                        <input type="number" step="0.01" class="form-control" name="cost_price" value="<?php echo $item['cost_price'] ?? ''; ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Tax Setting</label>
                        <select class="form-select" name="tax_setting">
                            <?php foreach (['default'=>'Default','exempt'=>'Exempt','reduced'=>'Reduced'] as $val => $lbl): ?>
                            <option value="<?php echo $val; ?>" <?php echo ($item['tax_setting'] ?? 'default') === $val ? 'selected' : ''; ?>><?php echo $lbl; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Prep Time (min)</label>
                        <input type="number" class="form-control" name="prep_time" value="<?php echo $item['prep_time'] ?? ''; ?>">
                    </div>
                    <div class="col-md-4 mb-3">
                        <label class="form-label">Calories</label>
                        <input type="number" class="form-control" name="calories" value="<?php echo $item['calories'] ?? ''; ?>">
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Stock Status</label>
                        <select class="form-select" name="stock_status">
                            <?php foreach (['in_stock'=>'In Stock','out_of_stock'=>'Out of Stock','low_stock'=>'Low Stock'] as $val => $lbl): ?>
                            <option value="<?php echo $val; ?>" <?php echo ($item['stock_status'] ?? 'in_stock') === $val ? 'selected' : ''; ?>><?php echo $lbl; ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Stock Quantity</label>
                        <input type="number" class="form-control" name="stock_quantity" value="<?php echo $item['stock_quantity'] ?? ''; ?>">
                    </div>
                    <div class="col-12 mb-3">
                        <label class="form-label">Ingredients</label>
                        <textarea class="form-control" name="ingredients" rows="2"><?php echo sanitize($item['ingredients'] ?? ''); ?></textarea>
                    </div>
                    <div class="col-12 mb-3">
                        <label class="form-label">Allergens</label>
                        <input type="text" class="form-control" name="allergens" value="<?php echo sanitize($item['allergens'] ?? ''); ?>" placeholder="Comma-separated: peanuts, gluten, dairy">
                    </div>
                </div>
            </div>

            <div class="form-card">
                <div class="card-title"><i class="fas fa-image me-2"></i>Images</div>
                <div class="row">
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Main Image</label>
                        <input type="file" class="form-control" name="main_image" accept="image/*" data-preview="#mainImagePreview">
                        <?php if (!empty($item['main_image'])): ?>
                            <img src="<?php echo $baseUrl . '/' . sanitize($item['main_image']); ?>" id="mainImagePreview" class="img-preview mt-2">
                        <?php else: ?>
                            <img src="" id="mainImagePreview" class="img-preview mt-2" style="display:none;">
                        <?php endif; ?>
                    </div>
                    <div class="col-md-6 mb-3">
                        <label class="form-label">Gallery Images</label>
                        <input type="file" class="form-control" name="gallery_images[]" accept="image/*" multiple>
                        <small class="text-muted">Select multiple images for the gallery</small>
                        <?php
                        $galleryImages = json_decode($item['gallery_images'] ?? '[]', true) ?: [];
                        if (!empty($galleryImages)):
                        ?>
                        <div class="d-flex flex-wrap gap-2 mt-2">
                            <?php foreach ($galleryImages as $gi): ?>
                                <img src="<?php echo $baseUrl . '/' . sanitize($gi); ?>" style="width:60px;height:60px;object-fit:cover;border-radius:6px;">
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <div class="form-card">
                <div class="card-title"><i class="fas fa-toggle-on me-2"></i>Status & Tags</div>
                <div class="mb-3">
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="is_available" id="is_available" value="1" <?php echo ($item['is_available'] ?? 1) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Available for Order</label>
                    </div>
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="is_featured" value="1" <?php echo ($item['is_featured'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Featured</label>
                    </div>
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="is_new" value="1" <?php echo ($item['is_new'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">New Item</label>
                    </div>
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="is_bestseller" value="1" <?php echo ($item['is_bestseller'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Bestseller</label>
                    </div>
                    <div class="form-check form-switch mb-2">
                        <input class="form-check-input" type="checkbox" name="is_chefs_choice" value="1" <?php echo ($item['is_chefs_choice'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Chef's Choice</label>
                    </div>
                </div>
                <hr>
                <div class="mb-2 small fw-bold">Dietary Tags</div>
                <div class="mb-3">
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="is_spicy" value="1" <?php echo ($item['is_spicy'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Spicy</label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="is_vegetarian" value="1" <?php echo ($item['is_vegetarian'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Vegetarian</label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="is_vegan" value="1" <?php echo ($item['is_vegan'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Vegan</label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="is_halal" value="1" <?php echo ($item['is_halal'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Halal</label>
                    </div>
                    <div class="form-check mb-1">
                        <input class="form-check-input" type="checkbox" name="is_gluten_free" value="1" <?php echo ($item['is_gluten_free'] ?? 0) ? 'checked' : ''; ?>>
                        <label class="form-check-label">Gluten Free</label>
                    </div>
                </div>
            </div>

            <?php if (!empty($addonGroups)): ?>
            <div class="form-card">
                <div class="card-title"><i class="fas fa-plus-square me-2"></i>Add-on Groups</div>
                <div class="mb-3">
                    <?php foreach ($addonGroups as $ag): ?>
                    <div class="form-check mb-2">
                        <input class="form-check-input" type="checkbox" name="addon_groups[]" value="<?php echo $ag['id']; ?>" id="ag_<?php echo $ag['id']; ?>" <?php echo in_array($ag['id'], $linkedAddons) ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="ag_<?php echo $ag['id']; ?>"><?php echo sanitize($ag['name']); ?></label>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>

            <div class="form-card">
                <button type="submit" class="btn btn-primary w-100" data-submit-text="<i class='fas fa-save me-1'></i>Save Item">
                    <i class="fas fa-save me-1"></i>Save Item
                </button>
                <?php if ($editId): ?>
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/item_save.php?action=duplicate&id=<?php echo $editId; ?>" class="btn btn-outline-secondary w-100 mt-2" onclick="return confirm('Duplicate this item?')">
                    <i class="fas fa-copy me-1"></i>Duplicate Item
                </a>
                <?php endif; ?>
            </div>
        </div>
    </div>
</form>

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