diff --git a/export_html.php b/export_html.php index b0de847..264d5f4 100644 --- a/export_html.php +++ b/export_html.php @@ -1,5 +1,9 @@ prepare("SELECT * FROM installations WHERE id = :id"); $stmt->bindParam(':id', $installation_id, PDO::PARAM_INT); @@ -30,107 +33,126 @@ try { $images = $img_stmt->fetchAll(PDO::FETCH_ASSOC); } catch (Exception $e) { - die("Erro ao acessar o banco de dados: " . $e->getMessage()); + // Em caso de erro, envie um cabeçalho de erro e uma mensagem clara. + header("HTTP/1.1 500 Internal Server Error"); + die("Erro no servidor: Não foi possível conectar ao banco de dados. Detalhe: " . $e->getMessage()); } -// --- Início da Geração MHTML --- +// --- Funções Auxiliares --- +function xml_escape($string) { + return htmlspecialchars($string, ENT_XML1, 'UTF-8'); +} -$boundary = "----=" . md5(uniqid(time())); -$filename = "instalacao_" . $installation['id'] . "_" . str_replace(' ', '_', $installation['client_name']) . ".doc"; +// --- Preparar variáveis --- +$filename = "instalacao_" . $installation['id'] . ".doc"; -// Cabeçalhos principais para MHTML -header("Content-Type: multipart/related; boundary=\"$boundary\""); -header("Content-Disposition: attachment; filename=\"" . $filename . "\""); +// --- Geração do XML --- -// Parte 1: Conteúdo HTML -$html_content = << - - - - Relatório de Instalação - {htmlspecialchars($installation['client_name'])} - - - -
-

Relatório de Instalação

-

Detalhes do Cliente e Instalação

- - - - - - - -
ID da Instalação{htmlspecialchars($installation['id'])}
Cliente{htmlspecialchars($installation['client_name'])}
Endereço{htmlspecialchars($installation['address'])}
Técnico Responsável{htmlspecialchars($installation['technician_name'])}
Data{date("d/m/Y H:i", strtotime($installation['created_at']))}
Status{ucfirst(htmlspecialchars($installation['status']))}
+$xml_template = ' + + -

Dados Elétricos

- - - - -
Tensão (V){htmlspecialchars($installation['voltage'] ?? 'N/A')}
Fase-Neutro-Terra{htmlspecialchars($installation['phase_neutral_ground'] ?? 'N/A')}
Saída do Disjuntor{htmlspecialchars($installation['breaker_output'] ?? 'N/A')}
+ + %s + +
'; -

Observações

-

{nl2br(htmlspecialchars($installation['observations'] ?? 'Nenhuma observação.'))}

-HTML; +$xml_content = ''; -// Preparar a seção de imagens -$images_html = ''; -$image_parts = ''; +// Título +$xml_content .= 'Relatório de Instalação'; +// Função para criar linhas da tabela +function create_table_rows($data) { + $rows = ''; + foreach ($data as $label => $value) { + $label = xml_escape($label); + $value = xml_escape($value); + $rows .= << + {$label} + {$value} + +XML; + } + return $rows; +} + +// Tabela de Informações +$info_data = [ + "ID da Instalação" => $installation['id'], + "Cliente" => $installation['client_name'], + "Endereço" => $installation['address'], + "Técnico" => $installation['technician_name'], + "Data" => date("d/m/Y H:i", strtotime($installation['created_at'])), + "Status" => ucfirst($installation['status']) +]; +$xml_content .= '' . create_table_rows($info_data) . ''; + +// Tabela de Dados Elétricos +$electric_data = [ + "Tensão (V)" => $installation['voltage'] ?? 'N/A', + "Fase-Neutro-Terra" => $installation['phase_neutral_ground'] ?? 'N/A', + "Saída do Disjuntor" => $installation['breaker_output'] ?? 'N/A' +]; +$xml_content .= 'Dados Elétricos'; +$xml_content .= '' . create_table_rows($electric_data) . ''; + +// Observações +$observations = xml_escape($installation['observations'] ?? 'Nenhuma observação.'); +$xml_content .= 'Observações'; +$xml_content .= "{\$observations}"; + +// Imagens if (!empty($images)) { - $images_html = '

Imagens da Instalação

'; - - foreach ($images as $i => $image) { - $image_full_path = realpath(__DIR__ . '/' . $image['image_path']); - - if (file_exists($image_full_path)) { - $finfo = finfo_open(FILEINFO_MIME_TYPE); - $image_mime = finfo_file($finfo, $image_full_path); - finfo_close($finfo); + $xml_content .= ''; + $xml_content .= 'Imagens da Instalação'; + + foreach ($images as $image) { + $image_path = __DIR__ . '/' . $image['image_path']; + if (file_exists($image_path)) { + $image_data = base64_encode(file_get_contents($image_path)); + list($width_px, $height_px) = getimagesize($image_path); + + $width_pt = $width_px * 0.75; // Convert pixels to points + $height_pt = $height_px * 0.75; + + $max_width_pt = 450; // Largura máxima de aprox. 6 polegadas + if ($width_pt > $max_width_pt) { + $ratio = $max_width_pt / $width_pt; + $width_pt = $max_width_pt; + $height_pt = $height_pt * $ratio; + } - $image_data = base64_encode(file_get_contents($image_full_path)); - $cid = "image" . $i . "@" . md5($image['image_path']); + $shape_id = '_x0000_i' . substr(uniqid(), 5); + $image_rid = 'rId' . substr(uniqid(), 5); - // Adiciona a tag ao HTML - $images_html .= 'Imagem da Instalação ' . ($i+1) . '
'; - - // Cria a parte MIME para a imagem - $image_parts .= "--$boundary\r\n"; - $image_parts .= "Content-Type: $image_mime\r\n"; - $image_parts .= "Content-Transfer-Encoding: base64\r\n"; - $image_parts .= "Content-ID: <$cid>\r\n"; - $image_parts .= "Content-Location: " . basename($image['image_path']) . "\r\n\r\n"; - $image_parts .= chunk_split($image_data) . "\r\n"; + $xml_content .= ' + + + + ' . $image_data . ' + + + + + + + '; } } - $images_html .= '
'; } -// Finaliza o HTML -$html_content .= $images_html; -$html_content .= '
'; - -// Monta a saída final -echo "--$boundary\r\n"; -echo "Content-Type: text/html; charset=\"UTF-8\"\r\n"; -echo "Content-Transfer-Encoding: 7bit\r\n\r\n"; -echo $html_content . "\r\n"; - -// Adiciona as partes das imagens -echo $image_parts; - -// Fecha o boundary final -echo "--$boundary--\r\n"; - -?> +// --- Enviar para o navegador --- +header("Content-Type: application/vnd.ms-word; charset=UTF-8"); +header("Content-Disposition: attachment; filename=\"" . $filename . "\""); +echo sprintf($xml_template, $xml_content); +ob_end_flush(); +?> \ No newline at end of file