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

// Lógica para excluir venda e itens
if (isset($_GET['del'])) {
    $id = (int)$_GET['del'];
    $conn->query("DELETE FROM itens_venda WHERE venda_id = '$id'");
    $conn->query("DELETE FROM comprovantes_pagamento WHERE id = '$id'");
    echo "<script>location.href='comprovantes_pagamento.php';</script>";
    exit;
}

$res = $conn->query("SELECT * FROM comprovantes_pagamento ORDER BY data_emissao DESC");
?>

<div style="padding: 20px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase;">
    <h2 style="color: #00569e; border-bottom: 2px solid #00569e; padding-bottom: 10px;">📂 HISTÓRICO UNIFICADO</h2>

    <table style="width: 100%; border-collapse: collapse; background: #fff; margin-top: 20px;">
        <thead>
            <tr style="background: #f4f4f4; text-align: left; border-bottom: 2px solid #ddd;">
                <th style="padding: 15px;">DATA</th>
                <th style="padding: 15px;">CLIENTE</th>
                <th style="padding: 15px;">TOTAL</th>
                <th style="padding: 15px; text-align: center;">AÇÕES</th>
            </tr>
        </thead>
        <tbody>
            <?php while($v = $res->fetch_assoc()): ?>
            <tr style="border-bottom: 1px solid #eee;">
                <td style="padding: 12px;"><?php echo date("d/m/Y H:i", strtotime($v['data_emissao'])); ?></td>
                <td style="padding: 12px; font-weight: bold;"><?php echo $v['cliente_nome']; ?></td>
                <td style="padding: 12px; color: #28a745;">R$ <?php echo number_format($v['valor_total'], 2, ',', '.'); ?></td>
                <td style="padding: 12px; text-align: center;">
                    <a href="imprimir_cupom.php?id=<?php echo $v['id']; ?>" target="_blank" style="background: #28a745; color: #fff; padding: 6px 12px; text-decoration: none; border-radius: 3px;">👁️ ABRIR</a>
                    <a href="?del=<?php echo $v['id']; ?>" onclick="return confirm('EXCLUIR?')" style="background: #d32f2f; color: #fff; padding: 6px 12px; text-decoration: none; border-radius: 3px; margin-left: 5px;">🗑️</a>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>