<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-12">
        <nav aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a href="<?= url('/dashboard') ?>">Dashboard</a></li>
                <li class="breadcrumb-item active">Categorias</li>
            </ol>
        </nav>
        <h2><i class="bi bi-tags me-2"></i> Categorias</h2>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-list-ul me-2"></i> Lista de Categorias</h5>
                <div class="d-flex gap-2">
                    <button class="btn btn-outline-secondary" onclick="filtrarCategorias()">
                        <i class="bi bi-funnel"></i> Filtrar
                    </button>
                    <a href="<?= url('/categorias/criar') ?>" class="btn btn-primary">
                        <i class="bi bi-plus-circle me-2"></i> Nova Categoria
                    </a>
                </div>
            </div>
            <div class="card-body">
                <!-- Filtros -->
                <div class="row mb-3" id="filtrosCategorias" style="display: none;">
                    <div class="col-md-4">
                        <label for="filtroTipo" class="form-label">Tipo</label>
                        <select class="form-select" id="filtroTipo">
                            <option value="">Todos</option>
                            <option value="produtos">Produtos</option>
                            <option value="servicos">Serviços</option>
                            <option value="ambos">Ambos</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="filtroStatus" class="form-label">Status</label>
                        <select class="form-select" id="filtroStatus">
                            <option value="">Todos</option>
                            <option value="1">Ativas</option>
                            <option value="0">Inativas</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="filtroBusca" class="form-label">Buscar</label>
                        <input type="text" class="form-control" id="filtroBusca" placeholder="Nome ou descrição...">
                    </div>
                </div>

                <!-- Tabela -->
                <div class="table-responsive">
                    <table class="table table-hover" id="tabelaCategorias">
                        <thead class="table-light">
                            <tr>
                                <th>Nome</th>
                                <th>Tipo</th>
                                <th>Descrição</th>
                                <th>Produtos</th>
                                <th>Status</th>
                                <th width="120">Ações</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (!empty($categorias)): ?>
                                <?php foreach ($categorias as $categoria): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center">
                                                <?php if ($categoria['icon']): ?>
                                                    <i class="<?= $categoria['icon'] ?> me-2 text-primary"></i>
                                                <?php endif; ?>
                                                <strong><?= htmlspecialchars($categoria['name']) ?></strong>
                                            </div>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $categoria['type'] === 'produtos' ? 'success' : ($categoria['type'] === 'servicos' ? 'info' : 'warning') ?>">
                                                <?= ucfirst($categoria['type']) ?>
                                            </span>
                                        </td>
                                        <td><?= htmlspecialchars($categoria['description'] ?? '') ?></td>
                                        <td>
                                            <span class="badge bg-secondary">
                                                <?= $categoria['product_count'] ?? 0 ?> produtos
                                            </span>
                                        </td>
                                        <td>
                                            <span class="badge bg-<?= $categoria['is_active'] ? 'success' : 'danger' ?>">
                                                <?= $categoria['is_active'] ? 'Ativa' : 'Inativa' ?>
                                            </span>
                                        </td>
                                        <td>
                                            <div class="btn-group btn-group-sm" role="group">
                                                <a href="<?= url('/categorias/editar?id=' . $categoria['id']) ?>"
                                                   class="btn btn-outline-primary" title="Editar">
                                                    <i class="bi bi-pencil"></i>
                                                </a>
                                                <button class="btn btn-outline-danger"
                                                        onclick="deletarCategoria(<?= $categoria['id'] ?>)"
                                                        title="Excluir">
                                                    <i class="bi bi-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            <?php else: ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted py-4">
                                        <i class="bi bi-inbox display-6 d-block mb-2"></i>
                                        Nenhuma categoria encontrada
                                    </td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // Filtros
    $('#filtroTipo, #filtroStatus, #filtroBusca').on('change keyup', function() {
        filtrarTabela();
    });
});

function filtrarCategorias() {
    $('#filtrosCategorias').toggle();
}

function filtrarTabela() {
    const tipo = $('#filtroTipo').val().toLowerCase();
    const status = $('#filtroStatus').val();
    const busca = $('#filtroBusca').val().toLowerCase();

    $('#tabelaCategorias tbody tr').each(function() {
        const $row = $(this);
        const tipoRow = $row.find('td:nth-child(2) .badge').text().toLowerCase();
        const statusRow = $row.find('td:nth-child(5) .badge').text().toLowerCase();
        const textoRow = $row.text().toLowerCase();

        const matchTipo = !tipo || tipoRow.includes(tipo);
        const matchStatus = !status || (status === '1' && statusRow.includes('ativa')) || (status === '0' && statusRow.includes('inativa'));
        const matchBusca = !busca || textoRow.includes(busca);

        $row.toggle(matchTipo && matchStatus && matchBusca);
    });
}

function deletarCategoria(id) {
    confirmDelete('Tem certeza que deseja excluir esta categoria?', function() {
        $.ajax({
            url: appUrl('/categorias/deletar'),
            type: 'POST',
            data: { id: id },
            dataType: 'json',
            success: function(response) {
                if (response.success) {
                    Swal.fire({
                        icon: 'success',
                        title: 'Sucesso!',
                        text: response.message,
                        showConfirmButton: false,
                        timer: 1500
                    }).then(() => {
                        location.reload();
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: 'Erro',
                        text: response.message
                    });
                }
            },
            error: function() {
                Swal.fire({
                    icon: 'error',
                    title: 'Erro',
                    text: 'Erro ao excluir categoria'
                });
            }
        });
    });
}
</script>

<?php
$content = ob_get_clean();
$activeMenu = 'categorias';
include ROOT_PATH . '/views/layouts/app.php';
?>
