<?php
// export_html.php

// 1. Validar e obter o ID
if (!isset($_GET['id']) || !filter_var($_GET['id'], FILTER_VALIDATE_INT)) {
    die("ID da instalação inválido.");
}
$installation_id = $_GET['id'];

// 2. Conectar ao banco de dados
require_once __DIR__ . '/db/config.php';

try {
    $pdo = db();

    // 3. Buscar dados da instalação
    $stmt = $pdo->prepare("SELECT * FROM installations WHERE id = :id");
    $stmt->bindParam(':id', $installation_id, PDO::PARAM_INT);
    $stmt->execute();
    $installation = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$installation) {
        die("Instalação não encontrada.");
    }

    // 4. Buscar imagens da instalação
    $img_stmt = $pdo->prepare("SELECT image_path FROM installation_images WHERE installation_id = :id ORDER BY id ASC");
    $img_stmt->bindParam(':id', $installation_id, PDO::PARAM_INT);
    $img_stmt->execute();
    $images = $img_stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    die("Erro ao acessar o banco de dados: " . $e->getMessage());
}

// --- Início da Geração MHTML ---

$boundary = "----=" . md5(uniqid(time()));
$filename = "instalacao_" . $installation['id'] . "_" . str_replace(' ', '_', $installation['client_name']) . ".doc";

// Cabeçalhos principais para MHTML
header("Content-Type: multipart/related; boundary=\"$boundary\"");
header("Content-Disposition: attachment; filename=\"" . $filename . "\"");

// Parte 1: Conteúdo HTML
$html_content = <<<HTML
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Relatório de Instalação - {htmlspecialchars($installation['client_name'])}</title>
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { width: 90%; margin: 0 auto; }
        h1 { color: #0056b3; border-bottom: 2px solid #f0f0f0; padding-bottom: 10px; }
        .details-table { width: 100%; border-collapse: collapse; margin-bottom: 20px; }
        .details-table td { padding: 8px; border: 1px solid #ddd; }
        .details-table td:first-child { font-weight: bold; background-color: #f9f9f9; width: 25%; }
        .images-section img { max-width: 400px; margin: 10px; border: 1px solid #ccc; padding: 5px; }
        .section-title { font-size: 1.5em; color: #0056b3; margin-top: 20px; margin-bottom: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <h1>Relatório de Instalação</h1>
        <h2 class="section-title">Detalhes do Cliente e Instalação</h2>
        <table class="details-table">
            <tr><td>ID da Instalação</td><td>{htmlspecialchars($installation['id'])}</td></tr>
            <tr><td>Cliente</td><td>{htmlspecialchars($installation['client_name'])}</td></tr>
            <tr><td>Endereço</td><td>{htmlspecialchars($installation['address'])}</td></tr>
            <tr><td>Técnico Responsável</td><td>{htmlspecialchars($installation['technician_name'])}</td></tr>
            <tr><td>Data</td><td>{date("d/m/Y H:i", strtotime($installation['created_at']))}</td></tr>
            <tr><td>Status</td><td>{ucfirst(htmlspecialchars($installation['status']))}</td></tr>
        </table>

        <h2 class="section-title">Dados Elétricos</h2>
        <table class="details-table">
            <tr><td>Tensão (V)</td><td>{htmlspecialchars($installation['voltage'] ?? 'N/A')}</td></tr>
            <tr><td>Fase-Neutro-Terra</td><td>{htmlspecialchars($installation['phase_neutral_ground'] ?? 'N/A')}</td></tr>
            <tr><td>Saída do Disjuntor</td><td>{htmlspecialchars($installation['breaker_output'] ?? 'N/A')}</td></tr>
        </table>

        <h2 class="section-title">Observações</h2>
        <p>{nl2br(htmlspecialchars($installation['observations'] ?? 'Nenhuma observação.'))}</p>
HTML;

// Preparar a seção de imagens
$images_html = '';
$image_parts = '';

if (!empty($images)) {
    $images_html = '<h2 class="section-title">Imagens da Instalação</h2><div class="images-section" style="page-break-before: always;">';
    
    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);
            
            $image_data = base64_encode(file_get_contents($image_full_path));
            $cid = "image" . $i . "@" . md5($image['image_path']);

            // Adiciona a tag <img> ao HTML
            $images_html .= '<img src="cid:' . $cid . '" alt="Imagem da Instalação ' . ($i+1) . '"><br>';

            // 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";
        }
    }
    $images_html .= '</div>';
}

// Finaliza o HTML
$html_content .= $images_html;
$html_content .= '</div></body></html>';

// 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";

?>
