<?php
ob_start();

$status = $status ?? [];
$modulos = $modulos ?? [];
$filters = $filters ?? [
    'search' => '',
    'modulo' => '',
    'ativo' => '',
    'padrao' => '',
    'final' => '',
];
?>

<div class="row mb-4">
    <div class="col-md-8">
        <h2><i class="bi bi-diagram-3 me-2"></i> Gestão de Status</h2>
        <p class="text-muted mb-0">Configure os status utilizados em cada módulo do sistema.</p>
    </div>
</div>

<div class="card mb-4 shadow-sm">
    <div class="card-body">
        <form method="GET" class="row g-3 align-items-end">
            <div class="col-md-4">
                <label class="form-label text-muted">Busca</label>
                <input type="text" class="form-control" name="search" placeholder="Buscar por nome, código ou descrição"
                    value="<?= htmlspecialchars($filters['search'] ?? '') ?>">
            </div>

            <div class="col-md-3">
                <label class="form-label text-muted">Módulo</label>
                <select class="form-select" name="modulo">
                    <option value="">Todos os módulos</option>
                    <?php foreach ($modulos as $modulo): ?>
                    <?php $selected = ($filters['modulo'] ?? '') === $modulo ? 'selected' : ''; ?>
                    <option value="<?= htmlspecialchars($modulo) ?>" <?= $selected ?>>
                        <?= htmlspecialchars(ucwords(str_replace('_', ' ', $modulo))) ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label text-muted">Ativo</label>
                <select class="form-select" name="ativo">
                    <option value="">Todos</option>
                    <option value="1" <?= ($filters['ativo'] ?? '') === '1' ? 'selected' : '' ?>>Ativos</option>
                    <option value="0" <?= ($filters['ativo'] ?? '') === '0' ? 'selected' : '' ?>>Inativos</option>
                </select>
            </div>

            <div class="col-md-2">
                <label class="form-label text-muted">Padrão</label>
                <select class="form-select" name="padrao">
                    <option value="">Todos</option>
                    <option value="1" <?= ($filters['padrao'] ?? '') === '1' ? 'selected' : '' ?>>Sim</option>
                    <option value="0" <?= ($filters['padrao'] ?? '') === '0' ? 'selected' : '' ?>>Não</option>
                </select>
            </div>

            <div class="col-md-1 d-grid">
                <button type="submit" class="btn btn-secondary">
                    <i class="bi bi-filter me-1"></i> Filtrar
                </button>
            </div>

            <div class="col-md-2 ms-auto">
                <label class="form-label text-muted">Finalizador</label>
                <select class="form-select" name="final">
                    <option value="">Todos</option>
                    <option value="1" <?= ($filters['final'] ?? '') === '1' ? 'selected' : '' ?>>Sim</option>
                    <option value="0" <?= ($filters['final'] ?? '') === '0' ? 'selected' : '' ?>>Não</option>
                </select>
            </div>
        </form>
    </div>
</div>

<div class="card shadow-sm">
    <div class="card-header d-flex justify-content-between align-items-center">
        <span><i class="bi bi-list-check me-2"></i> Status cadastrados</span>
        <span class="badge bg-primary"><?= count($status) ?> registro(s)</span>
    </div>
    <div class="card-body p-0">
        <?php if (!empty($status)): ?>
        <?php
            $statusAgrupados = [];
            foreach ($status as $item) {
                $chaveModulo = $item['modulo'] ?? 'outros';
                $statusAgrupados[$chaveModulo][] = $item;
            }
            ksort($statusAgrupados);
            ?>
        <div class="table-responsive">
            <?php foreach ($statusAgrupados as $moduloNome => $lista): ?>
            <?php
                    usort($lista, static function ($a, $b) {
                        return ($a['ordem'] ?? 0) <=> ($b['ordem'] ?? 0);
                    });
                    ?>
            <div class="status-module-group">
                <div class="status-module-header">
                    <div class="status-module-title">
                        <i class="bi bi-grid-3x3-gap me-2"></i>
                        <?= htmlspecialchars(ucwords(str_replace('_', ' ', $moduloNome))) ?>
                    </div>
                    <span class="badge bg-dark"><?= count($lista) ?> status ·
                        <?= htmlspecialchars(ucwords(str_replace('_', ' ', $moduloNome))) ?></span>
                </div>
                <table class="table table-hover mb-0 align-middle status-group-table">
                    <thead>
                        <tr>
                            <th>Nome</th>
                            <th>Descrição</th>
                            <th class="text-center" style="width: 140px;">Ordem</th>
                            <th class="text-center" style="width: 110px;">Financeiro</th>
                            <th class="text-center" style="width: 110px;">Estoque</th>
                            <th class="text-center" style="width: 120px;">NF-e</th>
                            <th style="width: 80px;">Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($lista as $item): ?>
                        <tr class="status-row" data-id="<?= (int) ($item['id'] ?? 0) ?>"
                            data-nome="<?= htmlspecialchars($item['nome'] ?? '-') ?>"
                            data-modulo="<?= htmlspecialchars(ucwords(str_replace('_', ' ', $moduloNome))) ?>"
                            data-codigo="<?= htmlspecialchars($item['codigo'] ?? '-') ?>"
                            data-descricao="<?= htmlspecialchars($item['descricao'] ?? '') ?>"
                            data-edit-url="<?= url('/gestao/status/editar?id=' . ($item['id'] ?? 0)) ?>">
                            <td>
                                <div class="d-flex align-items-center justify-content-between gap-3">
                                    <div class="d-flex align-items-center gap-2">
                                        <span class="status-color-dot"
                                            style="background: <?= htmlspecialchars($item['cor'] ?? '#6c757d') ?>;"></span>

                                        <span class="fw-semibold"><?= htmlspecialchars($item['nome'] ?? '-') ?></span>
                                    </div>
                                    <i class="bi bi-chevron-right text-muted status-row-indicator"></i>
                                </div>
                            </td>
                            <td>
                                <small class="text-muted"><?= htmlspecialchars($item['descricao'] ?? '-') ?></small>
                            </td>
                            <td class="text-center">
                                <span class="badge bg-dark">Ordem <?= (int) ($item['ordem'] ?? 0) ?></span>
                            </td>
                            <td class="text-center">
                                <span
                                    class="badge <?= ($item['gera_financeiro'] ?? 0) ? 'bg-success' : 'bg-secondary' ?>">
                                    <?= ($item['gera_financeiro'] ?? 0) ? 'Gera' : 'Não' ?>
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="d-flex justify-content-center gap-1">
                                    <span
                                        class="badge <?= ($item['movimenta_estoque'] ?? 0) ? 'bg-success' : 'bg-secondary' ?>">Mov.</span>
                                    <span
                                        class="badge <?= ($item['reserva_estoque'] ?? 0) ? 'bg-info text-dark' : 'bg-secondary' ?>">Res.</span>
                                    <span
                                        class="badge <?= ($item['previsao_estoque'] ?? 0) ? 'bg-warning text-dark' : 'bg-secondary' ?>">Prev.</span>
                                </div>
                            </td>
                            <td class="text-center">
                                <span
                                    class="badge <?= ($item['emite_nfe'] ?? 0) ? 'bg-info text-dark' : 'bg-secondary' ?>">
                                    <?= ($item['emite_nfe'] ?? 0) ? 'Emite' : 'Não' ?>
                                </span>
                            </td>
                            <td>
                                <span class="badge <?= ($item['ativo'] ?? 0) == 1 ? 'bg-success' : 'bg-danger' ?>">
                                    <?= ($item['ativo'] ?? 0) == 1 ? 'Ativo' : 'Inativo' ?>
                                </span>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endforeach; ?>
        </div>
        <?php else: ?>
        <div class="text-center py-5">
            <i class="bi bi-diagram-3" style="font-size: 4rem; color: var(--text-secondary);"></i>
            <p class="text-muted mt-3 mb-0">Nenhum status encontrado com os filtros atuais.</p>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const rows = document.querySelectorAll('.status-row');

    rows.forEach(function(row) {
        row.addEventListener('click', function() {
            const nome = this.dataset.nome || 'Status';
            const modulo = this.dataset.modulo || '';
            const codigo = this.dataset.codigo || '';
            const descricao = this.dataset.descricao || '';
            const editUrl = this.dataset.editUrl || '#';

            const html = `
                <div class="status-swal-content">
                    <div class="status-swal-header">
                        <span class="status-swal-module">${modulo}</span>
                        <h3 class="status-swal-title">${nome}</h3>
                        <span class="status-swal-code">${codigo}</span>
                    </div>
                    ${descricao ? `<p class="status-swal-description">${descricao}</p>` : ''}
                    <div class="status-swal-actions">
                        <button type="button" class="btn btn-primary status-swal-edit">
                            <i class="bi bi-pencil-square me-2"></i> Alterar status
                        </button>
                    </div>
                </div>`;

            Swal.fire({
                html: html,
                showConfirmButton: false,
                showCloseButton: true,
                width: 520,
                customClass: {
                    popup: 'swal-status-opcoes'
                },
                didOpen: function(popup) {
                    const editBtn = popup.querySelector('.status-swal-edit');
                    if (editBtn) {
                        editBtn.addEventListener('click', function() {
                            window.location.href = editUrl;
                        });
                    }
                }
            });
        });
    });
});
</script>

<style>
.status-module-group+.status-module-group {
    border-top: 1px solid rgba(255, 255, 255, 0.05);
}

.status-module-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 1.25rem 1.5rem 0.75rem;
    background: rgba(255, 255, 255, 0.02);
}

.status-module-title {
    font-weight: 700;
    text-transform: uppercase;
    font-size: 0.95rem;
    letter-spacing: 0.06em;
    color: rgba(255, 255, 255, 0.85);
}

.status-group-table thead {
    background: rgba(255, 255, 255, 0.02);
}

.status-group-table tbody tr:hover {
    background: rgba(13, 110, 253, 0.12);
}

.status-color-dot {
    width: 12px;
    height: 12px;
    border-radius: 50%;
    display: inline-block;
    box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}

.status-row {
    cursor: pointer;
}

.status-row-indicator {
    transition: transform 0.2s ease;
}

.status-row:hover .status-row-indicator {
    transform: translateX(4px);
}

.swal-status-opcoes {
    background: rgba(18, 24, 38, 0.95);
    border: 1px solid rgba(255, 255, 255, 0.05);
    border-radius: 1rem;
    color: #f8fafc;
}

.status-swal-content {
    text-align: left;
    padding: 0.5rem 0.25rem 0.25rem;
}

.status-swal-module {
    display: inline-block;
    font-size: 0.75rem;
    letter-spacing: 0.08em;
    text-transform: uppercase;
    color: rgba(148, 163, 184, 0.9);
    margin-bottom: 0.35rem;
}

.status-swal-title {
    margin: 0;
    font-size: 1.4rem;
    font-weight: 700;
    color: #f1f5f9;
}

.status-swal-code {
    display: inline-block;
    margin-top: 0.35rem;
    padding: 0.2rem 0.6rem;
    border-radius: 999px;
    background: rgba(148, 163, 184, 0.15);
    color: rgba(226, 232, 240, 0.95);
    font-size: 0.8rem;
}

.status-swal-description {
    margin: 1rem 0 0;
    font-size: 0.9rem;
    color: rgba(203, 213, 225, 0.9);
}

.status-swal-actions {
    margin-top: 1.5rem;
    display: flex;
    gap: 0.75rem;
}

.status-swal-actions .btn {
    flex: 1;
    font-weight: 600;
}
</style>

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