<?php
// ===============================
// NOTAS FISCAIS - LISTAGEM (SAAS)
// ===============================

require '../config/config.php';
require '../config/database.php';
require '../config/auth.php';

include 'layout/header.php';

// Busca SOMENTE notas do usuário logado
$stmt = $pdo->prepare("
    SELECT 
        n.id,
        n.chave,
        n.data_emissao,
        n.valor,
        n.xml_path,
        e.razao_social
    FROM notas_fiscais n
    INNER JOIN empresas e ON e.id = n.empresa_id
    WHERE e.usuario_id = ?
    ORDER BY n.data_emissao DESC
");

$stmt->execute([$_SESSION['user_id']]);
$notas = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<h1 class="text-2xl font-bold mb-6">📄 Notas Fiscais (XML)</h1>

<?php if (count($notas) === 0): ?>
    <div class="bg-yellow-100 text-yellow-800 p-4 rounded">
        Nenhuma nota fiscal encontrada para este usuário.
    </div>
<?php else: ?>

<div class="overflow-x-auto">
<table class="min-w-full bg-white rounded shadow">
    <thead class="bg-gray-200 text-gray-700">
        <tr>
            <th class="p-3 text-left">Empresa</th>
            <th class="p-3 text-left">Chave</th>
            <th class="p-3 text-left">Data Emissão</th>
            <th class="p-3 text-right">Valor</th>
            <th class="p-3 text-center">Ações</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($notas as $nota): ?>
        <tr class="border-b hover:bg-gray-50">
            <td class="p-3">
                <?= htmlspecialchars($nota['razao_social']) ?>
            </td>

            <td class="p-3 text-sm break-all">
                <?= htmlspecialchars($nota['chave']) ?>
            </td>

            <td class="p-3">
                <?= $nota['data_emissao'] 
                    ? date('d/m/Y', strtotime($nota['data_emissao'])) 
                    : '-' ?>
            </td>

            <td class="p-3 text-right">
                R$ <?= number_format((float)$nota['valor'], 2, ',', '.') ?>
            </td>

            <td class="p-3 text-center space-x-3">
                <a 
                    href="ver_xml.php?id=<?= (int)$nota['id'] ?>" 
                    class="text-blue-600 hover:underline"
                    target="_blank"
                >
                    👁️ Ver
                </a>

                <a 
                    href="download.php?id=<?= (int)$nota['id'] ?>" 
                    class="text-green-600 hover:underline"
                >
                    ⬇️ Download
                </a>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
</div>

<?php endif; ?>

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