<?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_admin_functions.php';

afRequireSuperAdmin();
$adminId = afAdminId();

try {
    afDiamondsAssertInstalled($pdo);
} catch (Throwable $e) {
    setFlash('error', $e->getMessage());
}

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.');
        $acao = (string)($_POST['acao'] ?? '');

        if ($acao === 'salvar_pacote') {
            $id = afDiamondsAdminSavePackage($pdo, $_POST, $adminId);
            setFlash('success', 'Pacote de Diamantes salvo com sucesso.');
            header('Location: '.SITE_URL.'/pages/admin-diamond-packages.php?edit_id='.$id); exit;
        }

        if ($acao === 'alternar_status') {
            $id = (int)($_POST['id'] ?? 0);
            $active = (int)($_POST['active'] ?? 0);
            afDiamondsAdminTogglePackage($pdo, $id, $active, $adminId);
            setFlash('success', $active ? 'Pacote ativado.' : 'Pacote desativado.');
            header('Location: '.SITE_URL.'/pages/admin-diamond-packages.php'); exit;
        }

        throw new RuntimeException('Ação inválida.');
    } catch (Throwable $e) {
        setFlash('error', $e->getMessage());
        $target = SITE_URL.'/pages/admin-diamond-packages.php';
        if (!empty($_POST['id'])) $target .= '?edit_id='.(int)$_POST['id'];
        header('Location: '.$target); exit;
    }
}

$status = (string)($_GET['status'] ?? 'all');
if (!in_array($status, ['all','active','inactive'], true)) $status = 'all';
$editId = (int)($_GET['edit_id'] ?? 0);
$editPackage = $editId > 0 ? afDiamondsAdminGetPackage($pdo, $editId) : null;
$packages = afDiamondsAdminListPackages($pdo, $status);
$stats = afDiamondsAdminPackageStats($pdo);

$pageTitle = 'Admin • Pacotes de 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>Pacotes de Diamantes</h1></div>
    <span class="admin-count">Parte 05 • Pacotes</span>
  </header>
  <?=renderFlash()?>

  <section class="admin-kpi-grid diamonds-kpis">
    <article><span>💎</span><div><small>Total de pacotes</small><strong><?=(int)$stats['total']?></strong></div></article>
    <article><span>✅</span><div><small>Ativos</small><strong><?=(int)$stats['active']?></strong></div></article>
    <article><span>⏸️</span><div><small>Inativos</small><strong><?=(int)$stats['inactive']?></strong></div></article>
    <article><span>💰</span><div><small>Faixa de preço</small><strong><?=afDiamondsFormatPrice((float)$stats['min_price'])?></strong><em>até <?=afDiamondsFormatPrice((float)$stats['max_price'])?></em></div></article>
  </section>

  <nav class="admin-tabs">
    <a class="active" href="<?=SITE_URL?>/pages/admin-diamond-packages.php">Pacotes de Diamantes</a>
    <a 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>
    <span class="diamond-tab-disabled">Ajustes — próxima parte</span>
  </nav>

  <section class="admin-grid-2 diamonds-grid">
    <article class="admin-panel">
      <header>
        <div><small><?= $editPackage ? 'EDITAR PACOTE' : 'NOVO PACOTE' ?></small><h2><?= $editPackage ? esc($editPackage['name']) : 'Cadastrar pacote' ?></h2></div>
        <?php if($editPackage): ?><a href="<?=SITE_URL?>/pages/admin-diamond-packages.php">+ novo pacote</a><?php endif; ?>
      </header>

      <form method="post" class="admin-form diamond-package-form" autocomplete="off">
        <?=camposCsrf()?>
        <input type="hidden" name="acao" value="salvar_pacote">
        <input type="hidden" name="id" value="<?=(int)($editPackage['id'] ?? 0)?>">

        <label>Nome do pacote
          <input name="name" required maxlength="120" value="<?=esc($editPackage['name'] ?? '')?>" placeholder="Ex: Pacote 7 Diamantes">
          <small>Aparece para o usuário na loja de Diamantes.</small>
        </label>

        <label>Código interno
          <input name="code" maxlength="60" value="<?=esc($editPackage['code'] ?? '')?>" placeholder="Gerado automaticamente se ficar vazio">
          <small>Use letras minúsculas, números e underline. Ex: pack_7_diamonds.</small>
        </label>

        <div class="diamond-form-row">
          <label>Diamantes
            <input name="diamonds" required inputmode="numeric" min="1" type="number" value="<?=esc((string)($editPackage['diamonds'] ?? ''))?>" placeholder="7">
          </label>
          <label>Bônus
            <input name="bonus_diamonds" inputmode="numeric" min="0" type="number" value="<?=esc((string)($editPackage['bonus_diamonds'] ?? '0'))?>" placeholder="0">
          </label>
        </div>

        <div class="diamond-form-row">
          <label>Preço em R$
            <input name="price" required inputmode="decimal" value="<?= $editPackage ? esc(number_format((float)$editPackage['price'], 2, ',', '.')) : '' ?>" placeholder="9,99">
          </label>
          <label>Ordem
            <input name="sort_order" inputmode="numeric" min="0" type="number" value="<?=esc((string)($editPackage['sort_order'] ?? '10'))?>">
          </label>
        </div>

        <label>Título para Mercado Pago
          <input name="mercado_pago_title" maxlength="150" value="<?=esc($editPackage['mercado_pago_title'] ?? '')?>" placeholder="Aura Farming - 7 Diamantes">
          <small>Usado na integração Mercado Pago da Parte 05.</small>
        </label>

        <label>Descrição curta
          <textarea name="description" rows="3" maxlength="255" placeholder="Descrição do pacote"><?=esc($editPackage['description'] ?? '')?></textarea>
        </label>

        <label class="diamond-switch">
          <input type="checkbox" name="active" value="1" <?=((int)($editPackage['active'] ?? 1) === 1) ? 'checked' : ''?>>
          <span>Pacote ativo para venda</span>
        </label>

        <button class="admin-primary" type="submit">Salvar pacote</button>
      </form>
    </article>

    <article class="admin-panel diamond-help">
      <header><div><small>PACOTES</small><h2>Planos com desconto</h2></div></header>
      <p><b>Esta parte só controla os pacotes.</b> O Mercado Pago já fica na aba ao lado. Like pago, Super Like pago, XP novo e mudança no perfil ficam para as próximas partes.</p>
      <p>Os seis pacotes padrão ficam disponíveis para edição:</p>
      <ul>
        <li>7 Diamantes — R$ 9,99</li>
        <li>20 Diamantes — R$ 19,99</li>
        <li>45 Diamantes — R$ 39,99</li>
        <li>100 Diamantes — R$ 79,99</li>
        <li>220 Diamantes — R$ 149,99</li>
        <li>500 Diamantes — R$ 299,99</li>
      </ul>
      <div class="admin-warning">Não apague todos os pacotes ativos. A loja precisa de pelo menos um pacote ativo para aparecer corretamente.</div>
    </article>
  </section>

  <section class="admin-panel">
    <header>
      <div><small>LISTAGEM</small><h2>Pacotes cadastrados</h2></div>
      <form method="get" class="diamond-status-filter">
        <select name="status" onchange="this.form.submit()">
          <option value="all" <?=$status==='all'?'selected':''?>>Todos</option>
          <option value="active" <?=$status==='active'?'selected':''?>>Ativos</option>
          <option value="inactive" <?=$status==='inactive'?'selected':''?>>Inativos</option>
        </select>
      </form>
    </header>

    <?php if(!$packages): ?>
      <p class="admin-empty">Nenhum pacote encontrado.</p>
    <?php else: ?>
      <div class="admin-table-wrap">
        <table class="admin-table diamond-package-table">
          <thead><tr><th>Pacote</th><th>Diamantes</th><th>Preço</th><th>Status</th><th>Ordem</th><th>Ações</th></tr></thead>
          <tbody>
            <?php foreach($packages as $pkg): ?>
              <tr>
                <td><b><?=esc($pkg['name'])?></b><small><?=esc($pkg['code'])?><?=!empty($pkg['description']) ? ' • '.esc($pkg['description']) : ''?></small></td>
                <td><strong>💎 <?=afDiamondsFormatBalance((int)$pkg['diamonds'] + (int)$pkg['bonus_diamonds'])?></strong><small><?=afDiamondsFormatBalance((int)$pkg['diamonds'])?> base<?=((int)$pkg['bonus_diamonds']>0) ? ' + '.afDiamondsFormatBalance((int)$pkg['bonus_diamonds']).' bônus' : ''?></small></td>
                <td><b><?=afDiamondsFormatPrice((float)$pkg['price'], (string)$pkg['currency'])?></b><small><?=esc($pkg['currency'])?></small></td>
                <td><span class="admin-pill <?=((int)$pkg['active']===1)?'status-normal':'status-restrito'?>"><?=((int)$pkg['active']===1)?'ativo':'inativo'?></span></td>
                <td><?=(int)$pkg['sort_order']?></td>
                <td>
                  <div class="admin-inline-actions">
                    <a class="admin-primary" href="<?=SITE_URL?>/pages/admin-diamond-packages.php?edit_id=<?=(int)$pkg['id']?>">Editar</a>
                    <form method="post" onsubmit="return confirm('Confirmar alteração de status deste pacote?')">
                      <?=camposCsrf()?>
                      <input type="hidden" name="acao" value="alternar_status">
                      <input type="hidden" name="id" value="<?=(int)$pkg['id']?>">
                      <input type="hidden" name="active" value="<?=((int)$pkg['active']===1)?0:1?>">
                      <button class="<?=((int)$pkg['active']===1)?'admin-danger':'admin-muted'?>" type="submit"><?=((int)$pkg['active']===1)?'Desativar':'Ativar'?></button>
                    </form>
                  </div>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </section>
</main>
</div>
<link rel="stylesheet" href="<?=SITE_URL?>/assets/css/diamonds-admin.css?v=3.0.0">
<script src="<?=SITE_URL?>/assets/js/admin.js?v=14.1"></script>
<?php require __DIR__.'/../includes/footer.php'; ?>
