<?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':
                $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)) {
                    // Insert the modifier (no group assignment needed)
                    $stmt = $conn->prepare("INSERT INTO item_modifiers (name, short_name, price_adjustment, cost_adjustment, is_default, sort_order, prep_time_adjustment) VALUES (?, ?, ?, ?, ?, ?, ?)");
                    $stmt->bind_param("ssddiid", $name, $short_name, $price_adjustment, $cost_adjustment, $is_default, $sort_order, $prep_time_adjustment);
                    
                    if ($stmt->execute()) {
                        $success_message = "Modifier added successfully! Use the Modifier Library tab to assign it to groups.";
                    } 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;
                
            // Template operations
            case 'add_template':
                $name = trim($_POST['template_name']);
                $icon = trim($_POST['template_icon']);
                $sort_order = intval($_POST['template_sort_order']);
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("INSERT INTO modifier_templates (name, icon, sort_order) VALUES (?, ?, ?)");
                    $stmt->bind_param("ssi", $name, $icon, $sort_order);
                    if ($stmt->execute()) {
                        $success_message = "Template added successfully!";
                    } else {
                        $error_message = "Error adding template: " . $stmt->error;
                    }
                }
                break;
                
            case 'update_template':
                $template_id = intval($_POST['template_id']);
                $name = trim($_POST['template_name']);
                $icon = trim($_POST['template_icon']);
                $sort_order = intval($_POST['template_sort_order']);
                $is_active = isset($_POST['template_is_active']) ? 1 : 0;
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("UPDATE modifier_templates SET name = ?, icon = ?, sort_order = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("ssiii", $name, $icon, $sort_order, $is_active, $template_id);
                    if ($stmt->execute()) {
                        $success_message = "Template updated successfully!";
                    } else {
                        $error_message = "Error updating template: " . $stmt->error;
                    }
                }
                break;
                
            case 'delete_template':
                $template_id = intval($_POST['template_id']);
                // Check if template has options
                $check = $conn->prepare("SELECT COUNT(*) as count FROM modifier_template_options WHERE template_id = ?");
                $check->bind_param("i", $template_id);
                $check->execute();
                $result = $check->get_result()->fetch_assoc();
                
                if ($result['count'] > 0) {
                    $error_message = "Cannot delete template. Please delete all options first.";
                } else {
                    $stmt = $conn->prepare("DELETE FROM modifier_templates WHERE id = ?");
                    $stmt->bind_param("i", $template_id);
                    if ($stmt->execute()) {
                        $success_message = "Template deleted successfully!";
                    } else {
                        $error_message = "Error deleting template: " . $stmt->error;
                    }
                }
                break;
                
            case 'add_template_option':
                $template_id = intval($_POST['option_template_id']);
                $name = trim($_POST['option_name']);
                $price_adjustment = floatval($_POST['option_price_adjustment']);
                $sort_order = intval($_POST['option_sort_order']);
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("INSERT INTO modifier_template_options (template_id, name, price_adjustment, sort_order) VALUES (?, ?, ?, ?)");
                    $stmt->bind_param("isdi", $template_id, $name, $price_adjustment, $sort_order);
                    if ($stmt->execute()) {
                        $success_message = "Template option added successfully!";
                    } else {
                        $error_message = "Error adding option: " . $stmt->error;
                    }
                }
                break;
                
            case 'update_template_option':
                $option_id = intval($_POST['option_id']);
                $name = trim($_POST['option_name']);
                $price_adjustment = floatval($_POST['option_price_adjustment']);
                $sort_order = intval($_POST['option_sort_order']);
                $is_active = isset($_POST['option_is_active']) ? 1 : 0;
                
                if (!empty($name)) {
                    $stmt = $conn->prepare("UPDATE modifier_template_options SET name = ?, price_adjustment = ?, sort_order = ?, is_active = ? WHERE id = ?");
                    $stmt->bind_param("sdiii", $name, $price_adjustment, $sort_order, $is_active, $option_id);
                    if ($stmt->execute()) {
                        $success_message = "Template option updated successfully!";
                    } else {
                        $error_message = "Error updating option: " . $stmt->error;
                    }
                }
                break;
                
            case 'delete_template_option':
                $option_id = intval($_POST['option_id']);
                $stmt = $conn->prepare("DELETE FROM modifier_template_options WHERE id = ?");
                $stmt->bind_param("i", $option_id);
                if ($stmt->execute()) {
                    $success_message = "Template option deleted successfully!";
                } else {
                    $error_message = "Error deleting option: " . $stmt->error;
                }
                break;
        }
    }
}

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

// 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");

// Get modifier templates
$templates_result = $conn->query("SELECT * FROM modifier_templates ORDER BY sort_order, name");
$templates = $templates_result->fetch_all(MYSQLI_ASSOC);

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="#library" role="tab" id="library-tab">
                            <i class="feather feather-book me-2"></i>Modifier Library
                        </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>
                    <li class="nav-item" role="presentation">
                        <a class="nav-link" data-bs-toggle="tab" href="#templates" role="tab" id="templates-tab">
                            <i class="feather feather-layers me-2"></i>Modifier Templates
                        </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 foreach ($groups as $group): ?>
                                                    <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 endforeach; ?>
                                                </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>

                    <!-- Modifier Library Tab -->
                    <div class="tab-pane fade" id="library" 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-book me-2"></i>Modifier Library
                                </h5>
                                <div>
                                    <button class="btn btn-success me-2" onclick="showBulkAssignmentModal()">
                                        <i class="feather feather-plus-circle me-2"></i>Assign
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="row mb-3">
                                    <div class="col-md-3">
                                        <label for="library_group_filter" class="form-label">Filter by Group</label>
                                        <select class="form-control" id="library_group_filter">
                                            <option value="">All Groups</option>
                                            <?php foreach ($groups as $group): ?>
                                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['display_name']) ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="col-md-4">
                                        <label for="library_search" class="form-label">Search Modifiers</label>
                                        <input type="text" class="form-control" id="library_search" placeholder="Search by name or short name..." onkeyup="loadLibrary()">
                                    </div>
                                    <div class="col-md-2">
                                        <label for="library_status_filter" class="form-label">Status</label>
                                        <select class="form-control" id="library_status_filter">
                                            <option value="">All Status</option>
                                            <option value="1">Active</option>
                                            <option value="0">Inactive</option>
                                        </select>
                                    </div>
                                    <div class="col-md-3">
                                        <label class="form-label">&nbsp;</label>
                                        <div>
                                            <button class="btn btn-outline-secondary" onclick="clearLibraryFilters()">
                                                <i class="feather feather-x me-1"></i>Clear Filters
                                            </button>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="table-responsive">
                                    <table class="table table-hover" id="libraryTable">
                                        <thead class="table-dark">
                                            <tr>
                                                <th width="30">
                                                    <input type="checkbox" id="select_all_library" onchange="toggleSelectAllLibrary()">
                                                </th>
                                                <th>Modifier Name</th>
                                                <th>Current Groups</th>
                                                <th>Price Adjustment</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                                        <tbody id="library_table">
                                            <!-- Library 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 foreach ($groups as $group): ?>
                                                <option value="<?= $group['id'] ?>"><?= htmlspecialchars($group['display_name']) ?></option>
                                            <?php endforeach; ?>
                                        </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>

                    <!-- Modifier Templates Tab -->
                    <div class="tab-pane fade" id="templates" role="tabpanel">
                        <div class="row">
                            <!-- Left: Template Management -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-layers me-2"></i>Modifier Templates
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="alert alert-info">
                                            <i class="feather feather-info me-2"></i>Templates are universal modifiers that work on ANY item (e.g., Spice Level, Sugar Level)
                                        </div>
                                        
                                        <button class="btn btn-primary mb-3" onclick="showAddTemplateModal()">
                                            <i class="feather feather-plus me-2"></i>Add Template
                                        </button>
                                        
                                        <div class="table-responsive">
                                            <table class="table table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Icon</th>
                                                        <th>Status</th>
                                                        <th>Actions</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($templates as $template): ?>
                                                    <tr>
                                                        <td>
                                                            <strong><?= htmlspecialchars($template['name']) ?></strong>
                                                        </td>
                                                        <td><i data-feather="<?= htmlspecialchars($template['icon']) ?>" class="feather-16"></i></td>
                                                        <td>
                                                            <?php if ($template['is_active']): ?>
                                                                <span class="badge bg-success">Active</span>
                                                            <?php else: ?>
                                                                <span class="badge bg-secondary">Inactive</span>
                                                            <?php endif; ?>
                                                        </td>
                                                        <td>
                                                            <button class="btn btn-sm btn-primary" onclick="editTemplate(<?= htmlspecialchars(json_encode($template)) ?>)">
                                                                <i class="feather feather-edit"></i>
                                                            </button>
                                                            <button class="btn btn-sm btn-info" onclick="viewTemplateOptions(<?= $template['id'] ?>, '<?= htmlspecialchars($template['name']) ?>')">
                                                                <i class="feather feather-list"></i>
                                                            </button>
                                                            <form method="POST" style="display: inline;">
                                                                <input type="hidden" name="action" value="delete_template">
                                                                <input type="hidden" name="template_id" value="<?= $template['id'] ?>">
                                                                <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete this template?')">
                                                                    <i class="feather feather-trash-2"></i>
                                                                </button>
                                                            </form>
                                                        </td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Right: Template Options Management -->
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">
                                            <i class="feather feather-list me-2"></i>Template Options
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="template-options-container">
                                            <div class="text-center text-muted py-5">
                                                <i data-feather="layers" class="feather-48 mb-3"></i>
                                                <p>Select a template from the left to view/manage options</p>
                                            </div>
                                        </div>
                                    </div>
                                </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="alert alert-info">
                        <i class="feather feather-info me-2"></i>
                        <strong>Note:</strong> After creating the modifier, use the <strong>Modifier Library</strong> tab to assign it to groups.
                    </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>Current Groups</label>
                        <div id="modifier_current_groups" class="form-control-plaintext">
                            <span class="text-muted">Groups will be loaded here</span>
                        </div>
                        <small class="text-muted">Use the Modifier Library tab to manage group assignments</small>
                    </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>

<!-- Bulk Assignment Modal -->
<div class="modal fade" id="bulkAssignmentModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Assign Modifiers</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div class="alert alert-info">
                    <i class="feather feather-info me-2"></i>
                    Select modifiers and assign them to multiple groups at once.
                </div>
                
                <div class="row">
                    <div class="col-md-6">
                        <h6>Selected Modifiers</h6>
                        <div id="selected_modifiers_list" class="border p-3" style="max-height: 300px; overflow-y: auto;">
                            <p class="text-muted">No modifiers selected</p>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6>Target Groups</h6>
                        <div id="target_groups_list" class="border p-3" style="max-height: 300px; overflow-y: auto;">
                            <!-- Groups will be loaded here -->
                        </div>
                    </div>
                </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-success" onclick="executeBulkAssignment()">Assign to Selected Groups</button>
            </div>
        </div>
    </div>
</div>

<!-- Add Template Modal -->
<div class="modal fade" id="addTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Add Modifier Template</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_template">
                    
                    <div class="form-group">
                        <label>Template Name</label>
                        <input type="text" class="form-control" name="template_name" required placeholder="e.g., Spice Level">
                        <small class="text-muted">This will be shown to users</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Icon</label>
                        <select class="form-control" name="template_icon" id="add_template_icon" onchange="updateIconPreview('add')">
                            <option value="layers">📋 Layers - General</option>
                            <option value="thermometer">🌡️ Thermometer - Temperature/Spice</option>
                            <option value="droplet">💧 Droplet - Liquid/Sugar Level</option>
                            <option value="maximize">📐 Maximize - Size/Portion</option>
                            <option value="coffee">☕ Coffee - Beverages</option>
                            <option value="zap">⚡ Zap - Spicy/Energy</option>
                            <option value="star">⭐ Star - Premium/Extra</option>
                            <option value="award">🏆 Award - Special</option>
                            <option value="check-circle">✅ Check Circle - Options</option>
                            <option value="plus-circle">➕ Plus Circle - Add-ons</option>
                            <option value="settings">⚙️ Settings - Customization</option>
                            <option value="sliders">🎚️ Sliders - Levels</option>
                            <option value="grid">🔲 Grid - Categories</option>
                            <option value="list">📝 List - Items</option>
                            <option value="tag">🏷️ Tag - Labels</option>
                        </select>
                        <div class="mt-2">
                            <small class="text-muted">Preview: </small>
                            <i data-feather="layers" id="add_icon_preview" class="feather-16"></i>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Sort Order</label>
                        <input type="number" class="form-control" name="template_sort_order" value="0">
                    </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 Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Template Modal -->
<div class="modal fade" id="editTemplateModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Modifier Template</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_template">
                    <input type="hidden" name="template_id" id="edit_template_id">
                    
                    <div class="form-group">
                        <label>Template Name</label>
                        <input type="text" class="form-control" name="template_name" id="edit_template_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Icon</label>
                        <select class="form-control" name="template_icon" id="edit_template_icon" onchange="updateIconPreview('edit')">
                            <option value="layers">📋 Layers - General</option>
                            <option value="thermometer">🌡️ Thermometer - Temperature/Spice</option>
                            <option value="droplet">💧 Droplet - Liquid/Sugar Level</option>
                            <option value="maximize">📐 Maximize - Size/Portion</option>
                            <option value="coffee">☕ Coffee - Beverages</option>
                            <option value="zap">⚡ Zap - Spicy/Energy</option>
                            <option value="star">⭐ Star - Premium/Extra</option>
                            <option value="award">🏆 Award - Special</option>
                            <option value="check-circle">✅ Check Circle - Options</option>
                            <option value="plus-circle">➕ Plus Circle - Add-ons</option>
                            <option value="settings">⚙️ Settings - Customization</option>
                            <option value="sliders">🎚️ Sliders - Levels</option>
                            <option value="grid">🔲 Grid - Categories</option>
                            <option value="list">📝 List - Items</option>
                            <option value="tag">🏷️ Tag - Labels</option>
                        </select>
                        <div class="mt-2">
                            <small class="text-muted">Preview: </small>
                            <i data-feather="layers" id="edit_icon_preview" class="feather-16"></i>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>Sort Order</label>
                        <input type="number" class="form-control" name="template_sort_order" id="edit_template_sort_order">
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="template_is_active" id="edit_template_is_active">
                        <label class="form-check-label" for="edit_template_is_active">Active</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">Update Template</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Add Template Option Modal -->
<div class="modal fade" id="addOptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="addOptionModalTitle">Add Option</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_template_option">
                    <input type="hidden" name="option_template_id" id="option_template_id">
                    
                    <div class="form-group">
                        <label>Option Name</label>
                        <input type="text" class="form-control" name="option_name" required placeholder="e.g., Less Spicy">
                    </div>
                    
                    <div class="form-group">
                        <label>Price Adjustment</label>
                        <input type="number" class="form-control" name="option_price_adjustment" step="0.01" value="0.00">
                        <small class="text-muted">Amount to add/subtract from item price</small>
                    </div>
                    
                    <div class="form-group">
                        <label>Sort Order</label>
                        <input type="number" class="form-control" name="option_sort_order" value="0">
                    </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 Option</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Edit Template Option Modal -->
<div class="modal fade" id="editOptionModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Edit Template Option</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_template_option">
                    <input type="hidden" name="option_id" id="edit_option_id">
                    
                    <div class="form-group">
                        <label>Option Name</label>
                        <input type="text" class="form-control" name="option_name" id="edit_option_name" required>
                    </div>
                    
                    <div class="form-group">
                        <label>Price Adjustment</label>
                        <input type="number" class="form-control" name="option_price_adjustment" id="edit_option_price_adjustment" step="0.01">
                    </div>
                    
                    <div class="form-group">
                        <label>Sort Order</label>
                        <input type="number" class="form-control" name="option_sort_order" id="edit_option_sort_order">
                    </div>
                    
                    <div class="form-check">
                        <input type="checkbox" class="form-check-input" name="option_is_active" id="edit_option_is_active">
                        <label class="form-check-label" for="edit_option_is_active">Active</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">Update Option</button>
                </div>
            </form>
        </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();
    });
    
    document.getElementById('library-tab').addEventListener('shown.bs.tab', function() {
        loadLibrary();
    });
    
    // 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);
    
    // Filter event listeners for library
    document.getElementById('library_group_filter').addEventListener('change', loadLibrary);
    document.getElementById('library_search').addEventListener('input', loadLibrary);
    document.getElementById('library_status_filter').addEventListener('change', loadLibrary);
});

// 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_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;
                
                // Load current groups for this modifier
                loadModifierGroups(id);
                
                new bootstrap.Modal(document.getElementById('editModifierModal')).show();
            } else {
                alert('Error loading modifier: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
}

// Load modifier groups function
function loadModifierGroups(modifierId) {
    fetch(`ajax/get_modifier_groups.php?modifier_id=${modifierId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const groupsContainer = document.getElementById('modifier_current_groups');
                if (data.groups && data.groups.length > 0) {
                    const groupBadges = data.groups.map(group => 
                        `<span class="badge bg-primary me-1">${group.display_name}</span>`
                    ).join('');
                    groupsContainer.innerHTML = groupBadges;
                } else {
                    groupsContainer.innerHTML = '<span class="text-muted">No groups assigned</span>';
                }
            } else {
                document.getElementById('modifier_current_groups').innerHTML = '<span class="text-muted">Error loading groups</span>';
            }
        })
        .catch(error => {
            console.error('Error loading groups:', error);
            document.getElementById('modifier_current_groups').innerHTML = '<span class="text-muted">Error loading groups</span>';
        });
}

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');
    });
}

// ===== MODIFIER LIBRARY FUNCTIONS =====

// Global array to track selected modifiers (persists across searches)
let selectedModifierIds = [];

// Load library function
function loadLibrary() {
    const groupFilter = document.getElementById('library_group_filter').value;
    const searchFilter = document.getElementById('library_search').value;
    const statusFilter = document.getElementById('library_status_filter').value;
    
    // Build query parameters
    const params = new URLSearchParams();
    if (groupFilter) params.append('group_filter', groupFilter);
    if (searchFilter) params.append('search', searchFilter);
    if (statusFilter !== '') params.append('status', statusFilter);
    
    fetch(`ajax/get_modifiers.php?${params.toString()}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayLibrary(data.modifiers);
            } else {
                console.error('Error loading library:', data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });
}


// Display library function
function displayLibrary(modifiers) {
    const tbody = document.getElementById('library_table');
    let html = '';
    
    modifiers.forEach(modifier => {
        const groupBadge = `<span class="badge bg-info me-1">${modifier.group_name}</span>`;
        html += `
            <tr>
                <td>
                    <input type="checkbox" class="library-checkbox" value="${modifier.id}" onchange="handleModifierSelection(this)">
                </td>
                <td>
                    <strong>${modifier.name}</strong>
                    ${modifier.short_name ? `<br><small class="text-muted">${modifier.short_name}</small>` : ''}
                </td>
                <td>${groupBadge}</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_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="editModifierFromLibrary(${modifier.id})">
                        <i class="feather feather-edit"></i>
                    </button>
                    <button class="btn btn-sm btn-success" onclick="assignModifierToGroups(${modifier.id}, '${modifier.name}')">
                        <i class="feather feather-plus"></i>
                    </button>
                </td>
            </tr>
        `;
    });
    
    tbody.innerHTML = html;
}

// Toggle select all library
function toggleSelectAllLibrary() {
    const selectAll = document.getElementById('select_all_library');
    const checkboxes = document.querySelectorAll('.library-checkbox');
    
    if (selectAll.checked) {
        // Select all visible modifiers
        checkboxes.forEach(checkbox => {
            checkbox.checked = true;
            const modifierId = checkbox.value;
            if (!selectedModifierIds.includes(modifierId)) {
                selectedModifierIds.push(modifierId);
            }
        });
    } else {
        // Deselect all visible modifiers
        checkboxes.forEach(checkbox => {
            checkbox.checked = false;
            const modifierId = checkbox.value;
            const index = selectedModifierIds.indexOf(modifierId);
            if (index > -1) {
                selectedModifierIds.splice(index, 1);
            }
        });
    }
    
    console.log('FIX: Select all toggled. Selected modifiers:', selectedModifierIds);
    updateSelectedModifiers();
}

// Update selected modifiers display
function updateSelectedModifiers() {
    const container = document.getElementById('selected_modifiers_list');
    
    console.log('FIX: Selected modifier IDs array:', selectedModifierIds);
    
    if (selectedModifierIds.length === 0) {
        container.innerHTML = '<p class="text-muted">No modifiers selected</p>';
        return;
    }
    
    // Get modifier details from the current visible modifiers
    const allModifiers = [];
    document.querySelectorAll('.library-checkbox').forEach(checkbox => {
        const row = checkbox.closest('tr');
        if (row) {
            const nameElement = row.querySelector('td:nth-child(2) strong');
            const name = nameElement ? nameElement.textContent : 'Unknown';
            allModifiers.push({
                id: checkbox.value,
                name: name
            });
        }
    });
    
    let html = '';
    selectedModifierIds.forEach(modifierId => {
        // Find the modifier name from current visible modifiers or use stored data
        let modifierName = 'Unknown';
        const visibleModifier = allModifiers.find(m => m.id == modifierId);
        if (visibleModifier) {
            modifierName = visibleModifier.name;
        } else {
            // If not visible, try to get from stored data or use ID
            modifierName = `Modifier ${modifierId}`;
        }
        
        console.log(`FIX: Processing selected modifier: ${modifierName} (ID: ${modifierId})`);
        
        html += `<div class="d-flex justify-content-between align-items-center mb-2">
                    <span>${modifierName}</span>
                    <button class="btn btn-sm btn-outline-danger" onclick="deselectModifier(${modifierId})">
                        <i class="feather feather-x"></i>
                    </button>
                 </div>`;
    });
    
    console.log('FIX: Final HTML for selected modifiers:', html);
    container.innerHTML = html;
}

// Handle modifier selection (checkbox change)
function handleModifierSelection(checkbox) {
    const modifierId = checkbox.value;
    
    if (checkbox.checked) {
        // Add to selected array if not already there
        if (!selectedModifierIds.includes(modifierId)) {
            selectedModifierIds.push(modifierId);
            console.log('FIX: Added modifier to selection:', modifierId, 'Total selected:', selectedModifierIds);
        }
    } else {
        // Remove from selected array
        const index = selectedModifierIds.indexOf(modifierId);
        if (index > -1) {
            selectedModifierIds.splice(index, 1);
            console.log('FIX: Removed modifier from selection:', modifierId, 'Total selected:', selectedModifierIds);
        }
    }
    
    updateSelectedModifiers();
}

// Deselect modifier
function deselectModifier(modifierId) {
    // Remove from selected array
    const index = selectedModifierIds.indexOf(modifierId);
    if (index > -1) {
        selectedModifierIds.splice(index, 1);
        console.log('FIX: Deselected modifier:', modifierId, 'Total selected:', selectedModifierIds);
    }
    
    // Uncheck the checkbox if it's visible
    const checkbox = document.querySelector(`.library-checkbox[value="${modifierId}"]`);
    if (checkbox) {
        checkbox.checked = false;
    }
    
    updateSelectedModifiers();
}

// Show bulk assignment modal
function showBulkAssignmentModal() {
    if (selectedModifierIds.length === 0) {
        alert('Please select modifiers first');
        return;
    }
    
    console.log('FIX: Opening assignment modal with selected modifiers:', selectedModifierIds);
    updateSelectedModifiers();
    loadTargetGroups();
    new bootstrap.Modal(document.getElementById('bulkAssignmentModal')).show();
}

// Load target groups
function loadTargetGroups() {
    console.log('FIX: Loading all target groups...');
    
    // Use PHP data directly to get all groups (including empty ones)
    try {
        const groups = <?= json_encode($groups) ?>;
        console.log('FIX: All groups loaded from PHP:', groups);
        displayTargetGroups(groups);
    } catch (e) {
        console.error('FIX: Error loading groups from PHP:', e);
        document.getElementById('target_groups_list').innerHTML = '<p class="text-danger">Error loading groups</p>';
    }
}

// Display target groups
function displayTargetGroups(groups) {
    console.log('FIX: Displaying target groups:', groups);
    const container = document.getElementById('target_groups_list');
    
    if (!groups || groups.length === 0) {
        console.log('FIX: No groups to display');
        container.innerHTML = '<p class="text-muted">No groups available</p>';
        return;
    }
    
    let html = '';
    groups.forEach((group, index) => {
        console.log(`FIX: Processing group ${index}:`, group);
        html += `
            <div class="form-check mb-2">
                <input type="checkbox" class="form-check-input target-group-checkbox" value="${group.id}" id="target_${group.id}">
                <label class="form-check-label" for="target_${group.id}">
                    <strong>${group.display_name}</strong>
                    <br><small class="text-muted">${group.description || ''}</small>
                </label>
            </div>
        `;
    });
    
    console.log('FIX: Final groups HTML:', html);
    container.innerHTML = html;
}

// Execute bulk assignment
function executeBulkAssignment() {
    const targetGroups = Array.from(document.querySelectorAll('.target-group-checkbox:checked')).map(cb => cb.value);
    
    console.log('FIX: Executing assignment with modifiers:', selectedModifierIds, 'to groups:', targetGroups);
    
    if (selectedModifierIds.length === 0) {
        alert('Please select modifiers');
        return;
    }
    
    if (targetGroups.length === 0) {
        alert('Please select target groups');
        return;
    }
    
    fetch('ajax/bulk_assign_modifiers.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
            modifier_ids: selectedModifierIds,
            group_ids: targetGroups
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('Modifiers assigned successfully!');
            bootstrap.Modal.getInstance(document.getElementById('bulkAssignmentModal')).hide();
            // Clear selections after successful assignment
            selectedModifierIds = [];
            loadLibrary(); // Reload library
        } else {
            alert('Error assigning modifiers: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Network error:', error);
        alert('Network error occurred');
    });
}


// Assign modifier to groups (quick action)
function assignModifierToGroups(modifierId, modifierName) {
    // Quick assignment - select this modifier and show bulk assignment modal
    // Clear all selections first
    selectedModifierIds = [];
    document.querySelectorAll('.library-checkbox').forEach(cb => cb.checked = false);
    
    // Select this specific modifier
    selectedModifierIds.push(modifierId);
    const checkbox = document.querySelector(`.library-checkbox[value="${modifierId}"]`);
    if (checkbox) {
        checkbox.checked = true;
    }
    
    console.log('FIX: Quick assignment for modifier:', modifierId, 'Selected:', selectedModifierIds);
    updateSelectedModifiers();
    showBulkAssignmentModal();
}

// Edit modifier from library
function editModifierFromLibrary(modifierId) {
    // Redirect to edit the modifier
    editModifier(modifierId);
}

// Clear library filters
function clearLibraryFilters() {
    document.getElementById('library_group_filter').value = '';
    document.getElementById('library_search').value = '';
    document.getElementById('library_status_filter').value = '';
    loadLibrary();
}

// ===== MODIFIER TEMPLATES FUNCTIONS =====

// Show Add Template Modal
function showAddTemplateModal() {
    new bootstrap.Modal(document.getElementById('addTemplateModal')).show();
}

// Edit Template
function editTemplate(template) {
    document.getElementById('edit_template_id').value = template.id;
    document.getElementById('edit_template_name').value = template.name;
    document.getElementById('edit_template_icon').value = template.icon;
    document.getElementById('edit_template_sort_order').value = template.sort_order;
    document.getElementById('edit_template_is_active').checked = template.is_active == 1;
    
    // Update icon preview
    const previewIcon = document.getElementById('edit_icon_preview');
    previewIcon.setAttribute('data-feather', template.icon);
    feather.replace();
    
    new bootstrap.Modal(document.getElementById('editTemplateModal')).show();
}

// Update icon preview when dropdown changes
function updateIconPreview(mode) {
    const selectId = mode === 'add' ? 'add_template_icon' : 'edit_template_icon';
    const previewId = mode === 'add' ? 'add_icon_preview' : 'edit_icon_preview';
    
    const selectedIcon = document.getElementById(selectId).value;
    const previewElement = document.getElementById(previewId);
    
    previewElement.setAttribute('data-feather', selectedIcon);
    feather.replace();
}

// View Template Options
function viewTemplateOptions(templateId, templateName) {
    fetch(`ajax/get_template_options.php?template_id=${templateId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayTemplateOptions(data.options, templateId, templateName);
            } else {
                alert('Error loading options: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('Network error occurred');
        });
}

// Display Template Options
function displayTemplateOptions(options, templateId, templateName) {
    const container = document.getElementById('template-options-container');
    
    let html = `
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6>${templateName} Options</h6>
            <button class="btn btn-sm btn-primary" onclick="showAddOptionModal(${templateId}, '${templateName}')">
                <i class="feather feather-plus me-1"></i>Add Option
            </button>
        </div>
        <div class="table-responsive">
            <table class="table table-hover">
                                        <thead>
                                            <tr>
                                                <th>Name</th>
                                                <th>Price</th>
                                                <th>Status</th>
                                                <th>Actions</th>
                                            </tr>
                                        </thead>
                <tbody>
    `;
    
    if (options.length === 0) {
        html += `<tr><td colspan="4" class="text-center text-muted">No options added yet</td></tr>`;
    } else {
        options.forEach(option => {
            const priceClass = option.price_adjustment > 0 ? 'text-success' : (option.price_adjustment < 0 ? 'text-danger' : '');
            const priceText = option.price_adjustment > 0 ? `+Rs ${option.price_adjustment}` : 
                             option.price_adjustment < 0 ? `-Rs ${Math.abs(option.price_adjustment)}` : 'Rs 0.00';
            
            html += `
                <tr>
                    <td><strong>${option.name}</strong></td>
                    <td class="${priceClass}">${priceText}</td>
                    <td>
                        ${option.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='editTemplateOption(${JSON.stringify(option)})'>
                            <i class="feather feather-edit"></i>
                        </button>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="delete_template_option">
                            <input type="hidden" name="option_id" value="${option.id}">
                            <button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Delete this option?')">
                                <i class="feather feather-trash-2"></i>
                            </button>
                        </form>
                    </td>
                </tr>
            `;
        });
    }
    
    html += `</tbody></table></div>`;
    container.innerHTML = html;
    feather.replace();
}

// Show Add Option Modal
function showAddOptionModal(templateId, templateName) {
    document.getElementById('option_template_id').value = templateId;
    document.getElementById('addOptionModalTitle').textContent = `Add Option to: ${templateName}`;
    new bootstrap.Modal(document.getElementById('addOptionModal')).show();
}

// Edit Template Option
function editTemplateOption(option) {
    document.getElementById('edit_option_id').value = option.id;
    document.getElementById('edit_option_name').value = option.name;
    document.getElementById('edit_option_price_adjustment').value = option.price_adjustment;
    document.getElementById('edit_option_sort_order').value = option.sort_order;
    document.getElementById('edit_option_is_active').checked = option.is_active == 1;
    
    new bootstrap.Modal(document.getElementById('editOptionModal')).show();
}

// Load templates tab when shown
document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('templates-tab')?.addEventListener('shown.bs.tab', function() {
        feather.replace();
    });
});
</script>

