<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../includes/functions.php';
startSecureSession();
requireAdmin();

$id = (int)($_GET['id'] ?? 0);
$p = Database::fetchOne("SELECT p.*, c.name as cat_name FROM products p LEFT JOIN categories c ON p.category_id = c.id WHERE p.id = ?", [$id]);

if (!$p) die('Product not found.');

$allSettings = Database::fetchAll("SELECT setting_key, setting_value FROM settings WHERE setting_group IN ('general', 'billing')");
$s = [];
foreach ($allSettings as $row) $s[$row['setting_key']] = $row['setting_value'];

$companyName = $s['company_name'] ?? 'RIG N DIG';
$logo = $s['logo'] ?? '';
$specs = json_decode($p['specifications'], true);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Material Specification Certificate — <?= e($p['name']) ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { background: #f3f4f6; padding: 10px; font-family: 'Inter', sans-serif; }
        .cert-border {
            width: 790px; height: 1080px; margin: 0 auto;
            background: #fff; padding: 2px; position: relative;
            box-shadow: 0 0 50px rgba(0,0,0,0.1); border: 1px solid #ddd;
            overflow: hidden;
        }
        .cert-inner {
            height: 100%; border: 10px double #111827;
            padding: 30px; position: relative;
            display: flex; flex-direction: column;
        }
        .watermark {
            position: absolute; top: 52%; left: 50%;
            transform: translate(-50%, -50%);
            width: 400px; opacity: 0.04; pointer-events: none;
            z-index: 0; filter: grayscale(1);
        }
        .content-layer { position: relative; z-index: 10; height: 100%; display: flex; flex-direction: column; }
        .govt-seal { width: 70px; height: 70px; filter: grayscale(1); opacity: 0.6; }
        @media print {
            body { background: none; padding: 0; }
            .cert-border { box-shadow: none; margin: 0; border: none; height: 100%; }
            .print-btn { display: none; }
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
function downloadPDF() {
    const element = document.querySelector('.cert-border');
    const originalMargin = element.style.margin;
    element.style.margin = '0';

    const opt = {
        margin:       0,
        filename:     'Certificate_<?= e($p['name']) ?>.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { 
            scale: 2, 
            useCORS: true, 
            scrollY: 0, 
            height: 1122,
            windowHeight: 1122
        },
        jsPDF:        { unit: 'px', format: [793, 1122], orientation: 'portrait' },
        pagebreak:    { mode: 'avoid-all' }
    };
    
    html2pdf().set(opt).from(element).save().then(() => {
        element.style.margin = originalMargin;
    });
}
</script>
<style>
    /* Strict clamping for single page export */
    .cert-border { height: 1122px !important; overflow: hidden !important; border:none !important; }
</style>
</head>
<body class="bg-gray-100" style="margin:0; padding:20px;">

<div class="fixed top-5 left-5 print-btn flex gap-2">
    <button onclick="downloadPDF()" class="bg-orange-600 text-white px-6 py-2 rounded-lg font-bold shadow-xl hover:bg-orange-700 transition-all flex items-center gap-2">
        ⬇️ DOWNLOAD PDF
    </button>
    <button onclick="window.print()" class="bg-[#111827] text-white px-6 py-2 rounded-lg font-bold shadow-xl hover:bg-[#ff6b00] transition-all flex items-center gap-2">
        🖨️ PRINT
    </button>
</div>

<div class="cert-border" style="margin: 0 auto; background: #fff;">
    <div class="cert-inner">
        <?php if ($logo): ?>
            <img src="/uploads/<?= e($logo) ?>" class="watermark">
        <?php else: ?>
            <div class="watermark" style="font-size: 80px; font-weight: 800; color: rgba(0,0,0,0.03); transform: translate(-50%, -50%) rotate(-45deg); text-align:center;"><?= strtoupper(e($companyName)) ?></div>
        <?php endif; ?>

        <div class="content-layer text-center">
            <!-- Header (Ultra Compact) -->
            <div class="flex justify-between items-center mb-4 border-b pb-3">
                <div class="flex items-center gap-3">
                    <?php if ($logo): ?>
                        <img src="/uploads/<?= e($logo) ?>" class="h-10">
                    <?php endif; ?>
                    <div>
                        <h1 class="text-lg font-black tracking-tighter text-[#111827]"><?= e($companyName) ?></h1>
                        <p class="text-[8px] text-gray-400 font-bold uppercase tracking-widest leading-none">Quality Assurance Division</p>
                    </div>
                </div>
                <div class="text-right">
                    <div class="text-[8px] font-bold text-gray-400 uppercase">Certificate No.</div>
                    <div class="text-sm font-bold text-[#111827] tracking-tighter">RD-SPEC-<?= str_pad($p['id'], 5, '0', STR_PAD_LEFT) ?></div>
                    <div class="text-[8px] text-gray-500 mt-0.5"><?= date('d F Y') ?></div>
                </div>
            </div>

            <div class="mb-4">
                <h2 class="text-xl font-bold text-[#111827] uppercase tracking-tighter">Material Analysis & Compliance Certificate</h2>
                <div class="mt-1 text-[9px] text-gray-500 font-bold uppercase tracking-widest flex justify-center gap-3">
                    <span>Product: <span class="text-[#111827]"><?= e($p['name']) ?></span></span>
                    <span>SKU: <span class="text-[#111827] font-mono"><?= e($p['sku'] ?: 'N/A') ?></span></span>
                    <span>Standard: <span class="bg-[#111827] text-white px-1 rounded-sm"><?= e($p['standards'] ?: 'API/ASME') ?></span></span>
                </div>
            </div>

            <!-- Focus: Technical Data Matrix (Slimmed Rows) -->
            <div class="text-left mb-4 flex-grow">
                <h3 class="text-[9px] font-bold text-orange-600 uppercase tracking-widest border-b border-gray-100 pb-1 mb-2 italic">Verified Technical Matrix</h3>
                <?php if (is_array($specs) && !empty($specs)): ?>
                    <table class="w-full text-[10.5px] border border-gray-100">
                        <thead>
                            <tr class="bg-[#111827] text-white uppercase text-[8px]">
                                <th class="px-3 py-1 text-left w-1/2">Technical Property</th>
                                <th class="px-3 py-1 text-left">Verified Metric</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100">
                            <?php foreach ($specs as $key => $val): ?>
                            <tr>
                                <td class="px-3 py-1.5 font-semibold text-gray-600"><?= e($key) ?></td>
                                <td class="px-3 py-1.5 font-bold text-[#111827]"><?= e($val) ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php else: ?>
                    <div class="bg-gray-50 border border-dashed border-gray-300 p-4 text-center">
                        <p class="text-[10px] text-gray-400 italic">No technical matrix provided for this specific configuration.</p>
                    </div>
                <?php endif; ?>
                
                <p class="text-[9px] text-gray-400 mt-3 leading-snug">
                    Veritas Statement: Material properties and technical dimensions of the listed asset comply with industrial safety benchmarks. 
                    Engineering verification conducted via NDT and visual inspection protocols.
                </p>
            </div>

            <!-- Signatures Section (Ultra Compact) -->
            <div class="grid grid-cols-3 gap-6 pt-3 items-end border-t border-gray-100">
                <div class="text-center">
                    <div class="h-6 mb-1 border-b border-dashed border-gray-200"></div>
                    <div class="text-[8px] font-bold text-[#111827] uppercase">Q.A Supervisor</div>
                </div>
                <div class="flex flex-col items-center">
                    <img src="https://upload.wikimedia.org/wikipedia/commons/e/ef/State_emblem_of_Pakistan.svg" class="govt-seal mb-1">
                    <div class="text-[7px] font-bold text-gray-400 uppercase text-center leading-tight">
                        Government of Pakistan<br>Certification Authority
                    </div>
                </div>
                <div class="text-center">
                    <div class="h-6 mb-1 border-b border-dashed border-gray-200"></div>
                    <div class="text-[8px] font-bold text-[#111827] uppercase">Authority Seal</div>
                </div>
            </div>

            <div class="mt-6 text-center bg-gray-50 py-1 rounded">
                <p class="text-[8px] text-gray-400 font-bold uppercase tracking-[0.4em] leading-none">
                    SECURE ID: <?= strtoupper(substr(md5($p['id'] . 'CERT'), 0, 10)) ?> — CONFORMITY VALIDATED / NO CHANGES ALLOWED
                </p>
            </div>
        </div>
    </div>
</div>

</body>
</html>
