<?php
$pageTitle = 'Variations & Add-ons';
require_once __DIR__ . '/includes/header.php';

$menuItems = $db->query("SELECT id, name FROM menu_items WHERE restaurant_id = ? AND is_available = 1 ORDER BY name ASC", [$restaurantId])->fetchAll();

$variations = $db->query("
    SELECT iv.*, mi.name as item_name
    FROM item_variations iv
    LEFT JOIN menu_items mi ON iv.menu_item_id = mi.id
    WHERE iv.restaurant_id = ?
    ORDER BY iv.sort_order ASC, iv.name ASC
", [$restaurantId])->fetchAll();

$addonGroups = $db->query("
    SELECT ag.*, COUNT(a.id) as addon_count
    FROM addon_groups ag
    LEFT JOIN addons a ON a.addon_group_id = ag.id AND a.status = 1
    WHERE ag.restaurant_id = ?
    GROUP BY ag.id
    ORDER BY ag.sort_order ASC, ag.name ASC
", [$restaurantId])->fetchAll();
?>

<div class="row">
    <div class="col-lg-6 mb-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="mb-0"><i class="fas fa-sliders-h me-2"></i>Variations</h6>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#variationModal" onclick="resetVariationForm()">
                <i class="fas fa-plus me-1"></i>Add Variation
            </button>
        </div>
        <div class="table-card">
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-hover mb-0">
                        <thead class="table-light">
                            <tr><th>Item</th><th>Name</th><th>Price</th><th>Status</th><th>Sort</th><th>Actions</th></tr>
                        </thead>
                        <tbody>
                            <?php if (empty($variations)): ?>
                                <tr><td colspan="6" class="text-center text-muted py-3">No variations</td></tr>
                            <?php else: ?>
                                <?php foreach ($variations as $var): ?>
                                <tr>
                                    <td><small><?php echo sanitize($var['item_name'] ?? 'N/A'); ?></small></td>
                                    <td><?php echo sanitize($var['name']); ?></td>
                                    <td><?php echo formatCurrency($var['price'], $currency); ?></td>
                                    <td><?php echo $var['status'] ? '<span class="badge bg-success">Active</span>' : '<span class="badge bg-secondary">Inactive</span>'; ?></td>
                                    <td><?php echo $var['sort_order']; ?></td>
                                    <td>
                                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editVariation(<?php echo $var['id']; ?>)"><i class="fas fa-edit"></i></button>
                                        <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/variation_save.php" data-name="<?php echo sanitize($var['name']); ?>" data-id="<?php echo $var['id']; ?>"><i class="fas fa-trash"></i></button>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="col-lg-6 mb-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h6 class="mb-0"><i class="fas fa-plus-square me-2"></i>Add-on Groups</h6>
            <button class="btn btn-primary btn-sm" data-bs-toggle="modal" data-bs-target="#addonGroupModal" onclick="resetAddonGroupForm()">
                <i class="fas fa-plus me-1"></i>Add Group
            </button>
        </div>
        <?php if (empty($addonGroups)): ?>
            <div class="table-card">
                <div class="card-body text-center text-muted py-4">No addon groups</div>
            </div>
        <?php else: ?>
            <?php foreach ($addonGroups as $ag): ?>
            <div class="table-card mb-3" id="agCard_<?php echo $ag['id']; ?>">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <div>
                        <strong><?php echo sanitize($ag['name']); ?></strong>
                        <small class="text-muted ms-2"><?php echo $ag['addon_count']; ?> addons</small>
                        <?php if ($ag['is_required']): ?><span class="badge bg-danger ms-1">Required</span><?php endif; ?>
                        <small class="text-muted ms-1">Min: <?php echo $ag['min_select']; ?> Max: <?php echo $ag['max_select']; ?></small>
                    </div>
                    <div>
                        <button class="btn btn-sm btn-outline-primary me-1" onclick="editAddonGroup(<?php echo $ag['id']; ?>)"><i class="fas fa-edit"></i></button>
                        <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/variation_save.php" data-name="<?php echo sanitize($ag['name']); ?>" data-id="<?php echo $ag['id']; ?>" data-type="addon_group"><i class="fas fa-trash"></i></button>
                    </div>
                </div>
                <div class="card-body p-2">
                    <?php
                    $addons = $db->query("SELECT * FROM addons WHERE addon_group_id = ? AND restaurant_id = ? ORDER BY sort_order ASC", [$ag['id'], $restaurantId])->fetchAll();
                    ?>
                    <?php if (empty($addons)): ?>
                        <div class="text-center text-muted small py-2">No addons</div>
                    <?php else: ?>
                    <table class="table table-sm mb-0">
                        <thead><tr><th>Name</th><th>Price</th><th>Status</th><th></th></tr></thead>
                        <tbody>
                        <?php foreach ($addons as $ad): ?>
                        <tr>
                            <td><?php echo sanitize($ad['name']); ?></td>
                            <td><?php echo formatCurrency($ad['price'], $currency); ?></td>
                            <td><?php echo $ad['status'] ? '<i class="fas fa-check text-success"></i>' : '<i class="fas fa-times text-danger"></i>'; ?></td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editAddon(<?php echo $ad['id']; ?>)"><i class="fas fa-edit"></i></button>
                                <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/variation_save.php" data-name="<?php echo sanitize($ad['name']); ?>" data-id="<?php echo $ad['id']; ?>" data-type="addon"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        </tbody>
                    </table>
                    <?php endif; ?>
                    <button class="btn btn-sm btn-outline-success m-2" onclick="openAddAddon(<?php echo $ag['id']; ?>)"><i class="fas fa-plus me-1"></i>Add Addon</button>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

<div class="modal fade" id="variationModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="variationForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="varAction" value="add_variation">
                <input type="hidden" name="variation_id" id="varId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="varModalTitle">Add Variation</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Menu Item <span class="text-danger">*</span></label>
                        <select class="form-select" name="menu_item_id" id="varItemId" required>
                            <option value="">Select Item</option>
                            <?php foreach ($menuItems as $mi): ?>
                            <option value="<?php echo $mi['id']; ?>"><?php echo sanitize($mi['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Variation Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="varName" required placeholder="e.g., Large, Extra Spicy">
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Additional Price</label>
                            <input type="number" step="0.01" class="form-control" name="price" id="varPrice" value="0">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" id="varSortOrder" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="varStatus">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </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"><i class="fas fa-save me-1"></i>Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="addonGroupModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="addonGroupForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="agAction" value="add_addon_group">
                <input type="hidden" name="addon_group_id" id="agId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="agModalTitle">Add Add-on Group</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Group Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="agName" required placeholder="e.g., Toppings, Drinks">
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Min Select</label>
                            <input type="number" class="form-control" name="min_select" id="agMinSelect" value="0">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Max Select</label>
                            <input type="number" class="form-control" name="max_select" id="agMaxSelect" value="10">
                        </div>
                        <div class="col-md-4 mb-3">
                            <label class="form-label">Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" id="agSortOrder" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check form-switch">
                            <input class="form-check-input" type="checkbox" name="is_required" id="agRequired" value="1">
                            <label class="form-check-label">Required Group</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="agStatus">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </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"><i class="fas fa-save me-1"></i>Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<div class="modal fade" id="addonModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="addonForm">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="adAction" value="add_addon">
                <input type="hidden" name="addon_id" id="adId" value="">
                <input type="hidden" name="addon_group_id" id="adGroupId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="adModalTitle">Add Addon</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Name <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" id="adName" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Price</label>
                            <input type="number" step="0.01" class="form-control" name="price" id="adPrice" value="0">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" id="adSortOrder" value="0">
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Status</label>
                        <select class="form-select" name="status" id="adStatus">
                            <option value="1">Active</option>
                            <option value="0">Inactive</option>
                        </select>
                    </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"><i class="fas fa-save me-1"></i>Save</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetVariationForm() {
    document.getElementById('varAction').value = 'add_variation';
    document.getElementById('varId').value = '';
    document.getElementById('varItemId').value = '';
    document.getElementById('varName').value = '';
    document.getElementById('varPrice').value = '0';
    document.getElementById('varSortOrder').value = '0';
    document.getElementById('varStatus').value = '1';
    document.getElementById('varModalTitle').textContent = 'Add Variation';
}

function editVariation(id) {
    fetch(BASE_URL + '/restaurant-admin/variation_save.php?action=get_variation&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var v = data.variation;
            document.getElementById('varAction').value = 'edit_variation';
            document.getElementById('varId').value = v.id;
            document.getElementById('varItemId').value = v.menu_item_id;
            document.getElementById('varName').value = v.name;
            document.getElementById('varPrice').value = v.price;
            document.getElementById('varSortOrder').value = v.sort_order;
            document.getElementById('varStatus').value = v.status;
            document.getElementById('varModalTitle').textContent = 'Edit Variation';
            new bootstrap.Modal(document.getElementById('variationModal')).show();
        }
    });
}

function resetAddonGroupForm() {
    document.getElementById('agAction').value = 'add_addon_group';
    document.getElementById('agId').value = '';
    document.getElementById('agName').value = '';
    document.getElementById('agMinSelect').value = '0';
    document.getElementById('agMaxSelect').value = '10';
    document.getElementById('agSortOrder').value = '0';
    document.getElementById('agRequired').checked = false;
    document.getElementById('agStatus').value = '1';
    document.getElementById('agModalTitle').textContent = 'Add Add-on Group';
}

function editAddonGroup(id) {
    fetch(BASE_URL + '/restaurant-admin/variation_save.php?action=get_addon_group&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var g = data.group;
            document.getElementById('agAction').value = 'edit_addon_group';
            document.getElementById('agId').value = g.id;
            document.getElementById('agName').value = g.name;
            document.getElementById('agMinSelect').value = g.min_select;
            document.getElementById('agMaxSelect').value = g.max_select;
            document.getElementById('agSortOrder').value = g.sort_order;
            document.getElementById('agRequired').checked = g.is_required == 1;
            document.getElementById('agStatus').value = g.status;
            document.getElementById('agModalTitle').textContent = 'Edit Add-on Group';
            new bootstrap.Modal(document.getElementById('addonGroupModal')).show();
        }
    });
}

function openAddAddon(groupId) {
    document.getElementById('adAction').value = 'add_addon';
    document.getElementById('adId').value = '';
    document.getElementById('adGroupId').value = groupId;
    document.getElementById('adName').value = '';
    document.getElementById('adPrice').value = '0';
    document.getElementById('adSortOrder').value = '0';
    document.getElementById('adStatus').value = '1';
    document.getElementById('adModalTitle').textContent = 'Add Addon';
    new bootstrap.Modal(document.getElementById('addonModal')).show();
}

function editAddon(id) {
    fetch(BASE_URL + '/restaurant-admin/variation_save.php?action=get_addon&id=' + id, {headers:{'X-Requested-With':'XMLHttpRequest'}})
    .then(function(r){return r.json();})
    .then(function(data){
        if(data.success){
            var a = data.addon;
            document.getElementById('adAction').value = 'edit_addon';
            document.getElementById('adId').value = a.id;
            document.getElementById('adGroupId').value = a.addon_group_id;
            document.getElementById('adName').value = a.name;
            document.getElementById('adPrice').value = a.price;
            document.getElementById('adSortOrder').value = a.sort_order;
            document.getElementById('adStatus').value = a.status;
            document.getElementById('adModalTitle').textContent = 'Edit Addon';
            new bootstrap.Modal(document.getElementById('addonModal')).show();
        }
    });
}

function handleFormSubmit(formId, modalId) {
    document.getElementById(formId).addEventListener('submit', function(e) {
        e.preventDefault();
        var form = this;
        var formData = new FormData(form);
        formData.append('csrf_token', CSRF_TOKEN);
        fetch(BASE_URL + '/restaurant-admin/variation_save.php', {
            method: 'POST', body: formData, headers: {'X-Requested-With': 'XMLHttpRequest'}
        })
        .then(function(r){return r.json();})
        .then(function(data){
            if(data.success){ showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
            else { showAlert('danger', data.message); }
        });
    });
}

handleFormSubmit('variationForm', 'variationModal');
handleFormSubmit('addonGroupForm', 'addonGroupModal');
handleFormSubmit('addonForm', 'addonModal');

document.querySelectorAll('.btn-ajax-delete[data-type]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        var name = this.dataset.name || 'this item';
        var type = this.dataset.type || 'variation';
        if (confirm('Are you sure you want to delete "' + name + '"?')) {
            var actionType = type === 'addon_group' ? 'delete_addon_group' : (type === 'addon' ? 'delete_addon' : 'delete_variation');
            ajaxPost(BASE_URL + '/restaurant-admin/variation_save.php', 'action=' + actionType + '&id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
                if (data.success) { showAlert('success', data.message); setTimeout(function(){location.reload();},1000); }
                else { showAlert('danger', data.message); }
            });
        }
    });
});
</script>

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