<?php
require_once __DIR__ . '/lib/core.php';

$id = isset($_GET['id']) ? trim($_GET['id']) : '';
$key = isset($_GET['key']) ? trim($_GET['key']) : '';
$door = dc_find_public_door($id, $key);
$certificateSlug = isset($_GET['cert']) ? trim($_GET['cert']) : '';

if (!$door) {
    http_response_code(404);
    exit('Certificate not found.');
}

$path = dc_company_certificate_path_for_door($door, $certificateSlug);
if ($path === '') {
    http_response_code(404);
    exit('Company certificate not found for this standard.');
}

if (!empty($_GET['viewer'])) {
    $mime = function_exists('mime_content_type') ? mime_content_type($path) : '';
    $rawUrl = dc_company_certificate_url($door, false, $certificateSlug);
    ?><!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <style>
    html, body { height: 100%; margin: 0; background: #f5f7fa; }
    body { align-items: center; display: flex; justify-content: center; }
    img { display: block; max-height: 100vh; max-width: 100%; object-fit: contain; }
    iframe { border: 0; height: 100vh; width: 100%; }
  </style>
</head>
<body>
  <?php if (strpos($mime, 'image/') === 0): ?>
    <img src="<?php echo dc_h($rawUrl); ?>" alt="Applicable standard certificate">
  <?php else: ?>
    <iframe src="<?php echo dc_h($rawUrl); ?>" title="Applicable standard certificate"></iframe>
  <?php endif; ?>
</body>
</html><?php
    exit;
}

dc_send_company_certificate($door, !empty($_GET['download']), $certificateSlug);
