<?php
declare(strict_types=1);

require_once __DIR__ . '/_bootstrap.php';
require_once __DIR__ . '/../config/mercado_pago_helpers.php';
admin_require_login();

$statusFiltro = trim((string) ($_GET['status'] ?? 'todos'));
if (!in_array($statusFiltro, ['todos', 'criado', 'pendente', 'autorizado', 'aprovado', 'recusado', 'cancelado', 'estornado', 'erro'], true)) {
    $statusFiltro = 'todos';
}

$resumo = admin_pagamentos_resumo();
$pagamentos = admin_pagamentos_listar($statusFiltro);
$contas = admin_mp_contas_listar();
$eventos = admin_mp_webhooks_listar();
$mpConfigTextual = mp_config_textual(db());
$mpConfigNumerica = mp_config(db());
$flash = admin_flash();
?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bulo Admin - Pagamentos</title>
  <link rel="stylesheet" href="assets/admin.css?v=20260626-1">
</head>
<body>
  <?php admin_sidebar('pagamentos'); ?>

  <main class="page">
    <?php if ($flash): ?>
      <div class="flash <?= e($flash['type']) ?>"><?= e($flash['message']) ?></div>
    <?php endif; ?>

    <section class="panel filter-panel">
      <div class="panel-header">
        <h1>Pagamentos</h1>
        <p>Controle de transacoes Mercado Pago, repasses e eventos recebidos do gateway.</p>
      </div>
      <div class="panel-body">
        <form class="period-form" method="get" action="pagamentos.php">
          <div class="filter-fields">
            <div class="field">
              <label for="status">Status</label>
              <select id="status" name="status">
                <?php foreach (['todos' => 'Todos', 'criado' => 'Criado', 'pendente' => 'Pendente', 'autorizado' => 'Autorizado', 'aprovado' => 'Aprovado', 'recusado' => 'Recusado', 'cancelado' => 'Cancelado', 'estornado' => 'Estornado', 'erro' => 'Erro'] as $valor => $label): ?>
                  <option value="<?= e($valor) ?>" <?= $statusFiltro === $valor ? 'selected' : '' ?>><?= e($label) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <button class="button" type="submit">Filtrar</button>
          </div>
        </form>
      </div>
    </section>

    <section class="metric-grid">
      <div class="stat-card stat-blue">
        <div>
          <strong><?= e(admin_money((float) $resumo['valor_total'])) ?></strong>
          <span>Total registrado</span>
          <small><?= e((string) $resumo['total']) ?> pagamentos</small>
        </div>
      </div>
      <div class="stat-card stat-green">
        <div>
          <strong><?= e(admin_money((float) $resumo['valor_motoristas'])) ?></strong>
          <span>Motoristas</span>
          <small>85% da base das corridas</small>
        </div>
      </div>
      <div class="stat-card stat-orange">
        <div>
          <strong><?= e(admin_money((float) $resumo['valor_plataforma'])) ?></strong>
          <span>Plataforma</span>
          <small>15% antes da taxa do gateway</small>
        </div>
      </div>
      <div class="stat-card stat-gold">
        <div>
          <strong><?= e((string) $resumo['pendentes']) ?></strong>
          <span>Pendentes</span>
          <small>Transacoes aguardando retorno</small>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-header">
        <h1>Configuracao Mercado Pago</h1>
        <p>Preencha as credenciais do aplicativo Mercado Pago. Segredos ja salvos ficam protegidos e nao aparecem na tela.</p>
      </div>
      <div class="panel-body">
        <form method="post" action="pagamentos_config_salvar.php">
          <div class="grid compact-grid">
            <div class="field">
              <label for="ambiente">Ambiente</label>
              <select id="ambiente" name="ambiente">
                <option value="sandbox" <?= $mpConfigNumerica['ambiente'] === 'sandbox' ? 'selected' : '' ?>>Sandbox</option>
                <option value="producao" <?= $mpConfigNumerica['ambiente'] === 'producao' ? 'selected' : '' ?>>Producao</option>
              </select>
            </div>
            <div class="field">
              <label for="taxa_gateway_percentual">Taxa estimada do gateway (%)</label>
              <input id="taxa_gateway_percentual" name="taxa_gateway_percentual" type="number" min="0" step="0.01" value="<?= e(number_format((float) $mpConfigNumerica['taxa_gateway_percentual'], 2, '.', '')) ?>">
            </div>
            <div class="field checkbox-field">
              <label>
                <input name="marketplace_ativo" type="checkbox" value="1" <?= $mpConfigNumerica['marketplace_ativo'] ? 'checked' : '' ?>>
                Marketplace ativo
              </label>
              <small>Ative somente quando as credenciais reais estiverem testadas.</small>
            </div>
          </div>

          <div class="grid compact-grid">
            <?php foreach (admin_mp_config_fields() as $chave => $field): ?>
              <?php
                $valorAtual = (string) ($mpConfigTextual[$chave]['valor'] ?? '');
                $sensivel = (bool) ($field['sensivel'] ?? false);
              ?>
              <div class="field">
                <label for="<?= e($chave) ?>"><?= e((string) $field['label']) ?></label>
                <input
                  id="<?= e($chave) ?>"
                  name="<?= e($chave) ?>"
                  type="<?= $sensivel ? 'password' : 'text' ?>"
                  value="<?= $sensivel ? '' : e($valorAtual) ?>"
                  placeholder="<?= $sensivel && $valorAtual !== '' ? 'Ja configurado. Preencha apenas para trocar.' : '' ?>"
                  autocomplete="off"
                >
                <small><?= e((string) $field['help']) ?></small>
                <?php if ($sensivel && $valorAtual !== ''): ?>
                  <small>Valor salvo: <?= e(admin_mask_secret($valorAtual)) ?></small>
                <?php endif; ?>
              </div>
            <?php endforeach; ?>
          </div>

          <div class="actions">
            <button class="button" type="submit">Salvar Mercado Pago</button>
            <a class="button secondary" href="../auth/mercado_pago_oauth_start.php?id_motorista=1" target="_blank">Testar link OAuth motorista #1</a>
          </div>
        </form>
      </div>
    </section>

    <section class="panel">
      <div class="panel-body">
        <h2 class="table-title">Transacoes de corridas</h2>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Corrida</th>
                <th>Metodo</th>
                <th>Valores</th>
                <th>Mercado Pago</th>
                <th>Status</th>
                <th>Atualizado</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($pagamentos as $p): ?>
                <tr>
                  <td>
                    <strong>#<?= e((string) $p['id_corrida']) ?></strong><br>
                    <small>Passageiro: <?= e((string) ($p['passageiro_nome'] ?? '--')) ?></small><br>
                    <small>Motorista: <?= e((string) ($p['motorista_nome'] ?? '--')) ?></small>
                  </td>
                  <td>
                    <strong><?= e(admin_pagamento_metodo_label((string) $p['metodo'])) ?></strong><br>
                    <small><?= e((string) $p['ambiente']) ?></small>
                  </td>
                  <td>
                    <strong><?= e(admin_money((float) $p['valor_total'])) ?></strong><br>
                    <small>Motorista: <?= e(admin_money((float) $p['valor_motorista'])) ?></small><br>
                    <small>Plataforma: <?= e(admin_money((float) $p['valor_plataforma'])) ?></small>
                  </td>
                  <td>
                    <small>Ref.: <?= e((string) $p['external_reference']) ?></small><br>
                    <small>Payment ID: <?= e((string) ($p['mp_payment_id'] ?: '--')) ?></small>
                  </td>
                  <td><span class="badge <?= e(admin_pagamento_status_class((string) $p['status'])) ?>"><?= e((string) $p['status']) ?></span></td>
                  <td><?= e((string) $p['atualizado_em']) ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$pagamentos): ?>
                <tr><td colspan="6">Nenhum pagamento encontrado.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-body">
        <h2 class="table-title">Contas Mercado Pago</h2>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Usuario</th>
                <th>Tipo</th>
                <th>Conta MP</th>
                <th>Status</th>
                <th>Modo</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($contas as $conta): ?>
                <tr>
                  <td>
                    <strong><?= e((string) $conta['usuario_nome']) ?></strong><br>
                    <small><?= e((string) $conta['usuario_email']) ?></small>
                  </td>
                  <td><?= e((string) $conta['tipo_usuario']) ?></td>
                  <td>
                    <strong><?= e((string) ($conta['mp_email'] ?: '--')) ?></strong><br>
                    <small>User ID: <?= e((string) ($conta['mp_user_id'] ?: '--')) ?></small>
                  </td>
                  <td><span class="badge <?= e(admin_pagamento_status_class((string) $conta['status'])) ?>"><?= e((string) $conta['status']) ?></span></td>
                  <td><?= e((string) $conta['modo']) ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$contas): ?>
                <tr><td colspan="5">Nenhuma conta Mercado Pago vinculada ainda.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-body">
        <h2 class="table-title">Ultimos webhooks</h2>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Evento</th>
                <th>Recurso</th>
                <th>Acao</th>
                <th>Processado</th>
                <th>Recebido</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($eventos as $evento): ?>
                <tr>
                  <td><?= e((string) ($evento['event_type'] ?: '--')) ?><br><small><?= e((string) ($evento['event_id'] ?: '--')) ?></small></td>
                  <td><?= e((string) ($evento['resource_id'] ?: '--')) ?></td>
                  <td><?= e((string) ($evento['acao'] ?: '--')) ?></td>
                  <td><span class="badge <?= (int) $evento['processado'] === 1 ? 'badge-ok' : 'badge-warn' ?>"><?= (int) $evento['processado'] === 1 ? 'sim' : 'nao' ?></span></td>
                  <td><?= e((string) $evento['criado_em']) ?></td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$eventos): ?>
                <tr><td colspan="5">Nenhum webhook recebido.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </section>
  </main>
</body>
</html>
<?php
function admin_pagamentos_resumo(): array
{
    if (!mp_table_exists(db(), 'pagamentos_corridas')) {
        return ['total' => 0, 'pendentes' => 0, 'valor_total' => 0, 'valor_motoristas' => 0, 'valor_plataforma' => 0];
    }

    $row = db()->query(
        'SELECT COUNT(*) AS total,
                SUM(CASE WHEN status IN ("criado", "pendente", "autorizado") THEN 1 ELSE 0 END) AS pendentes,
                COALESCE(SUM(valor_total), 0) AS valor_total,
                COALESCE(SUM(valor_motorista), 0) AS valor_motoristas,
                COALESCE(SUM(valor_plataforma), 0) AS valor_plataforma
         FROM pagamentos_corridas'
    )->fetch() ?: [];

    return [
        'total' => (int) ($row['total'] ?? 0),
        'pendentes' => (int) ($row['pendentes'] ?? 0),
        'valor_total' => round((float) ($row['valor_total'] ?? 0), 2),
        'valor_motoristas' => round((float) ($row['valor_motoristas'] ?? 0), 2),
        'valor_plataforma' => round((float) ($row['valor_plataforma'] ?? 0), 2),
    ];
}

function admin_pagamentos_listar(string $status): array
{
    if (!mp_table_exists(db(), 'pagamentos_corridas')) {
        return [];
    }

    $where = '';
    $params = [];
    if ($status !== 'todos') {
        $where = 'WHERE p.status = ?';
        $params[] = $status;
    }

    $stmt = db()->prepare(
        'SELECT p.*, pass.nome AS passageiro_nome, mot.nome AS motorista_nome,
                pass.email AS passageiro_email, mot.email AS motorista_email
         FROM pagamentos_corridas p
         LEFT JOIN usuarios pass ON pass.id = p.id_passageiro
         LEFT JOIN usuarios mot ON mot.id = p.id_motorista
         ' . $where . '
         ORDER BY p.atualizado_em DESC, p.id DESC
         LIMIT 300'
    );
    $stmt->execute($params);

    return $stmt->fetchAll();
}

function admin_mp_contas_listar(): array
{
    if (!mp_table_exists(db(), 'mercado_pago_contas')) {
        return [];
    }

    return db()->query(
        'SELECT c.*, u.nome AS usuario_nome, u.email AS usuario_email
         FROM mercado_pago_contas c
         INNER JOIN usuarios u ON u.id = c.id_usuario
         ORDER BY FIELD(c.status, "pendente", "erro", "conectado", "desconectado", "nao_conectado"), c.atualizado_em DESC
         LIMIT 300'
    )->fetchAll();
}

function admin_mp_webhooks_listar(): array
{
    if (!mp_table_exists(db(), 'pagamento_eventos_webhook')) {
        return [];
    }

    return db()->query(
        'SELECT *
         FROM pagamento_eventos_webhook
         ORDER BY criado_em DESC, id DESC
         LIMIT 30'
    )->fetchAll();
}

function admin_pagamento_status_class(string $status): string
{
    return match ($status) {
        'aprovado', 'conectado' => 'badge-ok',
        'recusado', 'cancelado', 'estornado', 'erro', 'desconectado' => 'badge-bad',
        default => 'badge-warn',
    };
}

function admin_pagamento_metodo_label(string $metodo): string
{
    return match ($metodo) {
        'pix_online' => 'Pix Online',
        'cartao_credito' => 'Cartao de credito',
        default => 'Dinheiro/Pix',
    };
}

function admin_mp_config_fields(): array
{
    return [
        'mp_client_id' => [
            'label' => 'Client ID',
            'help' => 'Identificador do app criado no Mercado Pago.',
            'sensivel' => false,
        ],
        'mp_client_secret' => [
            'label' => 'Client Secret',
            'help' => 'Segredo usado para trocar o codigo OAuth por token.',
            'sensivel' => true,
        ],
        'mp_public_key' => [
            'label' => 'Public Key',
            'help' => 'Chave publica usada no Checkout Transparente.',
            'sensivel' => false,
        ],
        'mp_access_token_plataforma' => [
            'label' => 'Access Token da plataforma',
            'help' => 'Token da conta principal Bulo para operacoes da plataforma.',
            'sensivel' => true,
        ],
        'mp_redirect_uri' => [
            'label' => 'Redirect URI OAuth',
            'help' => 'Cadastre exatamente esta URL no painel do Mercado Pago.',
            'sensivel' => false,
        ],
        'mp_webhook_url' => [
            'label' => 'Webhook URL',
            'help' => 'Cadastre esta URL para receber eventos de pagamento.',
            'sensivel' => false,
        ],
    ];
}

function admin_mask_secret(string $value): string
{
    $value = trim($value);
    if ($value === '') {
        return '--';
    }

    return str_repeat('•', 8) . substr($value, -4);
}
