<?php
// manifest.php
header('Content-Type: application/json');
    require_once(__DIR__ . '/db/db_connection.php');

if (session_status() === PHP_SESSION_NONE) session_start();
$user_id = $_SESSION['user_id'] ?? 1;

$appName = "Live Ops";
$shortName = "CRM";
$iconUrl = "https://cdn-icons-png.flaticon.com/512/9374/9374972.png"; 

try {
    $stmt = $pdo->prepare("SELECT company_name, logo_url FROM business_info WHERE user_id = ? LIMIT 1");
    $stmt->execute([$user_id]);
    $biz = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($biz) {
        if (!empty($biz['company_name'])) {
            $appName = substr($biz['company_name'], 0, 25); 
            $shortName = substr($biz['company_name'], 0, 12);
        }
        
        if (!empty($biz['logo_url'])) {
            $cleanLogo = str_replace('../', '', $biz['logo_url']);
            
            if (strpos($cleanLogo, 'http') === 0) {
                $iconUrl = $cleanLogo;
            } else {
                $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
                $host = $_SERVER['HTTP_HOST'];
                $path = dirname($_SERVER['PHP_SELF']);
                $iconUrl = "$protocol://$host$path/$cleanLogo";
            }
        }
    }
} catch (Exception $e) {
}

$manifest = [
    "name" => $appName,
    "short_name" => $shortName,
    "start_url" => "app.php",
    "display" => "standalone",
    "background_color" => "#ffffff",
    "theme_color" => "#ef4444",
    "orientation" => "portrait",
    "icons" => [
        [
            "src" => $iconUrl,
            "sizes" => "192x192", 
            "type" => "image/png"
        ],
        [
            "src" => $iconUrl,
            "sizes" => "512x512",
            "type" => "image/png"
        ]
    ]
];

echo json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
?>