<?php
// FILE: /digitalpremium/pwa/manifest.php
header('Content-Type: application/manifest+json; charset=utf-8');

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/message_helper.php';

$slug = $_GET['slug'] ?? '';
if (!$slug) {
  echo json_encode([
    "name" => "DigitalPremium",
    "short_name" => "DigitalPremium",
    "start_url" => "/digitalpremium/",
    "display" => "standalone",
    "background_color" => "#000000",
    "theme_color" => "#6a1b9a",
    "icons" => []
  ]);
  exit;
}

$stmt = $pdo->prepare("SELECT id_usuario, nombre_completo FROM usuarios WHERE catalogo_slug=?");
$stmt->execute([$slug]);
$u = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$u) {
  echo json_encode([
    "name" => "DigitalPremium",
    "short_name" => "DigitalPremium",
    "start_url" => "/digitalpremium/",
    "display" => "standalone",
    "background_color" => "#000000",
    "theme_color" => "#6a1b9a",
    "icons" => []
  ]);
  exit;
}
$id_usuario = (int)$u['id_usuario'];
$nombre_negocio = getConfigValue('nombre_negocio', $id_usuario, $u['nombre_completo'] ?? 'Tu Tienda');
$primary_color  = getConfigValue('primary_color', $id_usuario, '#6a1b9a');
$logo           = getConfigValue('brand_logo_url', $id_usuario, '');
$logoAbs        = $logo ? ((strpos($logo,'http')===0)?$logo:(((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS']!=='off')?'https':'http').'://'.$_SERVER['HTTP_HOST'].'/'.ltrim($logo,'/')))) : '';

$startUrl = "/catalogo/{$slug}";

echo json_encode([
  "name" => $nombre_negocio,
  "short_name" => mb_substr($nombre_negocio,0,12),
  "start_url" => $startUrl,
  "scope" => "/",
  "display" => "standalone",
  "background_color" => "#000000",
  "theme_color" => $primary_color,
  "icons" => $logoAbs ? [
    ["src"=>$logoAbs, "sizes"=>"192x192", "type"=>"image/png"],
    ["src"=>$logoAbs, "sizes"=>"512x512", "type"=>"image/png"]
  ] : []
], JSON_UNESCAPED_UNICODE);
