<?php
/**
 * WB Store - Configuração
 */
include ("../../../inc/includes.php");

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

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

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

$conf = Config::all();
$currentDomain = Utils::currentDomain();
$effectiveDomain = trim((string)($conf['domain'] ?? '')) !== '' ? (string)$conf['domain'] : $currentDomain;

$flash_ok = '';
$flash_err = '';

// --- Handle POST (CSRF is validated by GLPI kernel listener) ---
$action = $_POST['action'] ?? null;
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'POST') {

   if ($action === 'save') {
      $store_url   = trim((string)($_POST['store_url'] ?? ''));
      $api_base    = trim((string)($_POST['api_base'] ?? ''));
      $license_key = trim((string)($_POST['license_key'] ?? ''));
      $domain      = trim((string)($_POST['domain'] ?? ''));
      $token       = trim((string)($_POST['token'] ?? ''));
      $ssl_verify  = isset($_POST['ssl_verify']) ? 1 : 0;
      $safe_mode   = isset($_POST['safe_mode']) ? 1 : 0;

      $pix_qr_url  = trim((string)($_POST['pix_qr_url'] ?? ''));
      $pix_code    = trim((string)($_POST['pix_code'] ?? ''));

      if ($store_url !== '' && !preg_match('#^https?://#i', $store_url)) {
         $store_url = 'https://' . $store_url;
      }
      if ($api_base !== '' && !preg_match('#^https?://#i', $api_base)) {
         $api_base = 'https://' . $api_base;
      }
      if ($pix_qr_url !== '' && !preg_match('#^https?://#i', $pix_qr_url)) {
         $pix_qr_url = 'https://' . $pix_qr_url;
      }

      $before = Config::all();
      Config::set([
         'store_url'   => $store_url,
         'api_base'    => $api_base,
         'license_key' => $license_key,
         'domain'      => $domain,
         'token'       => $token,
         'ssl_verify'  => $ssl_verify,
         'safe_mode'   => $safe_mode,
         'pix_qr_url'  => $pix_qr_url,
         'pix_code'    => $pix_code,
      ]);

      $after = Config::all();
      Webhook::event('wbstore.config.save', ['before'=>$before,'after'=>$after]);
      Html::redirect($CFG_GLPI['root_doc'] . '/plugins/wbstore/front/config.php?saved=1');
      exit;
   }

   // Access workflow (lookup/register/donate)
   $client = new StoreClient();

   if ($action === 'lookup' || $action === 'register' || $action === 'donate') {
      $email = trim((string)($_POST['email'] ?? ''));
      $phone = trim((string)($_POST['phone'] ?? ''));
      $name  = trim((string)($_POST['name'] ?? ''));
      $company = trim((string)($_POST['company'] ?? ''));

      if ($email === '' || $phone === '') {
         $flash_err = 'E-mail e telefone são obrigatórios.';
      } else {
         $payload = [
            'email'   => $email,
            'phone'   => $phone,
         ];
         if ($name !== '') {
            $payload['name'] = $name;
         }
         if ($company !== '') {
            $payload['company'] = $company;
         }

         if ($action === 'lookup') {
            $resp = $client->lookupRegistration($payload);
         } elseif ($action === 'register') {
            if ($name === '') {
               $flash_err = 'Informe seu nome para liberar o acesso.';
               $resp = [];
            } else {
               $resp = $client->registerAccess($payload);
            }
         } else { // donate
            $code = trim((string)($_POST['donation_code'] ?? ''));
            if ($code === '') {
               $flash_err = 'Informe o código de confirmação.';
               $resp = [];
            } else {
               $payload['code'] = $code;
               $resp = $client->verifyDonation($payload);
            }
         }

         if ($flash_err === '') {
            $ok = (bool)($resp['ok'] ?? false);
            $lk = trim((string)($resp['license_key'] ?? ''));
            if ($ok && $lk !== '') {
               $before = Config::all();
      Config::set(['license_key' => $lk]);
               Html::redirect($CFG_GLPI['root_doc'] . '/plugins/wbstore/front/config.php?access=1');
               exit;
            }

            $msg = (string)($resp['message'] ?? '');
            if ($msg === '') {
               $msg = $client->getLastError();
            }
            if ($msg === '') {
               $msg = 'Não foi possível concluir. Confira os dados e tente novamente.';
            }
            $flash_err = $msg;
         }
      }
   }
}

// refresh conf after any post handling
$conf = Config::all();
$instance_id = (string)($conf['instance_id'] ?? '');

// IMPORTANT: generate CSRF token once and reuse across forms
$csrf = Session::getNewCSRFToken();

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

// --- Styles (WBUARQUE look) ---
echo "<style>
.wbwrap{max-width:1100px;margin:0 auto;}
.wbh1{display:flex;gap:12px;align-items:center;margin:0 0 12px;}
.wblogo{width:38px;height:38px;border-radius:10px;background:#0f1f17;display:flex;align-items:center;justify-content:center;box-shadow:0 8px 20px rgba(0,0,0,.12)}
.wblogo img{width:28px;height:28px;object-fit:contain}
.wbtitle{margin:0;font-size:22px;font-weight:800;letter-spacing:.2px}
.wbsub{margin:0 0 18px;opacity:.85}
.wbgrid{display:grid;grid-template-columns:1fr;gap:14px}
@media (min-width: 980px){.wbgrid{grid-template-columns:1.2fr .8fr}}
.wbcard{background:#fff;border-radius:16px;box-shadow:0 10px 25px rgba(16,24,40,.06);border:1px solid rgba(16,24,40,.08);padding:16px}
.wbcard h3{margin:0 0 10px;font-size:16px;font-weight:800}
.wbmuted{opacity:.8}
.wbrow{display:grid;grid-template-columns:1fr;gap:10px}
@media (min-width: 720px){.wbrow{grid-template-columns:1fr 1fr}}
.wbfield label{display:block;font-weight:700;margin:0 0 6px}
.wbfield input,.wbfield textarea{width:100%;border:1px solid rgba(16,24,40,.16);border-radius:12px;padding:10px 12px;outline:none}
.wbfield input:focus,.wbfield textarea:focus{border-color:#15803d;box-shadow:0 0 0 4px rgba(21,128,61,.15)}
.wbactions{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
.wbbtn{border-radius:12px;padding:10px 12px;font-weight:800;display:inline-flex;gap:8px;align-items:center}
.wbbtn-primary{background:#15803d;border:1px solid #0f6a30;color:#fff}
.wbbtn-primary:hover{filter:brightness(.98)}
.wbbtn-secondary{background:#0f1f17;border:1px solid #0a1510;color:#fff}
.wbbtn-light{background:#fff;border:1px solid rgba(16,24,40,.18);color:#111827}
.wbsep{height:1px;background:rgba(16,24,40,.08);margin:14px 0}
.wbpill{display:inline-flex;gap:8px;align-items:center;border-radius:999px;padding:6px 10px;background:rgba(21,128,61,.08);color:#14532d;font-weight:800}
.wbqr{display:flex;gap:14px;align-items:flex-start;flex-wrap:wrap}
.wbqrimg{width:160px;height:160px;border-radius:16px;border:1px solid rgba(16,24,40,.12);overflow:hidden;background:#f8fafc}
.wbqrimg img{width:100%;height:100%;object-fit:cover}
.wbsmall{font-size:12px;opacity:.8}
</style>";

echo "<div class='wbwrap'>";

echo "<div class='wbh1'>";
echo "<div class='wblogo'>";
// try plugin logo if exists
$logoPath = GLPI_ROOT . '/plugins/wbstore/pics/logo.png';
if (is_file($logoPath)) {
   $webdir = Plugin::getWebDir('wbstore');
   echo "<img src='" . wbstore_e($webdir . "/pics/logo.png") . "' alt='WB' />";
} else {
   echo "<i class='fas fa-store' style='color:#22c55e;font-size:18px'></i>";
}
echo "</div>";
echo "<div>";
echo "<h2 class='wbtitle'>WB Store</h2>";
echo "<p class='wbsub'>Catálogo de plugins da WBUARQUE, com instalação direta dentro do GLPI.</p>";
echo "</div>";
echo "</div>";

if (!empty($_GET['saved'])) {
   echo "<div class='alert alert-success'>Configurações salvas.</div>";
}
if (!empty($_GET['access'])) {
   echo "<div class='alert alert-success'>Acesso liberado. Você já pode abrir o catálogo.</div>";
}
if ($flash_err !== '') {
   echo "<div class='alert alert-danger'>" . wbstore_e($flash_err) . "</div>";
}

echo "<div class='wbgrid'>";

// LEFT: Access + Pix
echo "<div class='wbcard'>";
echo "<h3><i class='fas fa-unlock' style='color:#15803d'></i> Acesso ao catálogo</h3>";

if (trim((string)($conf['license_key'] ?? '')) !== '') {
   $licOk = License::isValid(false);
   if ($licOk) {
      echo "<div class='wbpill'><i class='fas fa-shield-check'></i> Licença válida</div>";
   } else {
      echo "<div class='alert alert-warning' style='margin:10px 0 0'>Licença configurada, mas <b>não validada</b>. Verifique no Portal-WB.</div>";
   }

   echo "<div class='wbpill'><i class='fas fa-check-circle'></i> Acesso já configurado</div>";
   echo "<div class='wbactions' style='margin-top:12px'>";
   echo "<a class='wbbtn wbbtn-primary' href='catalog.php'><i class='fas fa-list'></i> Abrir catálogo</a>";
   echo "</div>";
   echo "<div class='wbsep'></div>";
}

echo "<p class='wbmuted'>Se você já possui acesso, consulte antes para evitar duplicidade. Telefone é obrigatório.</p>";

echo "<form method='post' action='' style='margin:0'>";
echo Html::hidden('_glpi_csrf_token', ['value' => $csrf]);
echo "<div class='wbrow'>";
echo "<div class='wbfield'><label>Nome</label><input name='name' placeholder='Seu nome' value='' /></div>";
echo "<div class='wbfield'><label>Empresa</label><input name='company' placeholder='Opcional' value='' /></div>";
echo "<div class='wbfield'><label>E-mail</label><input name='email' required type='email' placeholder='seuemail@empresa.com' value='' /></div>";
echo "<div class='wbfield'><label>Telefone</label><input name='phone' required placeholder='DDD + número' value='' /></div>";
echo "</div>";

echo "<div class='wbactions'>";
echo "<button class='wbbtn wbbtn-light' type='submit' name='action' value='lookup'><i class='fas fa-search'></i> Consultar cadastro</button>";
echo "<button class='wbbtn wbbtn-primary' type='submit' name='action' value='register'><i class='fas fa-user-check'></i> Liberar acesso</button>";
echo "</div>";
echo "</form>";

echo "<div class='wbsep'></div>";

echo "<div class='wbsep'></div>";

echo "<h3 style='margin-top:0'><i class='fas fa-qrcode' style='color:#15803d'></i> Apoie via Pix</h3>";
echo "<p class='wbmuted'>Se este catálogo te ajuda no dia a dia, considere apoiar o projeto. Você escolhe o valor.</p>";

$pixQr = 'https://wbuarque.com.br/wp-content/uploads/public_html/img/pix.jpeg';

echo "<div class='wbqr'>";
echo "<div class='wbqrimg'><img src='" . wbstore_e($pixQr) . "' alt='Pix QR Code' /></div>";
echo "<div style='flex:1;min-width:240px'>";
echo "<div class='wbpill'><i class='fas fa-heart'></i> Obrigado pelo apoio</div>";
echo "<div class='wbsmall' style='margin-top:10px'>Seu apoio mantém o projeto evoluindo e ajuda a trazer novas melhorias.</div>";
echo "</div>";
echo "</div>";


echo "</div>"; // left card

// RIGHT: Info
echo "<div class='wbcard'>";
echo "<h3><i class='fas fa-info-circle' style='color:#15803d'></i> Informações</h3>";
echo "<p class='wbmuted'>Use o catálogo para instalar plugins diretamente no GLPI.</p>";

echo "<div class='wbfield'><label>Identificação da instalação</label><input readonly value='" . wbstore_e($instance_id) . "' /></div>";
echo "<div class='wbsmall'>Domínio do GLPI: <b>" . wbstore_e($currentDomain) . "</b></div>";

echo "<div class='wbactions'>";
echo "<a class='wbbtn wbbtn-secondary' href='catalog.php'><i class='fas fa-list'></i> Catálogo</a>";
echo "</div>";


echo "<div class='wbsep'></div>";
echo "<h3 style='margin-top:0'><i class='fas fa-bell' style='color:#15803d'></i> Avisos WBUARQUE</h3>";
echo "<div class='wbactions' style='margin-top:10px'>";
echo "<a class='wbbtn wbbtn-light' href='notifications.php'><i class='fas fa-inbox'></i> Ver avisos</a>";
echo "</div>";

$iframe = Utils::portalNoticesIframeUrl(['embed' => 'config']);
if ($iframe === '') {
   echo "<div class='alert alert-warning' style='margin:12px 0 0'>Avisos indisponíveis (store_url não configurada).</div>";
} else {
   echo "<div style='margin-top:12px;border:1px solid rgba(16,24,40,.10);border-radius:16px;overflow:hidden;background:#f8fafc'>";
   echo "<iframe src='" . wbstore_e($iframe) . "' style='width:100%;height:260px;border:0' loading='lazy'></iframe>";
   echo "</div>";
}


echo "</div>"; // right card



echo "</div>"; // grid

echo "</div>"; // wrap

Html::footer();
