<?php
require_once 'includes/funcoes.php';
include 'includes/header.php';

$pdo = conectarBanco();

// Buscar rascunhos
$stmt = $pdo->prepare("
    SELECT n.*, 
           e.razao_social as emitente_nome,
           t.razao_social as tomador_nome,
           emp.nome as empresa_nome
    FROM notas_fiscais n
    LEFT JOIN emitentes e ON n.emitente_id = e.id
    LEFT JOIN tomadores t ON n.tomador_id = t.id
    LEFT JOIN empresas emp ON n.empresa_id = emp.id
    WHERE n.status IN ('rascunho', 'pendente', 'erro')
    ORDER BY n.criado_em DESC
");
$stmt->execute();
$notas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>Gerenciar Rascunhos - NFSe</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body>

<div class="container-fluid mt-3">
    <div class="d-flex justify-content-between flex-wrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1><i class="bi bi-files"></i> Gerenciar Rascunhos</h1>
        <div>
            <a href="cadastrar_nota.php" class="btn btn-primary">
                <i class="bi bi-plus-circle"></i> Nova Nota
            </a>
            <a href="emitir_lote.php" class="btn btn-success">
                <i class="bi bi-send"></i> Emitir Selecionadas
            </a>
        </div>
    </div>

    <div class="card shadow">
        <div class="card-header bg-primary text-white">
            <strong><i class="bi bi-table"></i> Notas Fiscais</strong>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead class="table-dark">
                        <tr>
                            <th width="40"><input type="checkbox" id="selectAll"></th>
                            <th>ID</th>
                            <th>Empresa</th>
                            <th>Emitente</th>
                            <th>Tomador</th>
                            <th>Valor</th>
                            <th>Status</th>
                            <th>Criado em</th>
                            <th width="150">Ações</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($notas as $nota): ?>
                        <tr>
                            <td><input type="checkbox" class="nota-checkbox" value="<?php echo $nota['id']; ?>"></td>
                            <td><?php echo $nota['id']; ?></td>
                            <td><?php echo htmlspecialchars(substr($nota['empresa_nome'], 0, 30)); ?></td>
                            <td><?php echo htmlspecialchars(substr($nota['emitente_nome'], 0, 30)); ?></td>
                            <td><?php echo htmlspecialchars(substr($nota['tomador_nome'], 0, 30)); ?></td>
                            <td>R$ <?php echo number_format($nota['valor_servico'], 2, ',', '.'); ?></td>
                            <td>
                                <?php if ($nota['status'] == 'rascunho'): ?>
                                    <span class="badge bg-secondary">📝 Rascunho</span>
                                <?php elseif ($nota['status'] == 'pendente'): ?>
                                    <span class="badge bg-warning">⏳ Pendente</span>
                                <?php elseif ($nota['status'] == 'erro'): ?>
                                    <span class="badge bg-danger">❌ Erro</span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo date('d/m/Y H:i', strtotime($nota['criado_em'])); ?></td>
                            <td>
                                <a href="cadastrar_nota.php?id=<?php echo $nota['id']; ?>" class="btn btn-sm btn-warning" title="Editar">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <button class="btn btn-sm btn-danger" onclick="excluir(<?php echo $nota['id']; ?>)" title="Excluir">
                                    <i class="bi bi-trash"></i>
                                </button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                        <?php if (empty($notas)): ?>
                        <tr>
                            <td colspan="9" class="text-center">Nenhum rascunho encontrado</td>
                        </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('#selectAll').click(function() {
    $('.nota-checkbox').prop('checked', $(this).prop('checked'));
});

function excluir(id) {
    if (confirm('Tem certeza que deseja excluir esta nota?')) {
        $.ajax({
            url: '/emissornota/api/excluir_rascunho.php',
            method: 'POST',
            data: JSON.stringify({ id: id }),
            contentType: 'application/json',
            success: function(response) {
                if (response.sucesso) {
                    location.reload();
                } else {
                    alert('Erro ao excluir: ' + response.erro);
                }
            }
        });
    }
}
</script>

<?php include 'includes/footer.php'; ?>