<script>
/**
 * Example Module - Items JavaScript
 */

// Set AJAX module path
SLM.module = './?a=example.items';

// DataTable instance
let itemsTable;

// Modal instance
const itemModal = new bootstrap.Modal(document.getElementById('itemModal'));
const viewItemModal = new bootstrap.Modal(document.getElementById('viewItemModal'));

/**
 * Initialize DataTable
 */
function initDataTable() {
    itemsTable = $('#itemsTable').DataTable({
        processing: true,
        serverSide: true,
        ajax: {
            url: SLM.module,
            type: 'POST',
            data: function(d) {
                d.acc = 'getItems';
                d.filterStatus = $('#filterStatus').val();
                d.filterCategory = $('#filterCategory').val();
            }
        },
        columns: [
            {
                data: 'name',
                render: function(data, type, row) {
                    return `<strong>${escapeHtml(data)}</strong>`;
                }
            },
            {
                data: 'description',
                render: function(data) {
                    if (!data) return '<span class="text-muted">-</span>';
                    const truncated = data.length > 50 ? data.substring(0, 50) + '...' : data;
                    return escapeHtml(truncated);
                }
            },
            {
                data: 'category',
                render: function(data) {
                    const badges = {
                        'general': 'bg-secondary',
                        'special': 'bg-info',
                        'premium': 'bg-warning'
                    };
                    return `<span class="badge ${badges[data] || 'bg-secondary'}">${escapeHtml(data)}</span>`;
                }
            },
            {
                data: 'status',
                render: function(data) {
                    if (data === 'active') {
                        return '<span class="badge bg-success">Active</span>';
                    }
                    return '<span class="badge bg-danger">Inactive</span>';
                }
            },
            {
                data: 'slm.timestamp',
                render: function(data) {
                    if (!data) return '-';
                    return moment(data).format('YYYY-MM-DD HH:mm');
                }
            },
            {
                data: null,
                orderable: false,
                render: function(data, type, row) {
                    return `
                        <div class="btn-group btn-group-sm">
                            <button class="btn btn-outline-primary" onclick="viewItem('${row.id}')" title="View">
                                <i data-feather="eye" style="width:14px;height:14px;"></i>
                            </button>
                            <button class="btn btn-outline-secondary" onclick="editItem('${row.id}')" title="Edit">
                                <i data-feather="edit" style="width:14px;height:14px;"></i>
                            </button>
                            <button class="btn btn-outline-danger" onclick="deleteItem('${row.id}')" title="Delete">
                                <i data-feather="trash-2" style="width:14px;height:14px;"></i>
                            </button>
                        </div>
                    `;
                }
            }
        ],
        order: [[4, 'desc']],
        pageLength: 10,
        language: {
            processing: 'Loading...',
            emptyTable: 'No items found',
            zeroRecords: 'No matching items found'
        },
        drawCallback: function() {
            feather.replace();
        }
    });
}

/**
 * Apply filters
 */
function applyFilters() {
    itemsTable.ajax.reload();
}

/**
 * Clear filters
 */
function clearFilters() {
    $('#filterSearch').val('');
    $('#filterStatus').val('');
    $('#filterCategory').val('');
    itemsTable.search('').ajax.reload();
}

/**
 * Open modal for creating new item
 */
function openCreateModal() {
    document.getElementById('itemModalTitle').textContent = 'New Item';
    document.getElementById('itemForm').reset();
    document.getElementById('itemId').value = '';
}

/**
 * View item details
 */
async function viewItem(id) {
    try {
        SLM.loading();

        const result = await SLM.ajax('getItem', { id: id });
        const item = result.item;

        const tags = item.tags && item.tags.length ? item.tags.join(', ') : '-';

        document.getElementById('viewItemContent').innerHTML = `
            <dl class="row mb-0">
                <dt class="col-sm-4">Name</dt>
                <dd class="col-sm-8">${escapeHtml(item.name)}</dd>

                <dt class="col-sm-4">Category</dt>
                <dd class="col-sm-8"><span class="badge bg-secondary">${escapeHtml(item.category)}</span></dd>

                <dt class="col-sm-4">Description</dt>
                <dd class="col-sm-8">${escapeHtml(item.description || '-')}</dd>

                <dt class="col-sm-4">Price</dt>
                <dd class="col-sm-8">$${parseFloat(item.price || 0).toFixed(2)}</dd>

                <dt class="col-sm-4">Status</dt>
                <dd class="col-sm-8">
                    ${item.status === 'active'
                        ? '<span class="badge bg-success">Active</span>'
                        : '<span class="badge bg-danger">Inactive</span>'}
                </dd>

                <dt class="col-sm-4">Tags</dt>
                <dd class="col-sm-8">${escapeHtml(tags)}</dd>

                <dt class="col-sm-4">Created</dt>
                <dd class="col-sm-8">${moment(item.slm?.timestamp).format('YYYY-MM-DD HH:mm:ss')}</dd>
            </dl>
        `;

        SLM.closeLoading();
        viewItemModal.show();

    } catch (error) {
        SLM.error(error.message);
    }
}

/**
 * Edit item
 */
async function editItem(id) {
    try {
        SLM.loading();

        const result = await SLM.ajax('getItem', { id: id });
        const item = result.item;

        // Populate form
        document.getElementById('itemModalTitle').textContent = 'Edit Item';
        document.getElementById('itemId').value = item.id;
        document.getElementById('itemName').value = item.name;
        document.getElementById('itemCategory').value = item.category;
        document.getElementById('itemDescription').value = item.description || '';
        document.getElementById('itemPrice').value = item.price || '';
        document.getElementById('itemStatus').value = item.status;
        document.getElementById('itemTags').value = item.tags ? item.tags.join(', ') : '';

        SLM.closeLoading();
        itemModal.show();

    } catch (error) {
        SLM.error(error.message);
    }
}

/**
 * Delete item
 */
async function deleteItem(id) {
    const result = await SLM.confirm('Are you sure you want to delete this item?');

    if (!result.isConfirmed) return;

    try {
        SLM.loading();

        const response = await SLM.ajax('deleteItem', { id: id });

        SLM.success(response.message);

        if (response.reloadTable) {
            itemsTable.ajax.reload();
        }

    } catch (error) {
        SLM.error(error.message);
    }
}

/**
 * Handle form submission
 */
document.getElementById('itemForm').addEventListener('submit', async function(e) {
    e.preventDefault();

    const btn = document.getElementById('itemSubmitBtn');
    const spinner = btn.querySelector('.spinner-border');
    const id = document.getElementById('itemId').value;

    btn.disabled = true;
    spinner.classList.remove('d-none');

    try {
        const formData = new FormData(this);
        const data = {};
        formData.forEach((value, key) => data[key] = value);

        const action = id ? 'updateItem' : 'createItem';
        const response = await SLM.ajax(action, data);

        SLM.success(response.message);

        if (response.closeModal) {
            itemModal.hide();
        }

        if (response.reloadTable) {
            itemsTable.ajax.reload();
        }

    } catch (error) {
        SLM.error(error.message);
    } finally {
        btn.disabled = false;
        spinner.classList.add('d-none');
    }
});

/**
 * Filter change handlers
 */
$('#filterSearch').on('keyup', function() {
    itemsTable.search(this.value).draw();
});

$('#filterStatus, #filterCategory').on('change', applyFilters);

/**
 * Escape HTML to prevent XSS
 */
function escapeHtml(text) {
    if (!text) return '';
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', function() {
    initDataTable();
});
</script>
