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

$filterCategory = $_GET['category'] ?? '';
$filterStatus = $_GET['status'] ?? '';
$filterFeatured = $_GET['featured'] ?? '';
$filterSearch = $_GET['search'] ?? '';

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

$where = "mi.restaurant_id = ?";
$params = [$restaurantId];

if ($filterCategory) {
    $where .= " AND mi.category_id = ?";
    $params[] = (int)$filterCategory;
}
if ($filterStatus !== '') {
    $where .= " AND mi.is_available = ?";
    $params[] = (int)$filterStatus;
}
if ($filterFeatured !== '') {
    $where .= " AND mi.is_featured = ?";
    $params[] = (int)$filterFeatured;
}
if ($filterSearch) {
    $where .= " AND (mi.name LIKE ? OR mi.short_description LIKE ?)";
    $params[] = '%' . $filterSearch . '%';
    $params[] = '%' . $filterSearch . '%';
}

$menuItems = $db->query("
    SELECT mi.*, c.name as category_name
    FROM menu_items mi
    LEFT JOIN categories c ON mi.category_id = c.id
    WHERE {$where}
    ORDER BY mi.sort_order ASC, mi.name ASC
", $params)->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Menu Items</h6>
        <small class="text-muted">Manage your menu items</small>
    </div>
    <a href="<?php echo $baseUrl; ?>/restaurant-admin/item_form.php" class="btn btn-primary">
        <i class="fas fa-plus me-1"></i>Add Item
    </a>
</div>

<div class="table-card mb-3">
    <div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-2">
                <label class="form-label small">Category</label>
                <select class="form-select form-select-sm" name="category">
                    <option value="">All Categories</option>
                    <?php foreach ($categories as $cat): ?>
                    <option value="<?php echo $cat['id']; ?>" <?php echo $filterCategory == $cat['id'] ? 'selected' : ''; ?>><?php echo sanitize($cat['name']); ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small">Status</label>
                <select class="form-select form-select-sm" name="status">
                    <option value="">All</option>
                    <option value="1" <?php echo $filterStatus === '1' ? 'selected' : ''; ?>>Available</option>
                    <option value="0" <?php echo $filterStatus === '0' ? 'selected' : ''; ?>>Unavailable</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label small">Featured</label>
                <select class="form-select form-select-sm" name="featured">
                    <option value="">All</option>
                    <option value="1" <?php echo $filterFeatured === '1' ? 'selected' : ''; ?>>Featured</option>
                    <option value="0" <?php echo $filterFeatured === '0' ? 'selected' : ''; ?>>Not Featured</option>
                </select>
            </div>
            <div class="col-md-3">
                <label class="form-label small">Search</label>
                <input type="text" class="form-control form-control-sm" name="search" value="<?php echo sanitize($filterSearch); ?>" placeholder="Search items...">
            </div>
            <div class="col-md-3">
                <button type="submit" class="btn btn-sm btn-primary me-1"><i class="fas fa-filter me-1"></i>Filter</button>
                <a href="<?php echo $baseUrl; ?>/restaurant-admin/items.php" class="btn btn-sm btn-outline-secondary">Clear</a>
            </div>
        </form>
    </div>
</div>

<div class="table-card">
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover datatable mb-0">
                <thead class="table-light">
                    <tr>
                        <th>Image</th>
                        <th>Name</th>
                        <th>Category</th>
                        <th>Price</th>
                        <th>Offer</th>
                        <th>Status</th>
                        <th>Featured</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($menuItems as $item): ?>
                        <tr>
                            <td>
                                <?php if (!empty($item['main_image'])): ?>
                                    <img src="<?php echo $baseUrl . '/' . sanitize($item['main_image']); ?>" style="width:45px;height:45px;object-fit:cover;border-radius:8px;">
                                <?php else: ?>
                                    <div class="bg-light d-flex align-items-center justify-content-center" style="width:45px;height:45px;border-radius:8px;"><i class="fas fa-image text-muted"></i></div>
                                <?php endif; ?>
                            </td>
                            <td>
                                <strong><?php echo sanitize($item['name']); ?></strong>
                                <?php if ($item['is_new']): ?><span class="badge bg-success ms-1" style="font-size:10px;">New</span><?php endif; ?>
                                <?php if ($item['is_bestseller']): ?><span class="badge bg-warning ms-1" style="font-size:10px;">Best</span><?php endif; ?>
                                <?php if ($item['is_chefs_choice']): ?><span class="badge bg-info ms-1" style="font-size:10px;">Chef</span><?php endif; ?>
                            </td>
                            <td><?php echo sanitize($item['category_name'] ?? 'N/A'); ?></td>
                            <td>
                                <strong><?php echo formatCurrency($item['regular_price'], $currency); ?></strong>
                            </td>
                            <td>
                                <?php if ($item['offer_price'] && $item['offer_price'] > 0): ?>
                                    <span class="text-danger fw-bold"><?php echo formatCurrency($item['offer_price'], $currency); ?></span>
                                <?php else: ?>
                                    <span class="text-muted">-</span>
                                <?php endif; ?>
                            </td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-item-status" type="checkbox" data-id="<?php echo $item['id']; ?>" <?php echo $item['is_available'] ? 'checked' : ''; ?>>
                                </div>
                            </td>
                            <td><?php echo $item['is_featured'] ? '<i class="fas fa-star text-warning"></i>' : '-'; ?></td>
                            <td>
                                <a href="<?php echo $baseUrl; ?>/restaurant-admin/item_form.php?id=<?php echo $item['id']; ?>" class="btn btn-sm btn-outline-primary me-1" title="Edit"><i class="fas fa-edit"></i></a>
                                <button class="btn-ajax-delete btn btn-sm btn-outline-danger" data-url="<?php echo $baseUrl; ?>/restaurant-admin/item_save.php" data-name="<?php echo sanitize($item['name']); ?>" data-id="<?php echo $item['id']; ?>" title="Delete"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
document.querySelectorAll('.toggle-item-status').forEach(function(toggle) {
    toggle.addEventListener('change', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        ajaxPost(BASE_URL + '/restaurant-admin/item_save.php', 'action=toggle_status&id=' + id + '&csrf_token=' + encodeURIComponent(CSRF_TOKEN), function(data) {
            if (data.success) {
                showAlert('success', data.message);
            } else {
                showAlert('danger', data.message);
            }
        });
    });
});

document.querySelectorAll('.btn-ajax-delete[data-id]').forEach(function(btn) {
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        var name = this.dataset.name || 'this item';
        if (confirm('Are you sure you want to delete "' + name + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/item_save.php', 'action=delete&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'; ?>
