<?php
include_once('../config.php');
include_once('../header.php');

$cupons = $conn->query("SELECT * FROM cupons_gerados ORDER BY data_criacao DESC");
?>

<div class="cupom-wrapper">
    <div class="secao-titulo">📜 HISTÓRICO DE CUPONS GERADOS</div>
    
    <table class="table-itens">
        <thead>
            <tr>
                <th>DATA</th>
                <th>CLIENTE</th>
                <th style="text-align: right;">TOTAL</th>
                <th style="text-align: center;">AÇÃO</th>
            </tr>
        </thead>
        <tbody>
            <?php while($row = $cupons->fetch_assoc()): ?>
                <tr>
                    <td><?php echo date('d/m/Y H:i', strtotime($row['data_criacao'])); ?></td>
                    <td><?php echo $row['cliente_nome']; ?></td>
                    <td style="text-align: right;">R$ <?php echo number_format($row['total_geral'], 2, ',', '.'); ?></td>
                    <td style="text-align: center;">
                        <button class="btn-add" style="padding: 5px 10px; font-size: 10px;" onclick="verDetalhes(<?php echo $row['id']; ?>)">👁️ VER</button>
                    </td>
                </tr>
                <tr id="detalhe-<?php echo $row['id']; ?>" style="display:none; background: #f0f0f0;">
                    <td colspan="4" style="font-size: 11px; text-transform: none;">
                        <strong>Dados:</strong> <?php echo $row['cliente_dados']; ?><br>
                        <strong>Itens:</strong> 
                        <ul>
                            <?php 
                            $produtos = json_decode($row['itens_json'], true);
                            foreach($produtos as $p) {
                                echo "<li>{$p['qtd']}x {$p['nome']} - R$ " . number_format($p['total'], 2, ',', '.') . "</li>";
                            }
                            ?>
                        </ul>
                    </td>
                </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<script>
function verDetalhes(id) {
    const el = document.getElementById('detalhe-' + id);
    el.style.display = el.style.display === 'none' ? 'table-row' : 'none';
}
</script>