<?php
require_once __DIR__ . '/src/auth.php';
require_once __DIR__ . '/src/db.php';

// Iniciar sessão
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$path = $_GET['path'] ?? '';
$token = $_GET['token'] ?? '';
$contract_id = $_GET['contract_id'] ?? '';
$uid = $_GET['uid'] ?? '';
$utoken = $_GET['utoken'] ?? '';

if (empty($path)) {
    die("Caminho do arquivo não especificado.");
}

$pdo = get_db_connection();

// Buscar assinaturas para este contrato
if (!empty($contract_id)) {
    $stmt = $pdo->prepare("SELECT * FROM contract_signatures WHERE contract_id = ? AND is_signed = 1 ORDER BY signed_at DESC");
    $stmt->execute([$contract_id]);
    $signatures = $stmt->fetchAll();
} else {
    $signatures = [];
}

// Se o usuário não estiver logado, verificar o token
if (!isset($_SESSION['user_id']) && !empty($token)) {
    $stmt_token = $pdo->prepare("SELECT contract_id FROM contract_signatures WHERE token = ? AND is_signed = 0");
    $stmt_token->execute([$token]);
    if (!$stmt_token->fetch()) {
        die("Acesso negado.");
    }
} else if (!isset($_SESSION['user_id'])) {
    require_login();
}

$pdf_url = "serve_file.php?path=" . urlencode($path) 
         . (!empty($token) ? "&token=" . urlencode($token) : "")
         . (!empty($uid) ? "&uid=" . urlencode($uid) : "")
         . (!empty($utoken) ? "&utoken=" . urlencode($utoken) : "");
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <title>Visualizar Contrato com Assinatura</title>
    <script src="https://unpkg.com/pdf-lib@1.17.1/dist/pdf-lib.min.js"></script>
    <style>
        body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; font-family: sans-serif; }
        #viewer { width: 100%; height: 100%; border: none; }
        #loading { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: white; display: flex; align-items: center; justify-content: center; z-index: 1000; flex-direction: column; }
        .spinner { border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 40px; height: 40px; animation: spin 2s linear infinite; margin-bottom: 10px; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
    </style>
</head>
<body>
    <div id="loading">
        <div class="spinner"></div>
        <div>Aplicando selo de assinatura digital...</div>
    </div>
    <iframe id="viewer"></iframe>

    <script>
        const { PDFDocument, rgb, StandardFonts } = PDFLib;

        async function applySignature() {
            try {
                const url = '<?= $pdf_url ?>';
                const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer());

                const pdfDoc = await PDFDocument.load(existingPdfBytes);
                const helveticaFont = await pdfDoc.embedFont(StandardFonts.HelveticaBold);
                const pages = pdfDoc.getPages();

                const signatures = <?= json_encode($signatures) ?>;
                
                if (signatures.length > 0) {
                    pages.forEach((page) => {
                        const { width, height } = page.getSize();
                        
                        // Adicionar tarja no topo de cada página
                        page.drawRectangle({
                            x: 0,
                            y: height - 25,
                            width: width,
                            height: 25,
                            color: rgb(0.95, 0.95, 0.95),
                        });

                        const sig = signatures[0]; // Pegar a assinatura mais recente
                        const date = new Date(sig.signed_at).toLocaleDateString('pt-BR');
                        const time = new Date(sig.signed_at).toLocaleTimeString('pt-BR');
                        const text = `ASSINADO ELETRONICAMENTE POR: ${sig.signer_name.toUpperCase()} EM ${date} AS ${time}`;
                        
                        page.drawText(text, {
                            x: 20,
                            y: height - 17,
                            size: 8,
                            font: helveticaFont,
                            color: rgb(0, 0.29, 0.6),
                        });

                        page.drawText('AUTENTICIDADE GARANTIDA PELO SISTEMA DE GESTAO DE CONTRATOS', {
                            x: width - 320,
                            y: height - 17,
                            size: 7,
                            font: helveticaFont,
                            color: rgb(0.5, 0.5, 0.5),
                        });
                    });
                }

                const pdfBytes = await pdfDoc.save();
                const blob = new Blob([pdfBytes], { type: 'application/pdf' });
                const blobUrl = URL.createObjectURL(blob);
                
                document.getElementById('viewer').src = blobUrl;
                document.getElementById('loading').style.display = 'none';
            } catch (error) {
                console.error('Erro ao processar PDF:', error);
                // Se der erro, mostra o original
                document.getElementById('viewer').src = '<?= $pdf_url ?>';
                document.getElementById('loading').style.display = 'none';
            }
        }

        applySignature();
    </script>
</body>
</html>
