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

// 1. PEGA O ID DA VENDA PELA URL
$id_venda = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id_venda === 0) {
    die("ERRO: ID DA VENDA INVÁLIDO.");
}

// 2. BUSCA OS DADOS NO BANCO
$info = $conn->query("SELECT * FROM configuracoes_loja WHERE id=1")->fetch_assoc();
$venda = $conn->query("SELECT * FROM comprovantes_pagamento WHERE id = '$id_venda'")->fetch_assoc();
$res_itens = $conn->query("SELECT * FROM itens_venda WHERE venda_id = '$id_venda'");

if (!$venda) {
    die("ERRO: VENDA NÃO ENCONTRADA.");
}

$total_geral = 0;
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>IMPRESSÃO DE CUPOM #<?php echo $id_venda; ?></title>
    <style>
        /* ESTILOS REPLICADOS DO cupom.php */
        body { margin: 0; padding: 20px; font-family: 'Segoe UI', sans-serif; text-transform: uppercase; background: #fff; }
        .cupom-wrapper { max-width: 900px; margin: auto; padding: 0; }
        
        .cupom-header { border: 2px solid #333; padding: 15px; margin-bottom: 20px; text-align: center; }
        .cupom-header h1 { margin: 5px 0; font-size: 22px; color: #000; }
        .cupom-header p { margin: 2px 0; font-size: 11px; font-weight: bold; }

        .secao-titulo { background: #333; color: #fff; padding: 8px; font-size: 12px; font-weight: bold; margin-top: 20px; }

        .cliente-view { display: block; border: 1px solid #ccc; padding: 10px; margin-bottom: 10px; font-size: 12px; font-weight: bold; }

        .table-itens { width: 100%; border-collapse: collapse; margin-top: 10px; }
        .table-itens th { background: #eee; padding: 10px; font-size: 11px; border: 1px solid #ccc; text-align: left; }
        .table-itens td { padding: 8px; border: 1px solid #ddd; font-size: 12px; font-weight: bold; }

        .total-row { background: #333; color: #fff; font-weight: bold; }

        .no-print { 
            background: #00569e; color: white; border: none; padding: 15px; 
            width: 100%; font-size: 14px; font-weight: bold; cursor: pointer; 
            margin-bottom: 20px; text-transform: uppercase;
        }

        @media print {
            .no-print { display: none !important; }
            body { padding: 0; }
            .cupom-wrapper { width: 100%; }
            @page { margin: 10mm; }
        }
    </style>
</head>
<body onload="window.print()">

<div class="cupom-wrapper">
    <button class="no-print" onclick="window.print()">🖨️ REIMPRIMIR CUPOM</button>

    <div class="cupom-header">
        <?php if(!empty($info['logo_path'])): ?>
            <img src="<?php echo $info['logo_path']; ?>" style="max-height: 60px; margin-bottom: 10px;">
        <?php endif; ?>
        <h1><?php echo $info['nome_loja']; ?></h1>
        <p><?php echo $info['endereco']; ?></p>
        <p>CNPJ: <?php echo $info['cnpj']; ?> | TEL: <?php echo $info['telefone']; ?></p>
    </div>

    <div class="secao-titulo">👤 DADOS DO CLIENTE / VENDA</div>
    <div class="cliente-view">
        <strong>CLIENTE:</strong> <?php echo $venda['cliente_nome']; ?><br>
        <strong>DATA/HORA:</strong> <?php echo date('d/m/Y H:i', strtotime($venda['data_emissao'])); ?><br>
        <strong>Nº DO PEDIDO:</strong> #<?php echo str_pad($id_venda, 6, "0", STR_PAD_LEFT); ?>
    </div>

    <div class="secao-titulo">📝 ITENS DO PEDIDO</div>
    <table class="table-itens">
        <thead>
            <tr>
                <th>DESCRIÇÃO</th>
                <th style="text-align: center; width: 80px;">QTD</th>
                <th style="text-align: right; width: 100px;">UNIT.</th>
                <th style="text-align: right; width: 100px;">TOTAL</th>
            </tr>
        </thead>
        <tbody>
            <?php while($item = $res_itens->fetch_assoc()): 
                $subtotal = $item['quantidade'] * $item['preco_unitario'];
                $total_geral += $subtotal;
            ?>
            <tr>
                <td><?php echo $item['produto_nome']; ?></td>
                <td style="text-align: center;"><?php echo number_format($item['quantidade'], 0); ?></td>
                <td style="text-align: right;">R$ <?php echo number_format($item['preco_unitario'], 2, ',', '.'); ?></td>
                <td style="text-align: right;">R$ <?php echo number_format($subtotal, 2, ',', '.'); ?></td>
            </tr>
            <?php endwhile; ?>
        </tbody>
        <tfoot>
            <tr class="total-row">
                <td colspan="3" style="text-align: right; padding: 10px;">TOTAL GERAL:</td>
                <td style="text-align: right; padding: 10px;">R$ <?php echo number_format($total_geral, 2, ',', '.'); ?></td>
            </tr>
        </tfoot>
    </table>

    <div style="margin-top: 20px; text-align: center; font-size: 10px; border-top: 1px dashed #333; padding-top: 10px;">
        <?php echo $info['mensagem_rodape'] ?? 'OBRIGADO PELA PREFERÊNCIA!'; ?>
    </div>
</div>

</body>
</html>