<?php
declare(strict_types=1);

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

$statusFiltro = trim((string) ($_GET['status'] ?? 'pendente'));
$permitidos = ['todos', 'pendente', 'em_processamento', 'paga', 'reprovada', 'cancelada'];
if (!in_array($statusFiltro, $permitidos, true)) {
    $statusFiltro = 'pendente';
}

$retiradas = admin_retiradas_indicacoes($statusFiltro);
$resumo = admin_retiradas_indicacoes_resumo();
$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 - Retiradas de indicacoes</title>
  <link rel="stylesheet" href="assets/admin.css?v=20260626-1">
</head>
<body>
  <?php admin_sidebar('retiradas_indicacoes'); ?>

  <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>Retiradas de indicacoes</h1>
        <p>Pedidos feitos pelos motoristas para sacar saldo de indicacoes. Prazo operacional: até 3 dias úteis.</p>
      </div>
      <div class="panel-body">
        <form class="period-form" method="get" action="retiradas_indicacoes.php">
          <div class="filter-fields">
            <div class="field">
              <label for="status">Status</label>
              <select id="status" name="status">
                <?php foreach (['todos' => 'Todos', 'pendente' => 'Pendente', 'em_processamento' => 'Em processamento', 'paga' => 'Paga', 'reprovada' => 'Reprovada', 'cancelada' => 'Cancelada'] 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-orange">
        <div>
          <strong><?= e((string) $resumo['pendentes']) ?></strong>
          <span>Pendentes</span>
          <small><?= e(admin_money((float) $resumo['valor_pendente'])) ?></small>
        </div>
      </div>
      <div class="stat-card stat-blue">
        <div>
          <strong><?= e((string) $resumo['em_processamento']) ?></strong>
          <span>Em processamento</span>
          <small><?= e(admin_money((float) $resumo['valor_em_processamento'])) ?></small>
        </div>
      </div>
      <div class="stat-card stat-green">
        <div>
          <strong><?= e(admin_money((float) $resumo['valor_pago'])) ?></strong>
          <span>Total pago</span>
          <small><?= e((string) $resumo['pagas']) ?> retiradas</small>
        </div>
      </div>
    </section>

    <section class="panel">
      <div class="panel-body">
        <h2 class="table-title">Pedidos</h2>
        <div class="table-wrap">
          <table>
            <thead>
              <tr>
                <th>Motorista</th>
                <th>Valor</th>
                <th>Dados para pagamento</th>
                <th>Prazo</th>
                <th>Status</th>
                <th>Ações</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach ($retiradas as $r): ?>
                <tr>
                  <td>
                    <strong><?= e((string) $r['usuario_nome']) ?></strong><br>
                    <small><?= e((string) $r['usuario_email']) ?></small><br>
                    <small>Código: <?=  e((string) $r['codigoind']) ?></small>
                  </td>
                  <td><strong><?= e(admin_money((float) $r['valor'])) ?></strong><br><small>Solicitado em <?= e((string) $r['solicitado_em']) ?></small></td>
                  <td>
                    <strong>Pix:</strong> <?= e((string) ($r['pix_chave'] ?: '--')) ?> <small><?= e((string) ($r['pix_tipo'] ?: '')) ?></small><br>
                    <strong>Banco:</strong> <?= e((string) ($r['banco_nome'] ?: '--')) ?><br>
                    <small>Ag. <?= e((string) ($r['banco_agencia'] ?: '--')) ?> | Conta <?= e((string) ($r['banco_conta'] ?: '--')) ?> | <?= e((string) ($r['banco_tipo_conta'] ?: '--')) ?></small><br>
                    <small>Titular: <?= e((string) ($r['banco_titular_nome'] ?: '--')) ?> - <?= e((string) ($r['banco_titular_documento'] ?: '--')) ?></small>
                  </td>
                  <td>
                    <?= e((string) ($r['prazo_limite'] ?: '--')) ?><br>
                    <?php if (admin_retirada_atrasada($r)): ?>
                      <span class="badge badge-bad">atrasada</span>
                    <?php endif; ?>
                  </td>
                  <td>
                    <span class="badge <?= e(admin_retirada_status_class((string) $r['status'])) ?>"><?= e((string) $r['status']) ?></span><br>
                    <?php if (!empty($r['processado_por'])): ?>
                      <small>Por <?= e((string) $r['processado_por']) ?><br><?= e((string) $r['processado_em']) ?></small>
                    <?php endif; ?>
                  </td>
                  <td>
                    <form class="mini-action-form" method="post" action="retirada_indicacao_atualizar.php">
                      <input type="hidden" name="id" value="<?= e((string) $r['id']) ?>">
                      <select name="status">
                        <?php foreach (['pendente' => 'Pendente', 'em_processamento' => 'Em processamento', 'paga' => 'Paga', 'reprovada' => 'Reprovada', 'cancelada' => 'Cancelada'] as $valor => $label): ?>
                          <option value="<?= e($valor) ?>" <?= $r['status'] === $valor ? 'selected' : '' ?>><?= e($label) ?></option>
                        <?php endforeach; ?>
                      </select>
                      <textarea name="observacao" rows="2" placeholder="Observação opcional"><?= e((string) ($r['observacao'] ?? '')) ?></textarea>
                      <button class="button" type="submit">Salvar</button>
                    </form>
                  </td>
                </tr>
              <?php endforeach; ?>
              <?php if (!$retiradas): ?>
                <tr><td colspan="6">Nenhum pedido encontrado.</td></tr>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </section>
  </main>
</body>
</html>
<?php
function admin_retiradas_indicacoes(string $status): array
{
    $where = '';
    $params = [];
    if ($status !== 'todos') {
        $where = 'WHERE r.status = ?';
        $params[] = $status;
    }

    $stmt = db()->prepare(
        'SELECT r.*, u.nome AS usuario_nome, u.email AS usuario_email, u.codigoind
         FROM indicacao_retiradas r
         INNER JOIN usuarios u ON u.id = r.id_usuario
         ' . $where . '
         ORDER BY FIELD(r.status, "pendente", "em_processamento", "paga", "reprovada", "cancelada"), r.solicitado_em DESC
         LIMIT 300'
    );
    $stmt->execute($params);

    return $stmt->fetchAll();
}

function admin_retiradas_indicacoes_resumo(): array
{
    $row = db()->query(
        'SELECT
            SUM(CASE WHEN status = "pendente" THEN 1 ELSE 0 END) AS pendentes,
            SUM(CASE WHEN status = "pendente" THEN valor ELSE 0 END) AS valor_pendente,
            SUM(CASE WHEN status = "em_processamento" THEN 1 ELSE 0 END) AS em_processamento,
            SUM(CASE WHEN status = "em_processamento" THEN valor ELSE 0 END) AS valor_em_processamento,
            SUM(CASE WHEN status = "paga" THEN 1 ELSE 0 END) AS pagas,
            SUM(CASE WHEN status = "paga" THEN valor ELSE 0 END) AS valor_pago
         FROM indicacao_retiradas'
    )->fetch() ?: [];

    return [
        'pendentes' => (int) ($row['pendentes'] ?? 0),
        'valor_pendente' => round((float) ($row['valor_pendente'] ?? 0), 2),
        'em_processamento' => (int) ($row['em_processamento'] ?? 0),
        'valor_em_processamento' => round((float) ($row['valor_em_processamento'] ?? 0), 2),
        'pagas' => (int) ($row['pagas'] ?? 0),
        'valor_pago' => round((float) ($row['valor_pago'] ?? 0), 2),
    ];
}

function admin_retirada_status_class(string $status): string
{
    return match ($status) {
        'paga' => 'badge-ok',
        'reprovada', 'cancelada' => 'badge-bad',
        'em_processamento' => 'badge-muted',
        default => 'badge-warn',
    };
}

function admin_retirada_atrasada(array $retirada): bool
{
    if (!in_array((string) $retirada['status'], ['pendente', 'em_processamento'], true)) {
        return false;
    }
    if (empty($retirada['prazo_limite'])) {
        return false;
    }

    return (string) $retirada['prazo_limite'] < (new DateTimeImmutable('today'))->format('Y-m-d');
}
