<?php
ob_start();
?>

<div class="row mb-4">
    <div class="col-md-6">
        <h2><i class="bi bi-file-earmark-text me-2"></i> Contratos</h2>
        <p class="text-muted">Gerencie todos os contratos da empresa</p>
    </div>
    <div class="col-md-6 text-end">
        <a href="<?= url('/contratos/criar') ?>" class="btn btn-primary">
            <i class="bi bi-plus-circle me-2"></i> Novo Contrato
        </a>
    </div>
</div>

<style>
/* Cards de opções (padrão semelhante ao módulo Vendas) */
.opcoes-grupo {
    margin-bottom: 1.5rem;
    padding: 0 0.5rem;
}

.opcoes-grupo:last-child {
    margin-bottom: 0.5rem;
}

.opcoes-titulo {
    font-size: 0.85rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.08em;
    color: #64748b;
    margin-bottom: 0.6rem;
    display: flex;
    align-items: center;
    gap: 0.35rem;
}

.opcoes-titulo::before {
    content: '';
    width: 6px;
    height: 6px;
    border-radius: 50%;
    background: #cbd5f5;
}

.opcoes-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 0.75rem;
}

.opcao-card {
    width: 130px;
    height: 130px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 0.75rem;
    border: 2px solid #e0e0e0;
    border-radius: 12px;
    background: white;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
    padding: 1rem;
}

.opcao-card i { font-size: 2rem; }
.opcao-card span { font-size: 0.9rem; font-weight: 600; text-align: center; }
.opcao-card:hover { transform: translateY(-4px); box-shadow: 0 8px 18px rgba(0,0,0,0.12); }
.opcao-card-primary { border-color: #0d6efd; color: #0d6efd; }
.opcao-card-primary:hover { background: #0d6efd; color: #fff; }
.opcao-card-success { border-color: #198754; color: #198754; }
.opcao-card-success:hover { background: #198754; color: #fff; }
.opcao-card-warning { border-color: #ffc107; color: #ffc107; }
.opcao-card-warning:hover { background: #ffc107; color: #fff; }
.opcao-card-danger { border-color: #dc3545; color: #dc3545; }
.opcao-card-danger:hover { background: #dc3545; color: #fff; }
.opcao-card-secondary { border-color: #6c757d; color: #6c757d; }
.opcao-card-secondary:hover { background: #6c757d; color: #fff; }
.opcao-card-info { border-color: #0dcaf0; color: #0dcaf0; }
.opcao-card-info:hover { background: #0dcaf0; color: #fff; }

.swal-contrato-opcoes {
    border-radius: 16px;
    overflow: visible !important;
}
.swal-contrato-container {
    margin: 0 !important;
    padding: 0 !important;
    overflow: visible !important;
}
.swal-contrato-opcoes .swal2-html-container {
    overflow: visible !important;
}
.swal-contrato-opcoes .swal2-close {
    color: white !important;
    background: rgba(255,255,255,0.25) !important;
    border-radius: 8px !important;
    width: 36px !important;
    height: 36px !important;
    font-size: 1.5rem !important;
    transition: all 0.2s !important;
    top: 1rem !important;
    right: 1rem !important;
    box-shadow: 0 2px 8px rgba(0,0,0,0.2) !important;
    z-index: 9999 !important;
}
.swal-contrato-opcoes .swal2-close:hover {
    background: rgba(255,255,255,0.4) !important;
    transform: scale(1.1) !important;
}
.swal-contrato-opcoes .swal2-close:focus {
    box-shadow: 0 0 0 3px rgba(255,255,255,0.3) !important;
}
.opcoes-grid {
    padding: 1rem !important;
}
</style>

<div class="card">
    <div class="card-header">
        <div class="row">
            <div class="col-md-6">
                <input type="text" class="form-control" id="search-contratos" placeholder="Buscar contratos..." onkeyup="filterTable('contratos-table', this.value)">
            </div>
            <div class="col-md-3">
                <select class="form-select" id="filter-status" onchange="filterTableByStatus('contratos-table', this.value)">
                    <option value="">Todos os Status</option>
                    <option value="rascunho">Rascunho</option>
                    <option value="ativo">Ativo</option>
                    <option value="suspenso">Suspenso</option>
                    <option value="cancelado">Cancelado</option>
                    <option value="vencido">Vencido</option>
                    <option value="renovado">Renovado</option>
                </select>
            </div>
            <div class="col-md-3">
                <select class="form-select" id="filter-tipo" onchange="filterTableByTipo('contratos-table', this.value)">
                    <option value="">Todos os Tipos</option>
                    <option value="licenca_software">Licença de Software</option>
                    <option value="prestacao_servicos">Prestação de Serviços</option>
                    <option value="manutencao">Manutenção</option>
                    <option value="suporte">Suporte</option>
                    <option value="outro">Outro</option>
                </select>
            </div>
        </div>
    </div>
    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover" id="contratos-table">
                <thead>
                    <tr>
                        <th width="80">Número</th>
                        <th>Tipo</th>
                        <th>Cliente</th>
                        <th>Data Início</th>
                        <th>Data Fim</th>
                        <th>Valor Mensal</th>
                        <th>Status</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (!empty($contratos)): ?>
                    <?php foreach ($contratos as $contrato): ?>
                    <tr style="cursor: pointer;"
                        data-contrato-id="<?= $contrato['id'] ?>"
                        data-contrato-numero="<?= htmlspecialchars($contrato['numero_contrato'], ENT_QUOTES) ?>"
                        data-contrato-tipo="<?= htmlspecialchars($contrato['tipo'], ENT_QUOTES) ?>"
                        data-contrato-empresa="<?= htmlspecialchars($contrato['empresa_nome'] ?? '', ENT_QUOTES) ?>"
                        data-contrato-pessoa="<?= htmlspecialchars($contrato['pessoa_nome'] ?? '', ENT_QUOTES) ?>"
                        data-contrato-valor-mensal="<?= number_format($contrato['valor_mensal'], 2, ',', '.') ?>"
                        data-contrato-status="<?= htmlspecialchars($contrato['status'], ENT_QUOTES) ?>"
                        onclick="abrirOpcoesContrato(event)">
                        <td><strong><?= htmlspecialchars($contrato['numero_contrato']) ?></strong></td>
                        <td>
                            <?php
                            $tipos = [
                                'licenca_software' => 'Licença Software',
                                'site' => 'Site',
                                'loja_virtual' => 'Loja Virtual',
                                'treinamento_adicional' => 'Treinamento Adicional',
                                'manutencao' => 'Manutenção',
                                'suporte' => 'Suporte',
                                'outro' => 'Outro'
                            ];
                            echo $tipos[$contrato['tipo']] ?? $contrato['tipo'];
                            ?>
                        </td>
                        <td>
                            <?php if ($contrato['empresa_nome']): ?>
                                <i class="bi bi-building me-1"></i><?= htmlspecialchars($contrato['empresa_nome']) ?>
                            <?php elseif ($contrato['pessoa_nome']): ?>
                                <i class="bi bi-person me-1"></i><?= htmlspecialchars($contrato['pessoa_nome']) ?>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td><?= date('d/m/Y', strtotime($contrato['data_inicio'])) ?></td>
                        <td>
                            <?php if ($contrato['data_fim']): ?>
                                <?= date('d/m/Y', strtotime($contrato['data_fim'])) ?>
                            <?php else: ?>
                                <span class="text-muted">Sem término</span>
                            <?php endif; ?>
                        </td>
                        <td>R$ <?= number_format($contrato['valor_mensal'], 2, ',', '.') ?></td>
                        <td>
                            <?php
                            $statusClasses = [
                                'rascunho' => 'secondary',
                                'ativo' => 'success',
                                'suspenso' => 'warning',
                                'cancelado' => 'danger',
                                'vencido' => 'dark',
                                'renovado' => 'info'
                            ];
                            $statusLabels = [
                                'rascunho' => 'Rascunho',
                                'ativo' => 'Ativo',
                                'suspenso' => 'Suspenso',
                                'cancelado' => 'Cancelado',
                                'vencido' => 'Vencido',
                                'renovado' => 'Renovado'
                            ];
                            $class = $statusClasses[$contrato['status']] ?? 'secondary';
                            $label = $statusLabels[$contrato['status']] ?? $contrato['status'];
                            ?>
                            <span class="badge bg-<?= $class ?>"><?= $label ?></span>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php else: ?>
                    <tr>
                        <td colspan="7" class="text-center text-muted py-4">
                            <i class="bi bi-inbox fs-1 d-block mb-2"></i>
                            Nenhum contrato encontrado
                        </td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<script>
function filterTable(tableId, searchValue) {
    const table = document.getElementById(tableId);
    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        const text = rows[i].textContent || rows[i].innerText;
        rows[i].style.display = text.toLowerCase().indexOf(searchValue.toLowerCase()) > -1 ? '' : 'none';
    }
}

function filterTableByStatus(tableId, status) {
    const table = document.getElementById(tableId);
    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        const statusBadge = rows[i].querySelector('.badge');
        if (status === '' || (statusBadge && statusBadge.textContent.toLowerCase().includes(status.toLowerCase()))) {
            rows[i].style.display = '';
        } else {
            rows[i].style.display = 'none';
        }
    }
}

function filterTableByTipo(tableId, tipo) {
    const table = document.getElementById(tableId);
    const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');

    for (let i = 0; i < rows.length; i++) {
        const cells = rows[i].getElementsByTagName('td');
        if (cells.length > 1) {
            const tipoText = cells[1].textContent.toLowerCase();
            if (tipo === '' || tipoText.includes(tipo.toLowerCase())) {
                rows[i].style.display = '';
            } else {
                rows[i].style.display = 'none';
            }
        }
    }
}

function abrirOpcoesContrato(event) {
    // Prevenir propagação do evento
    event.stopPropagation();

    // Buscar dados da linha da tabela
    const row = event.target.closest('tr');
    if (!row) return;

    const id = row.dataset.contratoId;
    const numero = row.dataset.contratoNumero;
    const tipo = row.dataset.contratoTipo;
    const empresa = row.dataset.contratoEmpresa || '';
    const pessoa = row.dataset.contratoPessoa || '';
    const valorMensal = row.dataset.contratoValorMensal || '0,00';
    const status = row.dataset.contratoStatus || '';

    const tiposLabels = {
        'licenca_software': 'Licença Software',
        'site': 'Site',
        'loja_virtual': 'Loja Virtual',
        'treinamento_adicional': 'Treinamento Adicional',
        'manutencao': 'Manutenção',
        'suporte': 'Suporte',
        'outro': 'Outro'
    };

    const statusLabels = {
        'rascunho': 'Rascunho',
        'ativo': 'Ativo',
        'suspenso': 'Suspenso',
        'cancelado': 'Cancelado',
        'vencido': 'Vencido',
        'renovado': 'Renovado'
    };

    const tipoLabel = tiposLabels[tipo] || tipo;
    const statusLabel = statusLabels[status] || status;
    const clienteNome = empresa || pessoa || 'Não informado';

    const headerHtml = `
        <div style="background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
                    padding: 1.5rem;
                    margin: 0 0 1rem 0;
                    border-radius: 12px 12px 0 0;
                    color: white;
                    text-align: left;">
            <div style="display: flex; align-items: center; gap: 1rem; margin-bottom: 0.75rem;">
                <div style="background: rgba(255,255,255,0.2);
                            padding: 0.75rem;
                            border-radius: 10px;
                            display: flex;
                            align-items: center;
                            justify-content: center;">
                    <i class="bi bi-file-earmark-text" style="font-size: 1.5rem;"></i>
                </div>
                <div style="flex: 1; padding-right: 3rem;">
                    <div style="font-size: 0.85rem; opacity: 0.9; margin-bottom: 0.25rem;">Contrato</div>
                    <div style="font-size: 1.25rem; font-weight: 700;">${numero}</div>
                </div>
                <div style="text-align: right; min-width: 140px; padding-right: 2.5rem;">
                    <div style="font-size: 0.85rem; opacity: 0.9; margin-bottom: 0.25rem;">Valor Mensal</div>
                    <div style="font-size: 1.15rem; font-weight: 600;">R$ ${valorMensal}</div>
                </div>
            </div>
            <div style="background: rgba(255,255,255,0.15);
                        padding: 0.75rem 1rem;
                        border-radius: 8px;
                        display: flex;
                        align-items: center;
                        gap: 0.75rem;">
                <i class="bi bi-person-circle" style="font-size: 1.1rem; opacity: 0.9;"></i>
                <div style="flex: 1;">
                    <strong style="font-size: 0.95rem;">${clienteNome}</strong>
                    <div style="opacity: 0.9; font-size: 0.85rem; margin-top: 0.25rem;">
                        <i class="bi bi-tag" style="font-size: 0.85rem; margin-right: 0.25rem;"></i>
                        ${tipoLabel} • ${statusLabel}
                    </div>
                </div>
            </div>
        </div>
    `;

    const contratoButtons = `
        <div class="opcoes-grupo">
            <h6 class="opcoes-titulo">Contrato</h6>
            <div class="opcoes-grid">
                <button type="button" class="opcao-card opcao-card-secondary" onclick="window.location.href=appUrl('/contratos/visualizar?id=${id}')">
                    <i class="bi bi-eye"></i>
                    <span>Ver contrato</span>
                </button>
                <button type="button" class="opcao-card opcao-card-secondary" onclick="window.open(appUrl('/contratos/imprimir?id=${id}'), '_blank')">
                    <i class="bi bi-printer-fill"></i>
                    <span>Imprimir contrato</span>
                </button>
                <button type="button" class="opcao-card opcao-card-primary" onclick="window.location.href=appUrl('/contratos/editar?id=${id}')">
                    <i class="bi bi-pencil"></i>
                    <span>Editar contrato</span>
                </button>
                <button type="button" class="opcao-card opcao-card-danger" onclick="deletarContrato(${id}, '${numero.replace(/'/g, "&#39;")}')">
                    <i class="bi bi-trash"></i>
                    <span>Excluir contrato</span>
                </button>
            </div>
        </div>
    `;

    const html = headerHtml + contratoButtons;

    Swal.fire({
        html: html,
        showConfirmButton: false,
        showCloseButton: true,
        width: '700px',
        padding: '0',
        customClass: {
            popup: 'swal-contrato-opcoes',
            htmlContainer: 'swal-contrato-container'
        }
    });
}

function deletarContrato(id, numero) {
    Swal.close();

    Swal.fire({
        title: 'Confirmar exclusão',
        text: `Deseja realmente excluir o contrato ${numero}?`,
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc3545',
        cancelButtonColor: '#6c757d',
        confirmButtonText: 'Sim, excluir',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: appUrl('/contratos/deletar'),
                type: 'POST',
                data: { id: id },
                dataType: 'json',
                success: function(response) {
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Sucesso!',
                            text: response.message || 'Contrato excluído com sucesso',
                            timer: 1500,
                            showConfirmButton: false
                        }).then(() => {
                            window.location.reload();
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Erro!',
                            text: response.message || 'Erro ao excluir contrato'
                        });
                    }
                },
                error: function(xhr) {
                    let message = 'Erro ao processar requisição';
                    if (xhr.responseJSON && xhr.responseJSON.message) {
                        message = xhr.responseJSON.message;
                    }
                    Swal.fire({
                        icon: 'error',
                        title: 'Erro!',
                        text: message
                    });
                }
            });
        }
    });
}
</script>

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

