<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../vendor/autoload.php';

// Pega uma imagem real do banco
$pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
$row = $pdo->query("SELECT arquivo FROM produto_imagens LIMIT 1")->fetch(PDO::FETCH_ASSOC);
$imgAbs = UPLOADS_PATH . '/' . $row['arquivo'];

echo "<pre>";
echo "Imagem testada: $imgAbs\n";
echo "Existe: " . (file_exists($imgAbs) ? 'SIM' : 'NAO') . "\n";
echo "Mime: " . mime_content_type($imgAbs) . "\n";
echo "Tamanho: " . filesize($imgAbs) . " bytes\n";
echo "</pre>";

// Tenta gerar PDF com 3 estratégias diferentes
$opts = new \Dompdf\Options();
$opts->set('isRemoteEnabled', true);
$opts->set('isHtml5ParserEnabled', true);
$opts->set('chroot', dirname(__DIR__));  // libera o projeto inteiro
$opts->set('defaultFont', 'DejaVu Sans');

$dompdf = new \Dompdf\Dompdf($opts);

// Estratégia 1: caminho absoluto
$html1 = '<h2>Caminho absoluto</h2><img src="' . $imgAbs . '" style="width:200px">';

// Estratégia 2: file://
$html2 = '<h2>file://</h2><img src="file://' . $imgAbs . '" style="width:200px">';

// Estratégia 3: base64
$mime = mime_content_type($imgAbs);
$b64 = base64_encode(file_get_contents($imgAbs));
$html3 = '<h2>Base64</h2><img src="data:' . $mime . ';base64,' . $b64 . '" style="width:200px">';

$html = '<html><body>' . $html1 . '<hr>' . $html2 . '<hr>' . $html3 . '</body></html>';

$dompdf->loadHtml($html);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();

header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename=teste.pdf');
echo $dompdf->output();