<?php
// PWA Manifest Generator - Retorna APENAS JSON válido
// IMPORTANTE: Este arquivo NÃO deve iniciar sessão ou gerar qualquer output antes do JSON

// Remove TODOS os buffers
while (@ob_end_clean());

// Desabilita TODOS os outputs
error_reporting(0);
ini_set('display_errors', 0);
ini_set('log_errors', 0);
ini_set('output_buffering', 0);

// Previne início de sessão
ini_set('session.auto_start', 0);

// Inclui apenas pwa_config.php (não config.php completo para evitar sessão)
if (!file_exists(__DIR__ . '/pwa_config.php')) {
    http_response_code(404);
    header('Content-Type: application/json');
    die(json_encode(['error' => 'PWA config not found']));
}

// Lê pwa_config.php sem executar (para evitar includes que iniciam sessão)
// Mas precisamos das funções, então vamos incluí-lo de forma controlada
ob_start();
@require_once __DIR__ . '/pwa_config.php';
ob_clean();

if (!function_exists('pwa_module_installed') || !pwa_module_installed()) {
    http_response_code(404);
    header('Content-Type: application/json');
    die(json_encode(['error' => 'PWA module not installed']));
}

if (!file_exists(__DIR__ . '/pwa_functions.php')) {
    http_response_code(404);
    header('Content-Type: application/json');
    die(json_encode(['error' => 'PWA functions not found']));
}

// Inclui pwa_functions.php de forma controlada
ob_start();
@require_once __DIR__ . '/pwa_functions.php';
$output2 = ob_get_clean();

// Se houve output, descarta
if (!empty($output2)) {
    // Output capturado mas não exibido
}

// Headers (ANTES de qualquer output)
header('Content-Type: application/manifest+json; charset=utf-8');
header('Cache-Control: public, max-age=300');
header('Access-Control-Allow-Origin: *');
header('X-Content-Type-Options: nosniff');

// Gera manifest usando função isolada
try {
    // Usa função isolada que não depende de sessão
    if (function_exists('pwa_get_config_direct')) {
        $config = pwa_get_config_direct();
    } else {
        // Fallback: tenta função normal (pode iniciar sessão)
        $config = function_exists('pwa_get_config') ? pwa_get_config() : false;
    }
    
    if (!$config) {
        // Config padrão
        $config = [
            'app_name' => 'Plataforma',
            'short_name' => 'App',
            'description' => '',
            'icon_path' => '',
            'theme_color' => '#32e768',
            'background_color' => '#ffffff',
            'display_mode' => 'standalone',
            'start_url' => '/',
            'scope' => '/'
        ];
    }
    
    // Gera manifest manualmente (sem usar pwa_generate_manifest para evitar includes)
    $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || 
                $_SERVER['SERVER_PORT'] == 443 ||
                (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') ||
                (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && $_SERVER['HTTP_X_FORWARDED_SSL'] === 'on');
    $protocol = $is_https ? "https://" : "http://";
    $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
    
    // Constrói base_path corretamente, removendo caminhos de sistema de arquivos
    $script_path = $_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? '';
    $base_path = dirname($script_path);
    
    // Limpa caminho - remove qualquer referência a caminho de sistema de arquivos
    $base_path = str_replace('\\', '/', $base_path);
    $base_path = preg_replace('#^[A-Z]:/#i', '', $base_path); // Remove drive letter
    $base_path = preg_replace('#^.*htdocs#i', '', $base_path); // Remove htdocs
    
    if (!empty($base_path) && $base_path[0] !== '/') {
        $base_path = '/' . $base_path;
    }
    $base_path = preg_replace('#/+#', '/', $base_path);
    $base_path = rtrim($base_path, '/');
    
    if (empty($base_path) || $base_path === '/') {
        $base_path = '';
    }
    
    $base_url = $protocol . $host . $base_path;
    
    // Start URL
    $start_url = $config['start_url'] ?? '/';
    if (empty($start_url) || $start_url === '/') {
        $start_url = '/index.php';
    } elseif ($start_url[0] !== '/') {
        $start_url = '/' . ltrim($start_url, '/');
    }
    if ($start_url !== '/' && $start_url[strlen($start_url) - 1] === '/') {
        $start_url = rtrim($start_url, '/');
    }
    
    // Scope
    $scope = $config['scope'] ?? '/';
    if (empty($scope) || $scope === '/') {
        $scope = '/';
    } elseif ($scope[0] !== '/') {
        $scope = '/' . ltrim($scope, '/');
    }
    if ($scope !== '/' && $scope[strlen($scope) - 1] === '/') {
        $scope = rtrim($scope, '/');
    }
    
    // Manifest
    $manifest = [
        'name' => $config['app_name'] ?? 'Plataforma',
        'short_name' => $config['short_name'] ?? 'App',
        'description' => $config['description'] ?? '',
        'start_url' => $start_url,
        'scope' => $scope,
        'display' => $config['display_mode'] ?? 'standalone',
        'theme_color' => $config['theme_color'] ?? '#32e768',
        'background_color' => $config['background_color'] ?? '#ffffff',
        'orientation' => 'portrait-primary',
        'dir' => 'ltr',
        'lang' => 'pt-BR',
        'prefer_related_applications' => false,
        'icons' => []
    ];
    
    // Ícones
    if (!empty($config['icon_path'])) {
        $icon_path_clean = ltrim($config['icon_path'], '/');
        if (strpos($icon_path_clean, 'http://') === 0) {
            $icon_url = $is_https ? 'https://' . substr($icon_path_clean, 7) : $icon_path_clean;
        } elseif (strpos($icon_path_clean, 'https://') === 0) {
            $icon_url = $icon_path_clean;
        } else {
            $icon_url = $base_url . '/' . $icon_path_clean;
        }
        
        $manifest['icons'][] = [
            'src' => $icon_url,
            'sizes' => '192x192',
            'type' => 'image/png',
            'purpose' => 'any'
        ];
        $manifest['icons'][] = [
            'src' => $icon_url,
            'sizes' => '512x512',
            'type' => 'image/png',
            'purpose' => 'any maskable'
        ];
    }
    
    // Gera JSON
    $json = json_encode($manifest, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
    
    // Verifica se houve erro na codificação
    if ($json === false) {
        // JSON inválido - retorna JSON mínimo válido
        $json = json_encode([
            'name' => 'Plataforma',
            'short_name' => 'App',
            'display' => 'standalone',
            'start_url' => '/index.php',
            'scope' => '/'
        ], JSON_UNESCAPED_SLASHES);
    }
    
    // Remove BOM e espaços
    $json = trim($json);
    if (substr($json, 0, 3) === "\xEF\xBB\xBF") {
        $json = substr($json, 3);
    }
    
    // Garante que começa com {
    $start = strpos($json, '{');
    if ($start !== false && $start > 0) {
        $json = substr($json, $start);
    }
    
    // Valida JSON
    $decoded = @json_decode($json, true);
    if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
        // Se JSON inválido, retorna JSON mínimo válido
        $json = json_encode([
            'name' => 'Plataforma',
            'short_name' => 'App',
            'display' => 'standalone',
            'start_url' => '/index.php',
            'scope' => '/'
        ], JSON_UNESCAPED_SLASHES);
    }
    
    // Limpa TODOS os buffers finais
    while (@ob_end_clean());
    
    // Retorna APENAS o JSON, sem espaços ou caracteres antes
    echo $json;
    exit;
    
} catch (Throwable $e) {
    while (@ob_end_clean());
    http_response_code(500);
    header('Content-Type: application/json');
    die(json_encode(['error' => 'Error generating manifest']));
}
