<?php
include 'db.php';
include 'auth.php';
require_right('Access POS');

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Handle form submissions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['action'])) {
        switch ($_POST['action']) {
            case 'add_group':
                $name = trim($_POST['group_name']);
                $display_name = trim($_POST['display_name']);
                $description = trim($_POST['description']);
                $is_required = isset($_POST['is_required']) ? 1 : 0;
                $is_multiple_choice = isset($_POST['is_multiple_choice']) ? 1 : 0;
                $max_selections = !empty($_POST['max_selections']) ? intval($_POST['max_selections']) : NULL;
                $min_selections = intval($_POST['min_selections']);
                $sort_order = intval($_POST['sort_order']);
                
                if (!empty($name) && !empty($display_name)) {
                    $stmt = $conn->prepare("INSERT INTO item_modifier_groups (name, display_name, description, is_required, is_multiple_choice, max_selections, min_selections, sort_order) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("sssiiiii", $name, $display_name, $description, $is_required, $is_multiple_choice, $max_selections, $min_selections, $sort_order);
                    if ($stmt->execute()) {
                        $success_message = "Modifier group added successfully!";
                    } else {
                        $error_message = "Error adding modifier group: " . $stmt->error;
                    }
                }
                break;
                
            case 'update_group':
                $group_id = intval($_POST['group_id']);
                $name = trim($_POST['group_name']);
                $display_name = trim($_POST['display_name']);
                $description = trim($_POST['description']);
                $is_required = isset($_POST['is_required']) ? 1 : 0;
                $is_multiple_choice = isset($_POST['is_multiple_choice']) ? 1 : 0;
                $max_selections = !empty($_POST['max_selections']) ? intval($_POST['max_selections']) : NULL;
                $min_selections = intval($_POST['min_selections']);
                $sort_order = intval($_POST['sort_order']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!empty($name) && !empty($display_name)) {
                    $stmt = $conn->prepare("UPDATE item_modifier_groups SET name = ?, display_name = ?, description = ?, is_required = ?, is_multiple_choice = ?, max_selections = ?, min_selections = ?, sort_order = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("sssiiiiiii", $name, $display_name, $description, $is_required, $is_multiple_choice, $max_selections, $min_selections, $sort_order, $is_active, $group_id);
                    if ($stmt->execute()) {
                        $success_message = "Modifier group updated successfully!";
                    } else {
                        $error_message = "Error updating modifier group: " . $stmt->error;
                    }
                }
                break;
                
            case 'delete_group':
                $group_id = intval($_POST['group_id']);
                // Check if group has modifiers
                $check = $conn->prepare("SELECT COUNT(*) as count FROM item_modifiers WHERE modifier_group_id = ?");
                $check->bind_param("i", $group_id);
                $check->execute();
                $result = $check->get_result()->fetch_assoc();
                
                if ($result['count'] > 0) {
                    $error_message = "Cannot delete group. Please delete all modifiers in this group first.";
                } else {
                    $stmt = $conn->prepare("DELETE FROM item_modifier_groups WHERE id = ?");
                    $stmt->bind_param("i", $group_id);
                    if ($stmt->execute()) {
                        $success_message = "Modifier group deleted successfully!";
                    } else {
                        $error_message = "Error deleting modifier group: " . $stmt->error;
                    }
                }
                break;
                
            case 'add_modifier':
                $modifier_group_id = intval($_POST['modifier_group_id']);
                $name = trim($_POST['modifier_name']);
                $short_name = trim($_POST['short_name']);
                $price_adjustment = floatval($_POST['price_adjustment']);
                $cost_adjustment = floatval($_POST['cost_adjustment']);
                $is_default = isset($_POST['is_default']) ? 1 : 0;
                $sort_order = intval($_POST['sort_order']);
                $prep_time_adjustment = intval($_POST['prep_time_adjustment']);
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("INSERT INTO item_modifiers (modifier_group_id, name, short_name, price_adjustment, cost_adjustment, is_default, sort_order, prep_time_adjustment) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("issddiid", $modifier_group_id, $name, $short_name, $price_adjustment, $cost_adjustment, $is_default, $sort_order, $prep_time_adjustment);
                    if ($stmt->execute()) {
                        $success_message = "Modifier added successfully!";
                    } else {
                        $error_message = "Error adding modifier: " . $stmt->error;
                    }
                }
                break;
                
            case 'update_modifier':
                $modifier_id = intval($_POST['modifier_id']);
                $name = trim($_POST['modifier_name']);
                $short_name = trim($_POST['short_name']);
                $price_adjustment = floatval($_POST['price_adjustment']);
                $cost_adjustment = floatval($_POST['cost_adjustment']);
                $is_default = isset($_POST['is_default']) ? 1 : 0;
                $sort_order = intval($_POST['sort_order']);
                $prep_time_adjustment = intval($_POST['prep_time_adjustment']);
                $is_active = isset($_POST['is_active']) ? 1 : 0;
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("UPDATE item_modifiers SET name = ?, short_name = ?, price_adjustment = ?, cost_adjustment = ?, is_default = ?, sort_order = ?, prep_time_adjustment = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("ssddiiiii", $name, $short_name, $price_adjustment, $cost_adjustment, $is_default, $sort_order, $prep_time_adjustment, $is_active, $modifier_id);
                    if ($stmt->execute()) {
                        $success_message = "Modifier updated successfully!";
                    } else {
                        $error_message = "Error updating modifier: " . $stmt->error;
                    }
                }
                break;
                
            case 'delete_modifier':
                $modifier_id = intval($_POST['modifier_id']);
                $stmt = $conn->prepare("DELETE FROM item_modifiers WHERE id = ?");
                $stmt->bind_param("i", $modifier_id);
                if ($stmt->execute()) {
                    $success_message = "Modifier deleted successfully!";
                } else {
                    $error_message = "Error deleting modifier: " . $stmt->error;
                }
                break;
        }
    }
}

// Get modifier groups
$groups = $conn->query("SELECT * FROM item_modifier_groups ORDER BY sort_order, name");

// Get items for assignment
$items = $conn->query("SELECT id, name, category_id FROM items WHERE item_role != 'material' ORDER BY name");
$categories = $conn->query("SELECT id, name FROM categories ORDER BY name");

include 'layout.php';
?>

<div class="page-wrapper">
    <div class="content">
        <div class="page-header">
            <div class="page-title">
                <h4>Item Modifier Management</h4>
                <h6>Manage item choices, extras, and variations</h6>
            </div>
            <div class="page-btn">
                <a href="pos.php" class="btn btn-secondary">
                    <i class="feather feather-arrow-left me-2"></i>Back to POS
                </a>
            </div>
        </div>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                <i class="feather feather-check-circle me-2"></i><?= htmlspecialchars($success_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                <i class="feather feather-alert-circle me-2"></i><?= htmlspecialchars($error_message) ?>
                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
            </div>
        <?php endif; ?>

        <!-- Navigation Tabs -->
        <div class="card">
            <div class="card-body">
                <ul class="nav nav-tabs nav-tabs-solid nav-justified" role="tablist">
                    <li class="nav-item" role="presentation">
                        <a class="nav-link active" data-bs-toggle="tab" href="#groups" role="tab">
                            <i class="feather feather-grid me-2"></i>Modifier Groups
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#modifiers" role="tab" id="modifiers-tab">
                            <i class="feather feather-list me-2"></i>Modifiers
                        </a>
                    </li>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#assignments" role="tab" id="assignments-tab">
                            <i class="feather feather-link me-2"></i>Item Assignments
                        </a>
                    </li>
                </ul>

                <div class="tab-content">
                    <!-- Groups Tab -->
                    <div class="tab-pane fade show active" id="groups" role="tabpanel">
                        <div class="row">
                            <div class="col-md-4">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-plus me-2"></i>Add Modifier Group
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <form method="POST">
                                            <input type="hidden" name="action" value="add_group">
                                            
                                            <div class="form-group">
                                                <label>Group Name (Internal)</label>
                                                <input type="text" class="form-control" name="group_name" required placeholder="e.g., pizza_size">
                                                <small class="text-muted">Used for system identification</small>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Display Name</label>
                                                <input type="text" class="form-control" name="display_name" required placeholder="e.g., Pizza Size">
                                                <small class="text-muted">Shown to customers</small>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Description</label>
                                                <textarea class="form-control" name="description" rows="2" placeholder="Optional description"></textarea>
                                            </div>
                                            
                                            <div class="form-group">
                                                <div class="form-check">
                                                    <input type="checkbox" class="form-check-input" name="is_required" id="is_required">
                                                    <label class="form-check-label" for="is_required">Required Choice</label>
                                                </div>
                                                <small class="text-muted">Customer must select an option</small>
                                            </div>
                                            
                                            <div class="form-group">
                                                <div class="form-check">
                                                    <input type="checkbox" class="form-check-input" name="is_multiple_choice" id="is_multiple_choice">
                                                    <label class="form-check-label" for="is_multiple_choice">Multiple Choice</label>
                                                </div>
                                                <small class="text-muted">Allow multiple selections</small>
                                            </div>
                                            
                                            <div class="row">
                                                <div class="col-6">
                                                    <div class="form-group">
                                                        <label>Min Selections</label>
                                                        <input type="number" class="form-control" name="min_selections" value="1" min="0">
                                                    </div>
                                                </div>
                                                <div class="col-6">
                                                    <div class="form-group">
                                                        <label>Max Selections</label>
                                                        <input type="number" class="form-control" name="max_selections" placeholder="Unlimited">
                                                    </div>
                                                </div>
                                            </div>
                                            
                                            <div class="form-group">
                                                <label>Sort Order</label>
                                                <input type="number" class="form-control" name="sort_order" value="0">
                                            </div>
                                            
                                            <button type="submit" class="btn btn-primary">
                                                <i class="feather feather-plus me-2"></i>Add Group
                                            </button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="col-md-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-list me-2"></i>Existing Groups
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Display Name</th>
                                                        <th>Type</th>
                                                        <th>Required</th>
                                                        <th>Status</th>
                                                        <th>Sort</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php mysqli_data_seek($groups, 0); while ($group = $groups->fetch_assoc()): ?>
                                                    <tr>
                                                        <td>
                                                            <strong><?= htmlspecialchars($group['display_name']) ?></strong>
                                                            <br><small class="text-muted"><?= htmlspecialchars($group['name']) ?></small>
                                                        </td>
                                                        <td>
                                                            <?php if ($group['is_multiple_choice']): ?>
                                                                <span class="badge bg-info">Multiple Choice</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-primary">Single Choice</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($group['is_required']): ?>
                                                                <span class="badge bg-warning">Required</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-secondary">Optional</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <?php if ($group['is_active']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-secondary">Inactive</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td><?= $group['sort_order'] ?></td>
                                                        <td>
                                                            <button class="btn btn-sm btn-primary" onclick="editGroup(<?= htmlspecialchars(json_encode($group)) ?>)">
                                                                <i class="feather feather-edit"></i>
                                                            </button>
                                                            <form method="POST" style="display: inline;">
                                                                <input type="hidden" name="action" value="delete_group">
                                                                <input type="hidden" name="group_id" value="<?= $group['id'] ?>">
                                                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Are you sure you want to delete this group?')">
                                                                    <i class="feather feather-trash-2"></i>
                                                                </button>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                    <?php endwhile; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Modifiers Tab -->
                    <div class="tab-pane fade" id="modifiers" role="tabpanel">
                        <div class="card">
                            <div class="card-header d-flex justify-content-between align-items-center">
                                <h5 class="card-title mb-0">
                                    <i class="feather feather-list me-2"></i>Modifier Options
                                </h5>
                                <button class="btn btn-primary" onclick="showAddModifierModal()">
                                    <i class="feather feather-plus me-2"></i>Add Modifier
                                </button>
                            </div>
                            <div class="card-body">
                                <div class="table-responsive">
                                    <table class="table table-hover" id="modifiersTable">
                                        <thead>
                                            <tr>
                                                <th>Group</th>
                                                <th>Name</th>
                                                <th>Short Name</th>
                                                <th>Price Adjustment</th>
                                                <th>Default</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="modifiers_table">
                                            <!-- Modifiers will be loaded here via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Assignments Tab -->
                    <div class="tab-pane fade" id="assignments" role="tabpanel">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title mb-0">
                                    <i class="feather feather-link me-2"></i>Item to Modifier Group Assignments
                                </h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">Assign modifier groups to specific items to show choices when ordering.</p>
                                
                                <div class="row mb-3">
                                    <div class="col-md-4">
                                        <label for="category_filter" class="form-label">Filter by Category</label>
                                        <select class="form-control" id="category_filter">
                                            <option value="">All Categories</option>
                                            <?php mysqli_data_seek($categories, 0); while ($cat = $categories->fetch_assoc()): ?>
                                                <option value="<?= $cat['id'] ?>"><?= htmlspecialchars($cat['name']) ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label for="group_filter" class="form-label">Filter by Group</label>
                                        <select class="form-control" id="group_filter">
                                            <option value="">All Groups</option>
                                            <?php mysqli_data_seek($groups, 0); while ($group = $groups->fetch_assoc()): ?>
                                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['display_name']) ?></option>
                                            <?php endwhile; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4">
                                        <label for="search_items" class="form-label">Search Items</label>
                                        <input type="text" class="form-control" id="search_items" placeholder="Search items...">
                                    </div>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover">
                                        <thead class="table-dark">
                                            <tr>
                                                <th>Item</th>
                                                <th>Category</th>
                                                <th>Assigned Groups</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="assignments_table">
                                            <!-- Items will be loaded here via AJAX -->
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Edit Group Modal -->
<div class="modal fade" id="editGroupModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Modifier Group</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_group">
                    <input type="hidden" name="group_id" id="edit_group_id">
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Group Name (Internal)</label>
                                <input type="text" class="form-control" name="group_name" id="edit_group_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Display Name</label>
                                <input type="text" class="form-control" name="display_name" id="edit_display_name" required>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Description</label>
                        <textarea class="form-control" name="description" id="edit_description" rows="2"></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check mb-2">
                                <input type="checkbox" class="form-check-input" name="is_required" id="edit_is_required">
                                <label class="form-check-label" for="edit_is_required">Required Choice</label>
                            </div>
                            <div class="form-check mb-2">
                                <input type="checkbox" class="form-check-input" name="is_multiple_choice" id="edit_is_multiple_choice">
                                <label class="form-check-label" for="edit_is_multiple_choice">Multiple Choice</label>
                            </div>
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" name="is_active" id="edit_is_active">
                                <label class="form-check-label" for="edit_is_active">Active</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Min Selections</label>
                                <input type="number" class="form-control" name="min_selections" id="edit_min_selections" min="0">
                            </div>
                            <div class="form-group">
                                <label>Max Selections</label>
                                <input type="number" class="form-control" name="max_selections" id="edit_max_selections">
                            </div>
                            <div class="form-group">
                                <label>Sort Order</label>
                                <input type="number" class="form-control" name="sort_order" id="edit_sort_order">
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Group</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Modifier Modal -->
<div class="modal fade" id="addModifierModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Modifier</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="add_modifier">
                    
                    <div class="form-group">
                        <label>Modifier Group</label>
                        <select class="form-control" name="modifier_group_id" required>
                            <option value="">Select Group</option>
                            <?php mysqli_data_seek($groups, 0); while ($group = $groups->fetch_assoc()): ?>
                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['display_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Modifier Name</label>
                                <input type="text" class="form-control" name="modifier_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Short Name (Kitchen Display)</label>
                                <input type="text" class="form-control" name="short_name" placeholder="Optional">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Price Adjustment</label>
                                <input type="number" class="form-control" name="price_adjustment" step="0.01" value="0.00">
                                <small class="text-muted">Amount to add/subtract from base price</small>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Cost Adjustment</label>
                                <input type="number" class="form-control" name="cost_adjustment" step="0.01" value="0.00">
                                <small class="text-muted">Impact on item cost</small>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Sort Order</label>
                                <input type="number" class="form-control" name="sort_order" value="0">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Prep Time Adjustment (minutes)</label>
                                <input type="number" class="form-control" name="prep_time_adjustment" value="0">
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="is_default" id="add_is_default">
                        <label class="form-check-label" for="add_is_default">Default Selection</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Add Modifier</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Modifier Modal -->
<div class="modal fade" id="editModifierModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Modifier</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form method="POST">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_modifier">
                    <input type="hidden" name="modifier_id" id="edit_modifier_id">
                    
                    <div class="form-group">
                        <label>Modifier Group</label>
                        <select class="form-control" name="modifier_group_id" id="edit_modifier_group_id" required>
                            <?php mysqli_data_seek($groups, 0); while ($group = $groups->fetch_assoc()): ?>
                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['display_name']) ?></option>
                            <?php endwhile; ?>
                        </select>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Modifier Name</label>
                                <input type="text" class="form-control" name="modifier_name" id="edit_modifier_name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Short Name (Kitchen Display)</label>
                                <input type="text" class="form-control" name="short_name" id="edit_modifier_short_name">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Price Adjustment</label>
                                <input type="number" class="form-control" name="price_adjustment" id="edit_modifier_price" step="0.01">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Cost Adjustment</label>
                                <input type="number" class="form-control" name="cost_adjustment" id="edit_modifier_cost" step="0.01">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Sort Order</label>
                                <input type="number" class="form-control" name="sort_order" id="edit_modifier_sort">
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-group">
                                <label>Prep Time Adjustment (minutes)</label>
                                <input type="number" class="form-control" name="prep_time_adjustment" id="edit_modifier_prep_time">
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" name="is_default" id="edit_modifier_is_default">
                                <label class="form-check-label" for="edit_modifier_is_default">Default Selection</label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input" name="is_active" id="edit_modifier_is_active">
                                <label class="form-check-label" for="edit_modifier_is_active">Active</label>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-primary">Update Modifier</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Manage Item Groups Modal -->
<div class="modal fade" id="manageItemGroupsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="manageItemGroupsTitle">Manage Item Groups</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" id="manage_item_id">
                
                <div class="alert alert-info">
                    <i class="feather feather-info me-2"></i>
                    Select which modifier groups should be available for this item.
                </div>
                
                <div id="available_groups">
                    <!-- Groups will be loaded here -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary" onclick="saveItemGroupAssignments()">Save Changes</button>
            </div>
        </div>
    </div>
</div>

<script>
// Edit group function
function editGroup(group) {
    document.getElementById('edit_group_id').value = group.id;
    document.getElementById('edit_group_name').value = group.name;
    document.getElementById('edit_display_name').value = group.display_name;
    document.getElementById('edit_description').value = group.description || '';
    document.getElementById('edit_is_required').checked = group.is_required == 1;
    document.getElementById('edit_is_multiple_choice').checked = group.is_multiple_choice == 1;
    document.getElementById('edit_is_active').checked = group.is_active == 1;
    document.getElementById('edit_min_selections').value = group.min_selections;
    document.getElementById('edit_max_selections').value = group.max_selections || '';
    document.getElementById('edit_sort_order').value = group.sort_order;
    
    new bootstrap.Modal(document.getElementById('editGroupModal')).show();
}

// Show add modifier modal
function showAddModifierModal() {
    new bootstrap.Modal(document.getElementById('addModifierModal')).show();
}

// Load modifiers when tab is shown
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('modifiers-tab').addEventListener('shown.bs.tab', function() {
        loadModifiers();
    });
    
    document.getElementById('assignments-tab').addEventListener('shown.bs.tab', function() {
        loadAssignments();
    });
    
    // Filter event listeners for assignments
    document.getElementById('category_filter').addEventListener('change', loadAssignments);
    document.getElementById('group_filter').addEventListener('change', loadAssignments);
    document.getElementById('search_items').addEventListener('input', loadAssignments);
});

// Load modifiers function
function loadModifiers() {
    fetch('ajax/get_modifiers.php')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayModifiers(data.modifiers);
            } else {
                console.error('Error loading modifiers:', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// Display modifiers function
function displayModifiers(modifiers) {
    const tbody = document.getElementById('modifiers_table');
    let html = '';
    
    modifiers.forEach(modifier => {
        html += `
            <tr>
                <td><span class="badge bg-info">${modifier.group_name}</span></td>
                <td>${modifier.name}</td>
                <td>${modifier.short_name || '-'}</td>
                <td class="${modifier.price_adjustment > 0 ? 'text-success' : modifier.price_adjustment < 0 ? 'text-danger' : ''}">
                    ${modifier.price_adjustment > 0 ? '+' : ''}${modifier.price_adjustment}
                </td>
                <td>
                    ${modifier.is_default ? '<span class="badge bg-warning">Default</span>' : '-'}
                </td>
                <td>
                    ${modifier.is_active ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'}
                </td>
                <td>
                    <button class="btn btn-sm btn-primary" onclick="editModifier(${modifier.id})">
                        <i class="feather feather-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-danger" onclick="deleteModifier(${modifier.id})">
                        <i class="feather feather-trash-2"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    tbody.innerHTML = html;
}

// Load assignments function
function loadAssignments() {
    const categoryFilter = document.getElementById('category_filter').value;
    const groupFilter = document.getElementById('group_filter').value;
    const searchFilter = document.getElementById('search_items').value;
    
    const params = new URLSearchParams();
    if (categoryFilter) params.append('category', categoryFilter);
    if (groupFilter) params.append('group', groupFilter);
    if (searchFilter) params.append('search', searchFilter);
    
    fetch(`ajax/get_modifier_assignments.php?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayAssignments(data.assignments);
            } else {
                console.error('Error loading assignments:', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}

// Display assignments function
function displayAssignments(assignments) {
    const tbody = document.getElementById('assignments_table');
    let html = '';
    
    assignments.forEach(item => {
        html += `
            <tr>
                <td>${item.name}</td>
                <td>${item.category_name}</td>
                <td>
                    ${item.assigned_groups.map(group => 
                        `<span class="badge bg-primary me-1">${group.display_name}</span>`
                    ).join('')}
                    ${item.assigned_groups.length === 0 ? '<span class="text-muted">No groups assigned</span>' : ''}
                </td>
                <td>
                    <button class="btn btn-sm btn-outline-primary" onclick="manageItemGroups(${item.id}, '${item.name}')">
                        <i class="feather feather-settings"></i> Manage
                    </button>
                </td>
            </tr>
        `;
    });
    
    tbody.innerHTML = html;
}

// Edit modifier function
function editModifier(id) {
    fetch(`ajax/get_modifier_details.php?id=${id}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const modifier = data.modifier;
                document.getElementById('edit_modifier_id').value = modifier.id;
                document.getElementById('edit_modifier_group_id').value = modifier.modifier_group_id;
                document.getElementById('edit_modifier_name').value = modifier.name;
                document.getElementById('edit_modifier_short_name').value = modifier.short_name || '';
                document.getElementById('edit_modifier_price').value = modifier.price_adjustment;
                document.getElementById('edit_modifier_cost').value = modifier.cost_adjustment;
                document.getElementById('edit_modifier_sort').value = modifier.sort_order;
                document.getElementById('edit_modifier_prep_time').value = modifier.prep_time_adjustment;
                document.getElementById('edit_modifier_is_default').checked = modifier.is_default == 1;
                document.getElementById('edit_modifier_is_active').checked = modifier.is_active == 1;
                
                new bootstrap.Modal(document.getElementById('editModifierModal')).show();
            } else {
                alert('Error loading modifier: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
}

function deleteModifier(id) {
    if (confirm('Are you sure you want to delete this modifier?')) {
        fetch('ajax/delete_modifier.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ modifier_id: id })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('Modifier deleted successfully!');
                loadModifiers(); // Reload the table
            } else {
                alert('Error deleting modifier: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
    }
}

function manageItemGroups(itemId, itemName) {
    document.getElementById('manage_item_id').value = itemId;
    document.getElementById('manageItemGroupsTitle').textContent = `Manage Groups for: ${itemName}`;
    
    // Load available groups and current assignments
    fetch(`ajax/get_item_group_assignments.php?item_id=${itemId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayAvailableGroups(data.groups, data.assigned_group_ids);
                new bootstrap.Modal(document.getElementById('manageItemGroupsModal')).show();
            } else {
                alert('Error loading group assignments: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
}

function displayAvailableGroups(groups, assignedIds) {
    const container = document.getElementById('available_groups');
    let html = '';
    
    groups.forEach(group => {
        const isAssigned = assignedIds.includes(group.id);
        html += `
            <div class="card mb-3">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <div class="form-check">
                                <input type="checkbox" class="form-check-input group-checkbox" 
                                       id="group_${group.id}" value="${group.id}" ${isAssigned ? 'checked' : ''}>
                                <label class="form-check-label" for="group_${group.id}">
                                    <strong>${group.display_name}</strong>
                                </label>
                            </div>
                            <small class="text-muted">${group.description || ''}</small>
                            <div class="mt-2">
                                ${group.is_required ? '<span class="badge bg-warning me-1">Required</span>' : ''}
                                ${group.is_multiple_choice ? '<span class="badge bg-info">Multiple Choice</span>' : '<span class="badge bg-primary">Single Choice</span>'}
                            </div>
                        </div>
                        <div class="text-end" style="display: ${isAssigned ? 'block' : 'none'};" id="options_${group.id}">
                            <div class="form-check form-check-inline">
                                <input type="checkbox" class="form-check-input" id="required_${group.id}" 
                                       ${group.assignment_required ? 'checked' : ''}>
                                <label class="form-check-label" for="required_${group.id}">
                                    <small>Required for this item</small>
                                </label>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `;
    });
    
    container.innerHTML = html;
    
    // Add event listeners for checkboxes
    document.querySelectorAll('.group-checkbox').forEach(checkbox => {
        checkbox.addEventListener('change', function() {
            const groupId = this.value;
            const optionsDiv = document.getElementById(`options_${groupId}`);
            optionsDiv.style.display = this.checked ? 'block' : 'none';
        });
    });
}

function saveItemGroupAssignments() {
    const itemId = document.getElementById('manage_item_id').value;
    const assignments = [];
    
    document.querySelectorAll('.group-checkbox:checked').forEach(checkbox => {
        const groupId = parseInt(checkbox.value);
        const isRequired = document.getElementById(`required_${groupId}`).checked;
        assignments.push({
            modifier_group_id: groupId,
            is_required: isRequired ? 1 : 0
        });
    });
    
    fetch('ajax/save_item_group_assignments.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            item_id: itemId,
            assignments: assignments
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Group assignments saved successfully!');
            bootstrap.Modal.getInstance(document.getElementById('manageItemGroupsModal')).hide();
            loadAssignments(); // Reload the assignments table
        } else {
            alert('Error saving assignments: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Network error occurred');
    });
}
</script>

