<?php
/**
 * WB Store - Catálogo
 */
include ("../../../inc/includes.php");

// Guard lives in /inc (not covered by the simple PSR-4 autoloader in setup.php)
require_once __DIR__ . "/../inc/guard.php";

use GlpiPlugin\Wbstore\Config;
use GlpiPlugin\Wbstore\StoreClient;
use GlpiPlugin\Wbstore\Guard;
use GlpiPlugin\Wbstore\Utils;
// Avisos via iframe (Portal)

Session::checkRight('config', UPDATE);

function wbstore_e($v): string {
   return htmlspecialchars((string)$v, ENT_QUOTES, 'UTF-8');
}

Html::header('WB Store', $_SERVER['PHP_SELF'], 'config', 'plugins');

// Atualiza licença/cache ao abrir o catálogo (best-effort, sem travar o GLPI)
   // Ensure cron task exists (shows in Automatic actions)
   if (class_exists('PluginWbstoreCron') && method_exists('PluginWbstoreCron','ensureRegistered')) {
      PluginWbstoreCron::ensureRegistered();
   }

Guard::onCatalogOpen();

$conf = Config::all();
$license = trim((string)($conf['license_key'] ?? ''));

echo "<style>
.wbwrap{max-width:1200px;margin:0 auto;}
.wbh{display:flex;gap:12px;align-items:center;justify-content:space-between;flex-wrap:wrap;margin-bottom:14px}
.wbhL{display:flex;gap:12px;align-items:center}
.wblogo{width:40px;height:40px;border-radius:12px;background:#0f1f17;display:flex;align-items:center;justify-content:center;box-shadow:0 8px 20px rgba(0,0,0,.12)}
.wblogo i{color:#22c55e;font-size:18px}
.wbtitle{margin:0;font-size:22px;font-weight:900}
.wbsub{margin:0;opacity:.85}
.wbtop{display:flex;gap:10px;align-items:center;flex-wrap:wrap}
.wbsearch{min-width:260px;max-width:420px;flex:1}
.wbsearch input{width:100%;border:1px solid rgba(16,24,40,.16);border-radius:14px;padding:10px 12px;outline:none}
.wbsearch input:focus{border-color:#15803d;box-shadow:0 0 0 4px rgba(21,128,61,.15)}
.wbbtn{border-radius:12px;padding:10px 12px;font-weight:800;display:inline-flex;gap:8px;align-items:center;text-decoration:none}
.wbbtn-primary{background:#15803d;border:1px solid #0f6a30;color:#fff}
.wbbtn-light{background:#fff;border:1px solid rgba(16,24,40,.18);color:#111827}
.wbgrid{display:grid;grid-template-columns:1fr;gap:14px}
@media (min-width:720px){.wbgrid{grid-template-columns:1fr 1fr}}
@media (min-width:1100px){.wbgrid{grid-template-columns:1fr 1fr 1fr}}
.card{background:#fff;border-radius:18px;border:1px solid rgba(16,24,40,.08);box-shadow:0 10px 25px rgba(16,24,40,.06);padding:16px;display:flex;flex-direction:column;min-height:220px;position:relative;overflow:hidden}
.card:before{content:'';position:absolute;inset:-40% -30% auto auto;width:220px;height:220px;border-radius:50%;background:radial-gradient(circle at 30% 30%, rgba(34,197,94,.18), rgba(34,197,94,0));pointer-events:none}
.cname{margin:0;font-size:16px;font-weight:900;letter-spacing:.2px;position:relative;z-index:2}
.cdesc{margin:8px 0 0;opacity:.85;line-height:1.35;flex:1;position:relative;z-index:2}
.cmeta{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px;position:relative;z-index:2}
.pill{display:inline-flex;gap:6px;align-items:center;border-radius:999px;padding:6px 10px;font-weight:900;font-size:12px;border:1px solid rgba(16,24,40,.12);background:#fff}
.pill-ok{background:rgba(21,128,61,.08);color:#14532d;border-color:rgba(21,128,61,.25)}
.pill-warn{background:rgba(245,158,11,.10);color:#92400e;border-color:rgba(245,158,11,.25)}
.pill-bad{background:rgba(239,68,68,.10);color:#991b1b;border-color:rgba(239,68,68,.25)}
.actions{display:flex;flex-wrap:wrap;gap:10px;margin-top:12px;position:relative;z-index:2}
.a{border-radius:12px;padding:9px 11px;font-weight:900;text-decoration:none;display:inline-flex;gap:8px;align-items:center;border:1px solid rgba(16,24,40,.16);background:#fff;color:#111827}
.a-primary{background:#0f1f17;border-color:#0a1510;color:#fff}
.a-primary:hover{filter:brightness(.98)}
.a-disabled{opacity:.45;pointer-events:none}
.note{margin:0 0 14px;opacity:.85}
</style>";

echo "<div class='wbwrap'>";
echo "<div class='wbh'>";
echo "<div class='wbhL'>";
echo "<div class='wblogo'><i class='fas fa-store'></i></div>";
echo "<div><h2 class='wbtitle'>WB Store</h2><p class='wbsub'>Plugins prontos para instalar e usar.</p></div>";
echo "</div>";
echo "<div class='wbtop'>";
echo "<div class='wbsearch'><input id='wbq' placeholder='Pesquisar no catálogo...' /></div>";
echo "<a class='wbbtn wbbtn-light' href='config.php'><i class='fas fa-cog'></i> Configurações</a>";
echo "<a class='wbbtn wbbtn-light' href='notifications.php'><i class='fas fa-bell'></i> Avisos</a>";
echo "</div>";
echo "</div>";

// ===== Avisos WBUARQUE (iframe) =====
$iframe = Utils::portalNoticesIframeUrl(['embed' => 'catalog']);
if ($iframe !== '') {
   echo "<div style='margin:0 0 14px'>";
   echo "<div class='card' style='min-height:auto;padding:12px'>";
   echo "<div style='font-weight:900;margin:0 0 8px'><i class='fas fa-bell' style='color:#15803d'></i> Avisos WBUARQUE</div>";
   echo "<div style='border:1px solid rgba(16,24,40,.10);border-radius:14px;overflow:hidden;background:#f8fafc'>";
   echo "<iframe src='" . wbstore_e($iframe) . "' style='width:100%;height:220px;border:0' loading='lazy'></iframe>";
   echo "</div>";
   echo "</div>";
   echo "</div>";
}

if ($license === '') {
   echo "<div class='alert alert-warning'>Acesso não configurado. Vá em <b>Configurações</b> para liberar o catálogo.</div>";
   echo "</div>";
   Html::footer();
   exit;
}

$client = new StoreClient();

// Cache completo do catálogo (arquivo assinado). Se estiver vazio, força sync.
$data = Guard::getFullPackagesCache(true);
if (empty($data)) {
   // força uma sincronização online (catálogo pode chamar HTTP)
   Guard::refreshPackagesCache(true);
   $data = Guard::getFullPackagesCache(true);
}

$packages = [];
if (isset($data['packages']) && is_array($data['packages'])) {
   $packages = $data['packages'];
} elseif (is_array($data)) {
   // some servers return list directly
   $packages = $data;
}

if (empty($packages)) {
   // tenta ao vivo uma última vez só pra capturar erro (sem travar init)
   $tmp = $client->listPackages();
   $err = $client->getLastError();
   if ($err === '') {
      $err = 'Falha ao sincronizar o catálogo. Verifique a licença (WBStore) e a conectividade com o portal.';
   }
   echo "<div class='alert alert-danger'>" . wbstore_e($err) . "</div>";
   echo "</div>";
   Html::footer();
   exit;
}

echo "<p class='note'>Dica: mantenha seu GLPI atualizado. Plugins podem exigir versões mínimas.</p>";
echo "<div class='wbgrid' id='wbgrid'>";

foreach ($packages as $p) {
   if (!is_array($p)) continue;
   $slug = (string)($p['slug'] ?? '');
   $name = (string)($p['name'] ?? $slug);
   $desc = trim((string)($p['description'] ?? ''));
   if ($desc === '') {
      $desc = 'Plugin criado para necessidades reais e para facilitar o dia a dia no GLPI.';
   }
   $demo = trim((string)($p['demo_url'] ?? ''));
   $buy  = trim((string)($p['purchase_url'] ?? ''));
   $min  = trim((string)($p['min_glpi'] ?? ''));
   $ver  = trim((string)($p['latest_version'] ?? ''));

   $pluginDir = (string)($p['plugin_dir'] ?? ($p['dir'] ?? $slug));
   $st = Utils::pluginStatus($pluginDir);
   $installed = (bool)($st['installed'] ?? false);
   $activated = (bool)($st['activated'] ?? false);

   $can = true;
   if (array_key_exists('can_download', $p)) {
      $can = (bool)$p['can_download'];
   }

   $statusPill = '';
   if ($activated) {
      $statusPill = "<span class='pill pill-ok'><i class='fas fa-check'></i> Ativo</span>";
   } elseif ($installed) {
      $statusPill = "<span class='pill pill-warn'><i class='fas fa-box'></i> Instalado</span>";
   } elseif ($can) {
      $statusPill = "<span class='pill pill-ok'><i class='fas fa-sparkles'></i> Disponível</span>";
   } else {
      $statusPill = "<span class='pill pill-bad'><i class='fas fa-lock'></i> Bloqueado</span>";
   }

   $meta = [];
   if ($ver !== '') $meta[] = "<span class='pill'><i class='fas fa-tag'></i> v" . wbstore_e($ver) . "</span>";
   if ($min !== '') $meta[] = "<span class='pill'><i class='fas fa-arrow-up'></i> GLPI " . wbstore_e($min) . "+</span>";

   $installUrl = 'install.php?slug=' . rawurlencode($slug);
   $installCls = $can ? 'a a-primary' : 'a a-primary a-disabled';
   $installText = $installed ? 'Reinstalar' : 'Baixar e instalar';
   if ($activated) $installText = 'Reinstalar';

   $ln = function_exists('mb_strtolower') ? mb_strtolower($name) : strtolower($name);
   $ls = function_exists('mb_strtolower') ? mb_strtolower($slug) : strtolower($slug);
   echo "<div class='card' data-name='" . wbstore_e($ln) . "' data-slug='" . wbstore_e($ls) . "'>";
   echo "<h3 class='cname'>" . wbstore_e($name) . "</h3>";
   echo "<p class='cdesc'>" . wbstore_e($desc) . "</p>";
   echo "<div class='cmeta'>" . $statusPill . implode('', $meta) . "</div>";
   echo "<div class='actions'>";
   echo "<a class='$installCls' href='" . wbstore_e($installUrl) . "'><i class='fas fa-download'></i> " . wbstore_e($installText) . "</a>";
   if ($demo !== '') {
      echo "<a class='a' target='_blank' rel='noopener' href='" . wbstore_e($demo) . "'><i class='fas fa-play'></i> Demonstração</a>";
   }
   if ($buy !== '') {
      echo "<a class='a' target='_blank' rel='noopener' href='" . wbstore_e($buy) . "'><i class='fas fa-handshake'></i> Contratar</a>";
   }
   echo "</div>";
   echo "</div>";
}

echo "</div>";

echo "<script>
(function(){
  var q = document.getElementById('wbq');
  var grid = document.getElementById('wbgrid');
  if (!q || !grid) return;
  q.addEventListener('input', function(){
    var v = (q.value||'').toLowerCase().trim();
    var cards = grid.querySelectorAll('.card');
    cards.forEach(function(c){
      var name = c.getAttribute('data-name')||'';
      var slug = c.getAttribute('data-slug')||'';
      var ok = (v==='') || name.indexOf(v)>=0 || slug.indexOf(v)>=0;
      c.style.display = ok ? '' : 'none';
    });
  });
})();
</script>";

echo "</div>";

Html::footer();
