<?php
/**
 * ============================================================================
 *  myDraft CMS — Dynamisches, tenant-aware Web-App-Manifest
 * ============================================================================
 *  Ersetzt die ehemals statische, hart auf isharestuff.com codierte
 *  manifest.json. Generiert das Manifest pro Tenant (HTTP_HOST) aus den
 *  Domain-Settings (webseiten_name, template_folder, Icons, Theme-Color).
 *
 *  Behebt gleichzeitig:
 *    - hartcodiertes start_url / isharestuff.com (Custom-Domain-Mandanten
 *      erhalten jetzt ihr eigenes Manifest)
 *    - kaputtes "&amp;" im start_url (JSON-konform via json_encode)
 *    - hartcodierte Icon-Pfade auf ein einziges Theme
 *
 *  Cache-Header: no-cache, damit Tenant-Änderungen sofort greifen.
 * ============================================================================
 */

declare(strict_types=1);

define('CORE_INSTALL_PATH', dirname(__FILE__) . '/');

require_once CORE_INSTALL_PATH . 'include/inc_env.php';
require_once CORE_INSTALL_PATH . 'include/inc_config-data.php';
require_once CORE_INSTALL_PATH . 'include/inc_basic-functions.php';

// --- Tenant-Auflösung ---
$domainInfo = getDomainInfo();
$template   = !empty($domainInfo['template_folder'])
    ? preg_replace('/[^a-zA-Z0-9_\-]/', '', $domainInfo['template_folder'])
    : (defined('MYDRAFT_BASE_TEMPLATE') ? MYDRAFT_BASE_TEMPLATE : 'mydraft-basis-isharestuff-com');

// Basis-URL (Schema + Host), robust ohne hartcodierten Fallback auf einen Mandanten.
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
    || (($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '') === 'https')
    ? 'https'
    : 'http';
$host   = $_SERVER['HTTP_HOST'] ?? 'localhost';
$origin = $scheme . '://' . $host;

// Anzeige-Name: Tenant-Name, Fallback generisch-neutral (nicht mehr isharestuff).
$name = !empty($domainInfo['webseiten_name'])
    ? trim((string)$domainInfo['webseiten_name'])
    : 'Nachrichtenportal';
$shortName = mb_strlen($name) > 12 ? mb_substr($name, 0, 12) : $name;

// Theme-/Background-Farbe: kanonische CORE_-Konstanten (einheitliche Quelle
// zusammen mit header.tpl theme-color meta). Über env/installed.php überschreibbar.
$themeColor      = defined('CORE_THEME_COLOR') ? CORE_THEME_COLOR : '#68d15a';
$backgroundColor = defined('CORE_BG_COLOR') ? CORE_BG_COLOR : '#000000';

// Icons: pro Template, mit Datei-Existenz-Prüfung. Fallback auf die iOS-Icons,
// die in jedem Theme liegen (siehe header.tpl apple-touch-icon).
$mediaBase = 'templates/' . $template . '/media/';
$iconCandidates = [
    ['file' => 'android-chrome-192x192.png', 'sizes' => '192x192'],
    ['file' => 'android-chrome-512x512.png', 'sizes' => '512x512'],
    ['file' => 'ios/192.png',                'sizes' => '192x192'],
    ['file' => 'ios/512.png',                'sizes' => '512x512'],
];
$icons = [];
foreach ($iconCandidates as $ic) {
    $absPath = CORE_INSTALL_PATH . $mediaBase . $ic['file'];
    if (is_file($absPath)) {
        $icons[] = [
            'src'   => '/' . $mediaBase . $ic['file'],
            'sizes' => $ic['sizes'],
            'type'  => 'image/png',
        ];
    }
}
// Deduplizieren (192/512 je einmal).
$seen = [];
$icons = array_values(array_filter($icons, function ($i) use (&$seen) {
    $k = $i['sizes'];
    if (isset($seen[$k])) {
        return false;
    }
    $seen[$k] = true;
    return true;
}));

$manifest = [
    'name'             => $name,
    'short_name'       => $shortName,
    'lang'             => 'de-DE',
    'start_url'        => $origin . '/?pk_campaign=PWA&pk_kwd=startup',
    'scope'            => $origin . '/',
    'display'          => 'standalone',
    'orientation'      => 'portrait-primary',
    'theme_color'      => $themeColor,
    'background_color' => $backgroundColor,
    'description'      => $name,
    'icons'            => $icons,
];

header('Content-Type: application/manifest+json; charset=utf-8');
header('Cache-Control: no-cache, no-store, must-revalidate');
echo json_encode($manifest, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
