<?php
/**
 * AURA FARMING — Comprar Diamantes — Parte 05
 * Agora cria pedido e envia para o checkout Mercado Pago.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/diamond_mercadopago_functions.php';

requireLogin();
recarregarSessaoUsuario($pdo, (int)$_SESSION['usuario_id']);
$u = usuarioAtual();
$userId = (int)($u['id'] ?? 0);

$installed = true;
$installError = '';
$mpReady = false;
$balance = 0;
$packages = [];
$orders = [];
$lastOrder = null;
$buyPermission = ['allowed' => false, 'message' => 'Carregando permissões.'];


function afDiamondPackageShopMeta(array $package): array
{
    $raw = (string)($package['metadata_json'] ?? '');
    if ($raw === '') return [];
    $meta = json_decode($raw, true);
    return is_array($meta) ? $meta : [];
}

try {
    afDiamondsAssertInstalled($pdo);
    $balance = afDiamondsGetBalance($pdo, $userId);
    $packages = afDiamondShopListActivePackages($pdo);
    $orders = afDiamondShopListUserOrders($pdo, $userId, 20);
    $buyPermission = afDiamondShopCanUserBuy($pdo, $userId);
    $mpReady = afDiamondMpEnabled($pdo);

    if (!empty($_GET['pedido'])) {
        $lastOrder = afDiamondShopFindUserOrderByUuid($pdo, $userId, (string)$_GET['pedido']);
    }
} catch (Throwable $e) {
    $installed = false;
    $installError = $e->getMessage();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (!$installed) {
            throw new RuntimeException($installError ?: 'Sistema de Diamantes ainda não instalado.');
        }
        if (!validarCsrfToken($_POST[CSRF_TOKEN_NAME] ?? '')) {
            throw new RuntimeException('Sessão expirada. Atualize a página e tente novamente.');
        }
        $action = (string)($_POST['action'] ?? '');
        if ($action !== 'create_diamond_order') {
            throw new RuntimeException('Ação inválida.');
        }
        if (!afDiamondMpEnabled($pdo)) {
            throw new RuntimeException('Mercado Pago ainda não configurado para compra de Diamantes.');
        }

        $packageId = (int)($_POST['package_id'] ?? 0);
        $checkout = afDiamondShopStartMercadoPagoCheckout($pdo, $userId, $packageId);
        $checkoutUrl = (string)($checkout['checkout_url'] ?? '');
        if ($checkoutUrl === '') {
            throw new RuntimeException('Não foi possível gerar o link de pagamento.');
        }
        header('Location: ' . $checkoutUrl);
        exit;
    } catch (Throwable $e) {
        setFlash('error', $e->getMessage());
        header('Location: ' . SITE_URL . '/pages/comprar-diamantes.php');
        exit;
    }
}

$pageTitle = 'Comprar Diamantes';
$activePage = 'perfil';
$pageStyles = [SITE_URL . '/assets/css/diamonds-shop.css?v=5.2.0'];
require_once __DIR__ . '/../includes/header.php';
?>
<header class="app-header">
  <a href="<?= SITE_URL ?>/pages/home.php" class="btn-back">← Início</a>
  <div class="logo-inline"><span class="logo-main">AURA</span><span class="logo-sub">DIAMANTES</span></div>
  <div class="header-actions">
    <div class="diamonds-mini-balance">💎 <?= (int)$balance ?></div>
  </div>
</header>

<main class="page-content diamonds-shop-page">
  <?= renderFlash() ?>

  <section class="diamond-hero card card--glow fade-in">
    <div>
      <span class="diamond-kicker">Carteira do jogador</span>
      <h1>Comprar Diamantes</h1>
      <p>Escolha um pacote com desconto progressivo e pague com Mercado Pago. Os Diamantes só entram na carteira depois que o pagamento for aprovado.</p>
    </div>
    <div class="diamond-balance-card">
      <span>Saldo atual</span>
      <strong>💎 <?= (int)$balance ?></strong>
      <small>Diamantes disponíveis</small>
    </div>
  </section>

  <div class="diamond-info-banner">
    <span>🔒</span>
    <div>
      <strong>Pagamento seguro via Mercado Pago.</strong>
      <small>O retorno da tela não libera saldo sozinho. O sistema confirma o pagamento direto no Mercado Pago antes de creditar os Diamantes.</small>
    </div>
  </div>

  <?php if (!$installed): ?>
    <div class="diamond-error-card">
      <strong>Base dos Diamantes incompleta</strong>
      <p><?= esc($installError) ?></p>
      <small>Confira se as Partes 01, 02, 03 e 04 foram instaladas antes desta etapa.</small>
    </div>
  <?php else: ?>

    <?php if (!$mpReady): ?>
      <div class="diamond-warning-card">
        <strong>Mercado Pago ainda não configurado</strong>
        <p>O administrador precisa informar o Access Token e ativar a integração em Administração → Economia do Jogo → Mercado Pago.</p>
      </div>
    <?php endif; ?>

    <?php if (empty($buyPermission['allowed'])): ?>
      <div class="diamond-warning-card">
        <strong>Compra bloqueada para esta conta</strong>
        <p><?= esc((string)($buyPermission['message'] ?? 'Esta conta não pode comprar Diamantes agora.')) ?></p>
        <?php if (!empty($buyPermission['redirect'])): ?>
          <a class="btn btn-outline-cyan" href="<?= esc((string)$buyPermission['redirect']) ?>">Verificar status →</a>
        <?php endif; ?>
      </div>
    <?php endif; ?>

    <?php if ($lastOrder): $stInfo = afDiamondShopStatusLabel((string)$lastOrder['status']); ?>
      <section class="diamond-last-order card fade-in">
        <div>
          <span class="diamond-kicker">Último pedido</span>
          <h2><?= esc((string)$lastOrder['package_name']) ?></h2>
          <p><?= (int)$lastOrder['total_diamonds'] ?> Diamantes • <?= afDiamondShopMoney($lastOrder['amount'], (string)$lastOrder['currency']) ?></p>
          <small>Referência: <?= esc((string)$lastOrder['external_reference']) ?></small>
        </div>
        <span class="diamond-status diamond-status--<?= esc($stInfo[1]) ?>"><?= esc($stInfo[2]) ?> <?= esc($stInfo[0]) ?></span>
      </section>
    <?php endif; ?>

    <div class="section-title">💎 Pacotes disponíveis</div>
    <section class="diamond-package-grid">
      <?php if (!$packages): ?>
        <div class="diamond-empty card">Nenhum pacote de Diamantes ativo no momento.</div>
      <?php endif; ?>

      <?php foreach ($packages as $package):
        $total = afDiamondShopTotalDiamonds($package);
        $bonus = (int)($package['bonus_diamonds'] ?? 0);
        $meta = afDiamondPackageShopMeta($package);
        $badge = trim((string)($meta['badge'] ?? ''));
        $discountLabel = trim((string)($meta['discount_label'] ?? ''));
        $highlight = preg_replace('/[^a-z0-9_-]/', '', strtolower((string)($meta['highlight'] ?? 'standard')));
        $featured = !empty($meta['featured']);
      ?>
        <article class="diamond-package-card <?= $featured ? 'diamond-package-card--featured' : '' ?> diamond-package-card--<?= esc($highlight ?: 'standard') ?>">
          <?php if ($badge !== ''): ?>
            <div class="diamond-pack-badge"><?= esc($badge) ?></div>
          <?php endif; ?>
          <div class="diamond-package-top">
            <span class="diamond-pack-icon">💎</span>
            <div>
              <h2><?= esc((string)$package['name']) ?></h2>
              <p><?= esc((string)($package['description'] ?? 'Pacote de Diamantes')) ?></p>
            </div>
          </div>

          <div class="diamond-pack-amount">
            <strong><?= (int)$package['diamonds'] ?></strong>
            <span>Diamantes</span>
            <?php if ($bonus > 0): ?><small>+ <?= $bonus ?> bônus = <?= $total ?> total</small><?php endif; ?>
          </div>

          <div class="diamond-pack-price"><?= afDiamondShopMoney($package['price'], (string)$package['currency']) ?></div>
          <?php if ($discountLabel !== ''): ?>
            <div class="diamond-pack-discount"><?= esc($discountLabel) ?></div>
          <?php endif; ?>

          <form method="post" class="diamond-buy-form">
            <?= camposCsrf() ?>
            <input type="hidden" name="action" value="create_diamond_order">
            <input type="hidden" name="package_id" value="<?= (int)$package['id'] ?>">
            <button class="btn btn-primary" type="submit" <?= (empty($buyPermission['allowed']) || !$mpReady) ? 'disabled' : '' ?>>Comprar com Mercado Pago</button>
          </form>
        </article>
      <?php endforeach; ?>
    </section>

    <div class="section-title">🧾 Histórico de compras</div>
    <section class="diamond-history card">
      <?php if (!$orders): ?>
        <p class="diamond-empty-text">Você ainda não criou nenhum pedido de Diamantes.</p>
      <?php else: ?>
        <?php foreach ($orders as $order): $stInfo = afDiamondShopStatusLabel((string)$order['status']); ?>
          <div class="diamond-history-row">
            <div>
              <strong><?= esc((string)$order['package_name']) ?></strong>
              <small><?= date('d/m/Y H:i', strtotime((string)$order['created_at'])) ?> • <?= esc((string)$order['external_reference']) ?></small>
              <?php if (!empty($order['checkout_url']) && (string)$order['status'] === 'pending'): ?>
                <small><a href="<?= esc((string)$order['checkout_url']) ?>">Continuar pagamento →</a></small>
              <?php endif; ?>
            </div>
            <div class="diamond-history-mid">
              <b>💎 <?= (int)$order['total_diamonds'] ?></b>
              <span><?= afDiamondShopMoney($order['amount'], (string)$order['currency']) ?></span>
            </div>
            <span class="diamond-status diamond-status--<?= esc($stInfo[1]) ?>"><?= esc($stInfo[2]) ?> <?= esc($stInfo[0]) ?></span>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </section>

  <?php endif; ?>

  <a class="btn btn-secondary mt-16" href="<?= SITE_URL ?>/pages/perfil.php">← Voltar ao perfil</a>
</main>

<?php require_once __DIR__ . '/../includes/navbar.php'; ?>
<?php require_once __DIR__ . '/../includes/footer.php'; ?>
