<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ordem de Produção #<?= htmlspecialchars($ordem['service_number']) ?></title>
    <style>
    @page {
        size: A4;
        margin: 0;
    }

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    body {
        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        font-size: 11pt;
        line-height: 1.4;
        color: #2c3e50;
        background: white;
        padding: 1.5cm;
    }

    .documento {
        border: 3px solid #1e3a8a;
        padding: 0;
        background: white;
    }

    /* Header */
    .header {
        background: linear-gradient(135deg, #1e3a8a 0%, #3b82f6 100%);
        color: white;
        padding: 1.5rem;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 2rem;
    }

    .header-left {
        display: flex;
        align-items: center;
        gap: 1rem;
        flex: 1;
    }

    .logo-empresa {
        max-width: 120px;
        max-height: 60px;
        background: white;
        padding: 0.5rem;
        border-radius: 4px;
        object-fit: contain;
    }

    .header-right {
        text-align: right;
    }

    .header h1 {
        font-size: 24pt;
        font-weight: bold;
        margin-bottom: 0.5rem;
        text-transform: uppercase;
        letter-spacing: 2px;
    }

    .header .numero {
        font-size: 18pt;
        font-weight: 600;
        opacity: 0.95;
    }

    .header .data {
        font-size: 10pt;
        opacity: 0.9;
        margin-top: 0.5rem;
    }

    /* Informações principais */
    .info-principal {
        padding: 1.5rem;
        background: #f8f9fa;
        border-bottom: 2px solid #dee2e6;
    }

    .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 0;
        padding: 0.75rem;
        background: white;
        border-radius: 4px;
    }

    .info-label {
        font-weight: 600;
        color: #495057;
        margin-right: 0.75rem;
    }

    .info-value {
        color: #212529;
        font-size: 11pt;
    }

    /* Seção de itens */
    .section-title {
        background: #1e3a8a;
        color: white;
        padding: 0.75rem 1.5rem;
        font-size: 12pt;
        font-weight: bold;
        text-transform: uppercase;
        letter-spacing: 1px;
    }

    .itens {
        width: 100%;
        border-collapse: collapse;
        margin: 0;
    }

    .itens thead {
        background: #e9ecef;
    }

    .itens th {
        padding: 0.75rem;
        text-align: left;
        font-weight: 600;
        font-size: 9pt;
        border-bottom: 2px solid #dee2e6;
        color: #495057;
    }

    .itens td {
        padding: 0.75rem;
        border-bottom: 1px solid #e9ecef;
        font-size: 10pt;
    }

    .itens tbody tr:hover {
        background: #f8f9fa;
    }

    .item-numero {
        display: inline-block;
        width: 30px;
        height: 30px;
        line-height: 30px;
        background: #1e3a8a;
        color: white;
        border-radius: 50%;
        font-weight: bold;
        text-align: center;
    }

    .item-dimensoes {
        font-size: 9pt;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    /* Grid de imagens */
    .imagens-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 1rem;
        padding: 1.5rem;
        background: #f8f9fa;
    }

    .imagem-card {
        background: white;
        border: 2px solid #dee2e6;
        border-radius: 8px;
        padding: 1rem;
        text-align: center;
        page-break-inside: avoid;
    }

    .imagem-card img {
        max-width: 100%;
        max-height: 150px;
        width: auto;
        height: auto;
        border-radius: 4px;
        margin-bottom: 0.5rem;
        object-fit: contain;
        display: block;
        margin-left: auto;
        margin-right: auto;
    }

    .imagem-card .codigo {
        font-weight: bold;
        color: #1e3a8a;
        font-size: 10pt;
        margin-top: 0.5rem;
    }

    .imagem-card .nome {
        font-size: 9pt;
        color: #6c757d;
        margin-top: 0.25rem;
        word-break: break-word;
    }

    /* Observações */
    .observacoes {
        padding: 1.5rem;
        background: #fff3cd;
        border-top: 2px solid #ffc107;
        margin-top: 1rem;
    }

    .observacoes-title {
        font-weight: bold;
        color: #856404;
        margin-bottom: 0.75rem;
        font-size: 11pt;
    }

    .observacoes-text {
        color: #856404;
        font-size: 10pt;
        line-height: 1.6;
    }

    /* Botão de impressão */
    .no-print {
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1000;
    }

    .no-print button {
        padding: 0.75rem 1.5rem;
        background: #1e3a8a;
        color: white;
        border: none;
        border-radius: 6px;
        font-size: 12pt;
        cursor: pointer;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
    }

    .no-print button:hover {
        background: #1e40af;
    }

    @media print {
        .no-print {
            display: none;
        }

        body {
            padding: 0;
        }

        .documento {
            border: none;
        }

        .itens tbody tr {
            page-break-inside: avoid;
        }

        .imagem-card {
            page-break-inside: avoid;
        }
    }
    </style>
</head>

<body>
    <div class="no-print">
        <button onclick="window.print()">
            🖨 Imprimir
        </button>
    </div>

    <div class="documento">
        <!-- Header -->
        <div class="header">
            <div class="header-left">
                <?php
                // Buscar logo da empresa (tenant)
                $logoPath = 'storage/uploads/logo.png';
                if (!empty($empresa['logo'])) {
                    $logoPath = $empresa['logo'];
                }
                // Verificar se existe logo por CNPJ (prioriza campo 'cnpj')
                $cnpjLimpo = preg_replace('/\D/', '', $empresa['cnpj'] ?? ($empresa['document'] ?? ''));
                if ($cnpjLimpo && file_exists(ROOT_PATH . '/storage/uploads/logos/' . $cnpjLimpo . '.jpg')) {
                    $logoPath = 'storage/uploads/logos/' . $cnpjLimpo . '.jpg';
                }
                ?>
                <?php if (file_exists(ROOT_PATH . '/' . $logoPath)): ?>
                <img src="<?= asset($logoPath) ?>" alt="Logo" class="logo-empresa">
                <?php endif; ?>
            </div>
            <div class="header-right">
                <h1>Ordem de Produção</h1>
                <div class="numero">#<?= htmlspecialchars($ordem['service_number']) ?></div>
                <div class="data">
                    Data: <?= date('d/m/Y H:i', strtotime($ordem['created_at'] ?? $ordem['service_date'])) ?>
                </div>
            </div>
        </div>

        <!-- Informações principais -->
        <div class="info-principal">
            <?php if (!empty($cliente)): ?>
            <div class="info-row">
                <span class="info-label">Cliente:</span>
                <span class="info-value"><?= htmlspecialchars($cliente['name'] ?? $cliente['trade_name'] ?? 'N/A') ?></span>
            </div>
            <?php endif; ?>
            <?php if (!empty($ordem['delivery_date']) || !empty($venda['delivery_date'])): ?>
            <div class="info-row">
                <span class="info-label">Data de Entrega:</span>
                <span class="info-value">
                    <?= date('d/m/Y', strtotime($ordem['delivery_date'] ?? $venda['delivery_date'] ?? '')) ?>
                </span>
            </div>
            <?php endif; ?>
        </div>

        <!-- Itens -->
        <div class="section-title">📋 Itens para Produção</div>
        <table class="itens">
            <thead>
                <tr>
                    <th width="50">#</th>
                    <th width="100">Código</th>
                    <th>Produto</th>
                    <th width="80" class="text-center">Altura</th>
                    <th width="80" class="text-center">Largura</th>
                        <th width="80" class="text-center">M²</th>
                        <th width="80" class="text-center">Qtd</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($itens as $index => $item): ?>
                <?php
                // Buscar altura e largura (podem estar NULL se não foram salvas)
                $altura = isset($item['altura']) && $item['altura'] !== null ? floatval($item['altura']) : 0;
                $largura = isset($item['largura']) && $item['largura'] !== null ? floatval($item['largura']) : 0;
                $m2 = floatval($item['quantity'] ?? ($altura * $largura));
                $qtd = intval($item['quantity2'] ?? $item['quantity'] ?? 1);
                $temObservacao = !empty($item['notes']);
                ?>
                <tr>
                    <td class="text-center">
                        <span class="item-numero"><?= $index + 1 ?></span>
                    </td>
                    <td><strong><?= htmlspecialchars($item['product_sku'] ?? '-') ?></strong></td>
                    <td>
                        <div><?= htmlspecialchars($item['product_name']) ?></div>
                    </td>
                    <td class="text-center"><?= $altura > 0 ? number_format($altura, 2, ',', '.') . ' m' : '-' ?></td>
                    <td class="text-center"><?= $largura > 0 ? number_format($largura, 2, ',', '.') . ' m' : '-' ?></td>
                    <td class="text-center"><strong><?= number_format($m2, 3, ',', '.') ?> m²</strong></td>
                    <td class="text-center"><strong><?= $qtd ?></strong></td>
                    <td></td>
                </tr>
                <?php if ($temObservacao): ?>
                <tr style="background-color: #f8f9fa;">
                    <td colspan="8" style="padding: 0.75rem 1rem; border-top: none; border-bottom: 2px solid #dee2e6;">
                        <div style="display: flex; align-items: flex-start; gap: 0.5rem;">
                            <span style="font-weight: 600; color: #495057; min-width: 80px;">Observação:</span>
                            <span style="color: #212529; flex: 1;"><?= nl2br(htmlspecialchars($item['notes'])) ?></span>
                        </div>
                    </td>
                </tr>
                <?php endif; ?>
                <?php endforeach; ?>
            </tbody>
        </table>

        <!-- Imagens dos Produtos -->
        <?php
        $itensComImagens = array_filter($itens, function($item) {
            return !empty($item['product_image']);
        });
        ?>
        <?php if (!empty($itensComImagens)): ?>
        <div class="section-title">📷 Referências Visuais</div>
        <div class="imagens-grid">
            <?php foreach ($itensComImagens as $item): ?>
            <div class="imagem-card">
                <?php
                $imagePath = $item['product_image'];
                $imageUrl = null;
                if (!empty($imagePath)) {
                    if (strpos($imagePath, 'http') !== 0) {
                        // Verificar se o arquivo existe
                        $fullPath = ROOT_PATH . '/' . ltrim($imagePath, '/');
                        if (file_exists($fullPath)) {
                            $imageUrl = asset($imagePath);
                        } else {
                            // Tentar caminhos alternativos
                            $altPaths = [
                                'storage/uploads/products/' . basename($imagePath),
                                'storage/uploads/' . basename($imagePath),
                                $imagePath
                            ];
                            foreach ($altPaths as $altPath) {
                                if (file_exists(ROOT_PATH . '/' . $altPath)) {
                                    $imageUrl = asset($altPath);
                                    break;
                                }
                            }
                        }
                    } else {
                        $imageUrl = $imagePath;
                    }
                }
                ?>
                <?php if (!empty($imageUrl)): ?>
                <div style="width: 100%; height: 150px; overflow: hidden; border-radius: 4px; margin-bottom: 0.5rem; background: #f8f9fa; display: flex; align-items: center; justify-content: center;">
                    <img src="<?= htmlspecialchars($imageUrl) ?>" alt="<?= htmlspecialchars($item['product_name']) ?>" style="max-width: 100%; max-height: 100%; object-fit: contain;">
                </div>
                <?php endif; ?>
                <div class="codigo"><?= htmlspecialchars($item['product_sku'] ?? '-') ?></div>
                <div class="nome"><?= htmlspecialchars(mb_substr($item['product_name'], 0, 30)) ?><?= mb_strlen($item['product_name']) > 30 ? '...' : '' ?></div>
            </div>
            <?php endforeach; ?>
        </div>
        <?php endif; ?>

        <!-- Observações -->
        <?php if (!empty($ordem['notes'])): ?>
        <div class="observacoes">
            <div class="observacoes-title">⚠️ Observações Importantes</div>
            <div class="observacoes-text">
                <?= nl2br(htmlspecialchars($ordem['notes'])) ?>
            </div>
        </div>
        <?php endif; ?>
    </div>

    <script>
    // Auto-imprimir ao carregar (com pequeno delay para renderização)
    window.addEventListener('load', function() {
        setTimeout(function() {
            window.print();
        }, 500);
    });
    </script>
</body>

</html>

