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

$categories = $db->query("
    SELECT c.*, COUNT(mi.id) as items_count
    FROM categories c
    LEFT JOIN menu_items mi ON mi.category_id = c.id AND mi.is_available = 1
    WHERE c.restaurant_id = ?
    GROUP BY c.id
    ORDER BY c.sort_order ASC, c.name ASC
", [$restaurantId])->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <div>
        <h6 class="mb-0">Menu Categories</h6>
        <small class="text-muted">Manage your menu categories</small>
    </div>
    <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#categoryModal" onclick="resetCategoryForm()">
        <i class="fas fa-plus me-1"></i>Add Category
    </button>
</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>Status</th>
                        <th>Featured</th>
                        <th>Sort</th>
                        <th>Items</th>
                        <th>Availability</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($categories as $cat): ?>
                        <tr data-id="<?php echo $cat['id']; ?>">
                            <td>
                                <?php if (!empty($cat['image'])): ?>
                                    <img src="<?php echo $baseUrl . '/' . sanitize($cat['image']); ?>" style="width:50px;height:50px;object-fit:cover;border-radius:8px;">
                                <?php else: ?>
                                    <div class="bg-light d-flex align-items-center justify-content-center" style="width:50px;height:50px;border-radius:8px;"><i class="fas fa-image text-muted"></i></div>
                                <?php endif; ?>
                            </td>
                            <td><strong><?php echo sanitize($cat['name']); ?></strong><br><small class="text-muted"><?php echo sanitize($cat['description'] ? substr($cat['description'], 0, 50) : ''); ?></small></td>
                            <td>
                                <div class="form-check form-switch">
                                    <input class="form-check-input toggle-status" type="checkbox" data-url="<?php echo $baseUrl; ?>/restaurant-admin/category_save.php" data-id="<?php echo $cat['id']; ?>" <?php echo $cat['status'] ? 'checked' : ''; ?>>
                                </div>
                            </td>
                            <td><?php echo $cat['is_featured'] ? '<i class="fas fa-star text-warning"></i>' : '<i class="far fa-star text-muted"></i>'; ?></td>
                            <td><?php echo $cat['sort_order']; ?></td>
                            <td><span class="badge bg-info"><?php echo $cat['items_count']; ?></span></td>
                            <td>
                                <?php
                                $days = $cat['available_days'] ?? '';
                                if ($days) {
                                    echo '<small>' . sanitize($days) . '</small>';
                                } else {
                                    echo '<small class="text-muted">All days</small>';
                                }
                                ?>
                            </td>
                            <td>
                                <button class="btn btn-sm btn-outline-primary me-1" onclick="editCategory(<?php echo $cat['id']; ?>)" title="Edit"><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/category_save.php" data-name="<?php echo sanitize($cat['name']); ?>" data-id="<?php echo $cat['id']; ?>" title="Delete"><i class="fas fa-trash"></i></button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<div class="modal fade" id="categoryModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="categoryForm" enctype="multipart/form-data">
                <?php echo $csrf->field(); ?>
                <input type="hidden" name="action" id="catAction" value="add">
                <input type="hidden" name="category_id" id="catId" value="">
                <div class="modal-header">
                    <h5 class="modal-title" id="catModalTitle">Add Category</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="catName" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Description</label>
                        <textarea class="form-control" name="description" id="catDescription" rows="2"></textarea>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Image</label>
                        <input type="file" class="form-control" name="image" accept="image/*" data-preview="#catImagePreview">
                        <img src="" id="catImagePreview" class="img-preview mt-2" style="display:none;">
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Sort Order</label>
                            <input type="number" class="form-control" name="sort_order" id="catSortOrder" value="0">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Status</label>
                            <select class="form-select" name="status" id="catStatus">
                                <option value="1">Active</option>
                                <option value="0">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="mb-3">
                        <div class="form-check">
                            <input class="form-check-input" type="checkbox" name="is_featured" id="catFeatured" value="1">
                            <label class="form-check-label">Featured Category</label>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Available Days</label>
                        <div class="d-flex flex-wrap gap-2">
                            <?php foreach (['mon'=>'Mon','tue'=>'Tue','wed'=>'Wed','thu'=>'Thu','fri'=>'Fri','sat'=>'Sat','sun'=>'Sun'] as $dk => $dv): ?>
                            <div class="form-check">
                                <input class="form-check-input" type="checkbox" name="available_days[]" value="<?php echo $dk; ?>" id="day_<?php echo $dk; ?>">
                                <label class="form-check-label" for="day_<?php echo $dk; ?>"><?php echo $dv; ?></label>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <small class="text-muted">Leave unchecked for all days</small>
                    </div>
                    <div class="row">
                        <div class="col-md-6 mb-3">
                            <label class="form-label">Start Time</label>
                            <input type="time" class="form-control" name="start_time" id="catStartTime">
                        </div>
                        <div class="col-md-6 mb-3">
                            <label class="form-label">End Time</label>
                            <input type="time" class="form-control" name="end_time" id="catEndTime">
                        </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"><i class="fas fa-save me-1"></i>Save Category</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function resetCategoryForm() {
    document.getElementById('catAction').value = 'add';
    document.getElementById('catId').value = '';
    document.getElementById('catName').value = '';
    document.getElementById('catDescription').value = '';
    document.getElementById('catSortOrder').value = '0';
    document.getElementById('catStatus').value = '1';
    document.getElementById('catFeatured').checked = false;
    document.getElementById('catStartTime').value = '';
    document.getElementById('catEndTime').value = '';
    document.getElementById('catImagePreview').style.display = 'none';
    document.getElementById('catModalTitle').textContent = 'Add Category';
    document.querySelectorAll('input[name="available_days[]"]').forEach(function(cb) { cb.checked = false; });
}

function editCategory(id) {
    fetch(BASE_URL + '/restaurant-admin/category_save.php?action=get&id=' + id, {
        headers: {'X-Requested-With': 'XMLHttpRequest'}
    })
    .then(function(r) { return r.json(); })
    .then(function(data) {
        if (data.success) {
            var c = data.category;
            document.getElementById('catAction').value = 'edit';
            document.getElementById('catId').value = c.id;
            document.getElementById('catName').value = c.name;
            document.getElementById('catDescription').value = c.description || '';
            document.getElementById('catSortOrder').value = c.sort_order || 0;
            document.getElementById('catStatus').value = c.status;
            document.getElementById('catFeatured').checked = c.is_featured == 1;
            document.getElementById('catStartTime').value = c.start_time || '';
            document.getElementById('catEndTime').value = c.end_time || '';
            document.getElementById('catModalTitle').textContent = 'Edit Category';
            var days = (c.available_days || '').split(',');
            document.querySelectorAll('input[name="available_days[]"]').forEach(function(cb) {
                cb.checked = days.indexOf(cb.value) !== -1;
            });
            if (c.image) {
                document.getElementById('catImagePreview').src = BASE_URL + '/' + c.image;
                document.getElementById('catImagePreview').style.display = 'block';
            }
            new bootstrap.Modal(document.getElementById('categoryModal')).show();
        }
    });
}

document.getElementById('categoryForm').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/category_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);
        }
    })
    .catch(function() {
        showAlert('danger', 'An error occurred');
    });
});

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 category';
        if (confirm('Are you sure you want to delete "' + name + '"?')) {
            ajaxPost(BASE_URL + '/restaurant-admin/category_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);
                }
            });
        }
    });
});

document.querySelectorAll('.toggle-status').forEach(function(toggle) {
    toggle.addEventListener('change', function(e) {
        e.preventDefault();
        var id = this.dataset.id;
        ajaxPost(BASE_URL + '/restaurant-admin/category_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);
            }
        });
    });
});
</script>

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