<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';
require_once __DIR__.'/../includes/admin_functions.php';
require_once __DIR__.'/../includes/diamond_mercadopago_functions.php';

afRequireSuperAdmin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!validarCsrfToken($_POST[CSRF_TOKEN_NAME] ?? '')) throw new RuntimeException('Sessão expirada. Atualize a página e tente novamente.');
        afDiamondMpSaveAdminConfig($pdo, $_POST);
        setFlash('success', 'Configurações do Mercado Pago salvas com sucesso.');
        header('Location: '.SITE_URL.'/pages/admin-diamond-mercadopago.php'); exit;
    } catch (Throwable $e) {
        setFlash('error', $e->getMessage());
        header('Location: '.SITE_URL.'/pages/admin-diamond-mercadopago.php'); exit;
    }
}

$enabled = afDiamondMpEnabled($pdo);
$configEnabled = filter_var(afDiamondMpConfig($pdo, 'diamond_mp_enabled', false), FILTER_VALIDATE_BOOLEAN);
$environment = afDiamondMpEnvironment($pdo);
$publicKey = (string)afDiamondMpConfig($pdo, 'diamond_mp_public_key', '');
$hasToken = afDiamondMpAccessToken($pdo) !== '';
$webhookToken = afDiamondMpWebhookToken($pdo);
$webhookUrl = afDiamondMpWebhookUrl($pdo);

$recent = [];
try {
    $recent = $pdo->query('SELECT * FROM af_diamond_payment_logs ORDER BY id DESC LIMIT 20')->fetchAll() ?: [];
} catch (Throwable $e) {}

$pageTitle = 'Admin • Mercado Pago Diamantes';
$showNav = false;
$bodyClass = 'admin-body';
$adminPage = 'economia_diamantes';
require __DIR__.'/../includes/header.php';
?>
<div class="admin-shell">
<?php require __DIR__.'/../includes/admin_nav.php'; ?>
<main class="admin-main diamonds-admin">
  <header class="admin-topbar">
    <div><small>ECONOMIA DO JOGO</small><h1>Mercado Pago dos Diamantes</h1></div>
    <span class="admin-count">Parte 05 • v<?=esc(AURA_DIAMONDS_PART05_VERSION)?></span>
  </header>
  <?=renderFlash()?>

  <section class="admin-kpi-grid diamonds-kpis">
    <article><span><?= $enabled ? '✅' : '⚠️' ?></span><div><small>Status real</small><strong><?= $enabled ? 'Ativo' : 'Inativo' ?></strong></div></article>
    <article><span>🔑</span><div><small>Access Token</small><strong><?= $hasToken ? 'Informado' : 'Ausente' ?></strong></div></article>
    <article><span>🌎</span><div><small>Ambiente</small><strong><?= esc($environment) ?></strong></div></article>
    <article><span>🔔</span><div><small>Webhook</small><strong>URL gerada</strong></div></article>
  </section>

  <nav class="admin-tabs">
    <a href="<?=SITE_URL?>/pages/admin-diamond-packages.php">Pacotes de Diamantes</a>
    <a class="active" href="<?=SITE_URL?>/pages/admin-diamond-mercadopago.php">Mercado Pago</a>
    <span class="diamond-tab-disabled">Compras — próxima parte</span>
    <span class="diamond-tab-disabled">Extrato — próxima parte</span>
  </nav>

  <section class="admin-grid-2 diamonds-grid">
    <article class="admin-panel">
      <header><div><small>CONFIGURAÇÃO</small><h2>Recebimento via Mercado Pago</h2></div></header>

      <form method="post" class="admin-form diamond-package-form" autocomplete="off">
        <?=camposCsrf()?>

        <label class="diamond-switch">
          <input type="checkbox" name="diamond_mp_enabled" value="1" <?= $configEnabled ? 'checked' : '' ?>>
          <span>Ativar compras de Diamantes via Mercado Pago</span>
        </label>

        <label>Ambiente
          <select name="diamond_mp_environment">
            <option value="production" <?= $environment === 'production' ? 'selected' : '' ?>>Produção</option>
            <option value="sandbox" <?= $environment === 'sandbox' ? 'selected' : '' ?>>Sandbox / Testes</option>
          </select>
          <small>Use Produção para receber pagamentos reais.</small>
        </label>

        <label>Access Token do Mercado Pago
          <input name="diamond_mp_access_token" type="password" placeholder="<?= $hasToken ? 'Token já salvo — preencha somente para trocar' : 'Cole aqui o access token' ?>">
          <small>Por segurança, o token salvo não aparece na tela. Preencha apenas se for cadastrar ou trocar.</small>
        </label>

        <label>Public Key
          <input name="diamond_mp_public_key" value="<?=esc($publicKey)?>" placeholder="APP_USR-...">
          <small>Usado para referência administrativa. O checkout da Parte 05 usa o Access Token no servidor.</small>
        </label>

        <label>Token interno do webhook
          <input name="diamond_mp_webhook_token" value="<?=esc($webhookToken)?>">
          <small>Este token protege a URL do webhook no seu servidor. Não publique em locais abertos.</small>
        </label>

        <button class="admin-primary" type="submit">Salvar configurações</button>
      </form>
    </article>

    <article class="admin-panel diamond-help">
      <header><div><small>WEBHOOK</small><h2>URL para cadastrar no Mercado Pago</h2></div></header>
      <p>Cadastre esta URL no painel do Mercado Pago para receber eventos de pagamento:</p>
      <textarea readonly rows="4" onclick="this.select()" style="width:100%;border-radius:14px;background:rgba(0,0,0,.35);color:#fff;border:1px solid rgba(0,212,255,.24);padding:12px;resize:none"><?=esc($webhookUrl)?></textarea>
      <p><b>Evento necessário:</b> pagamentos / payment.</p>
      <div class="admin-warning">Os Diamantes só são liberados depois que o sistema consulta o pagamento na API oficial do Mercado Pago e confirma status aprovado.</div>
    </article>
  </section>

  <section class="admin-panel">
    <header><div><small>LOGS RECENTES</small><h2>Eventos Mercado Pago</h2></div></header>
    <?php if (!$recent): ?>
      <p class="admin-empty">Nenhum evento de pagamento registrado ainda.</p>
    <?php else: ?>
      <div class="admin-table-wrap">
        <table class="admin-table">
          <thead><tr><th>Data</th><th>Evento</th><th>Origem</th><th>Status</th><th>Pedido</th><th>Pagamento</th></tr></thead>
          <tbody>
          <?php foreach ($recent as $log): ?>
            <tr>
              <td><?=date('d/m/Y H:i', strtotime((string)$log['created_at']))?></td>
              <td><b><?=esc((string)$log['event_type'])?></b></td>
              <td><?=esc((string)$log['source'])?></td>
              <td><span class="admin-pill <?=((string)$log['status']==='ok'||(string)$log['status']==='approved')?'status-normal':'status-restrito'?>"><?=esc((string)$log['status'])?></span></td>
              <td><?= $log['order_id'] ? '#'.(int)$log['order_id'] : '-' ?></td>
              <td><?= esc((string)($log['payment_id'] ?? '-')) ?></td>
            </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </section>
</main>
</div>
<link rel="stylesheet" href="<?=SITE_URL?>/assets/css/diamonds-admin.css?v=5.0.0">
<script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script>
<?php require __DIR__.'/../includes/footer.php'; ?>
