<?php
declare(strict_types=1);

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

$q = trim((string) ($_GET['q'] ?? ''));
$rows = admin_buscar_motoristas($q, true);
$veiculosPendentes = admin_buscar_veiculos($q, true);
$flash = admin_flash();
$preview = str_replace('\\', '/', trim((string) ($_GET['preview'] ?? '')));
if (!preg_match('/^uploads\/[A-Za-z0-9_\-\/\.]+$/', $preview)) {
    $preview = '';
}
$previewExt = strtolower(pathinfo($preview, PATHINFO_EXTENSION));
$previewIsImage = in_array($previewExt, ['jpg', 'jpeg', 'png', 'gif', 'webp'], true);

function admin_pendente_preview_link(string $url, string $q): string
{
    $url = str_replace('\\', '/', trim($url));
    if ($url === '') {
        return '#';
    }

    $params = ['preview' => $url];
    if ($q !== '') {
        $params['q'] = $q;
    }

    return 'pendentes_documentos.php?' . http_build_query($params) . '#visualizador';
}
?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bulo Admin - Pendentes</title>
  <link rel="stylesheet" href="assets/admin.css?v=20260626-1">
</head>
<body>
  <?php admin_sidebar('pendentes'); ?>

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

    <section class="panel">
      <div class="panel-header">
        <h1>Documentos pendentes</h1>
        <p>Aprove ou reprove cada documento individualmente. O motorista pode entrar no app normalmente, mas so fica online quando tudo estiver aprovado.</p>
      </div>
      <div class="panel-body">
        <form method="get" action="pendentes_documentos.php" style="margin-bottom:16px;">
          <input type="text" name="q" placeholder="Pesquisar..." value="<?= e($q) ?>">
        </form>

        <div class="review-layout">
          <div class="review-list">
            <h2 style="margin: 8px 0 16px;">Documentos pessoais</h2>
            <?php foreach ($rows as $r): ?>
              <div class="panel" style="margin-bottom:14px;">
                <div class="panel-body">
              <strong><?= e($r['nome']) ?></strong> - <?= e($r['email']) ?><br>
              CPF: <?= e($r['cpf']) ?> | Celular: <?= e($r['celular']) ?><br><br>
              <div class="status-stack" style="margin-bottom:12px;">
                <span class="badge <?= admin_status_class((string) $r['cnh_status']) ?>">
                  CNH: <?= e((string) $r['cnh_status']) ?>
                </span>
                <span class="badge <?= admin_status_class((string) ($r['documento_veiculo_status_real'] ?? $r['documento_veiculo_status'])) ?>">
                  Veículo: <?=  e((string) ($r['documento_veiculo_status_real'] ?? $r['documento_veiculo_status'])) ?>
                </span>
                <span class="badge <?= admin_status_class((string) $r['selfie_status']) ?>">
                  Foto: <?= e((string) $r['selfie_status']) ?>
                </span>
                <span class="badge <?= admin_status_class((string) ($r['status_verificacao_operacional'] ?? $r['status_verificacao'])) ?>">
                  Geral: <?= e((string) ($r['status_verificacao_operacional'] ?? $r['status_verificacao'])) ?>
                </span>
                <span class="badge <?= admin_disponibilidade_class((string) $r['disponivel']) ?>">
                  <?= e((string) $r['disponivel']) === 'sim' ? 'online' : 'offline' ?>
                </span>
              </div>
              <a class="button secondary" href="<?= e(admin_pendente_preview_link((string) $r['cnh_url'], $q)) ?>">Abrir CNH</a>
              <a class="button secondary" href="<?= e(admin_pendente_preview_link((string) $r['documento_veiculo_url'], $q)) ?>">Abrir Documento Veículo</a>
              <a class="button secondary" href="<?= e(admin_pendente_preview_link((string) $r['selfie_url'], $q)) ?>">Abrir Selfie</a>
              <a class="button" href="visualizar_motorista.php?id=<?= e((string) $r['id']) ?>" style="margin-left:8px;">Visualizar cadastro</a>

              <div class="grid" style="margin-top:16px;">
                <?php
                  $documentos = [
                    ['campo' => 'cnh_status', 'observacao' => 'cnh_observacao', 'titulo' => 'CNH', 'url' => 'cnh_url', 'vencimento' => true],
                    ['campo' => 'selfie_status', 'observacao' => 'selfie_observacao', 'titulo' => 'Foto de rosto', 'url' => 'selfie_url', 'vencimento' => false],
                  ];
                ?>
                <?php foreach ($documentos as $doc): ?>
                  <div class="panel" style="box-shadow:none; border:1px solid #e6edf2;">
                    <div class="panel-body" style="padding:16px;">
                      <strong><?= e($doc['titulo']) ?></strong><br>
                      <span class="badge <?= admin_status_class((string) $r[$doc['campo']]) ?>" style="margin-top:8px;">
                        <?= e((string) $r[$doc['campo']]) ?>
                      </span>
                      <div style="margin-top:10px;">
                        <a class="button secondary" href="<?= e(admin_pendente_preview_link((string) $r[$doc['url']], $q)) ?>">Abrir arquivo</a>
                      </div>
                      <form method="post" action="revisar_motorista.php" style="margin-top:12px;">
                        <input type="hidden" name="id_motorista" value="<?= e((string) $r['id']) ?>">
                        <input type="hidden" name="campo" value="<?= e((string) $doc['campo']) ?>">
                        <?php if (!empty($doc['vencimento'])): ?>
                          <input type="date" name="vencimento" value="<?= e((string) ($r['cnh_vencimento'] ?? '')) ?>">
                        <?php endif; ?>
                        <input type="text" name="observacao" placeholder="Observação ao reprovar">
                        <div class="actions">
                          <button class="button" type="submit" name="acao" value="aprovar">Aprovar</button>
                          <button class="button secondary" type="submit" name="acao" value="reprovar">Reprovar</button>
                        </div>
                      </form>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
                </div>
              </div>
            <?php endforeach; ?>

            <h2 style="margin: 28px 0 16px;">Veículos pendentes</h2>
            <?php foreach ($veiculosPendentes as $v): ?>
              <div class="panel" style="margin-bottom:14px;">
                <div class="panel-body">
              <strong><?= e($v['motorista_nome']) ?></strong> - <?= e($v['motorista_email']) ?><br>
              <div style="margin-top:8px;">
                <?= e((string) $v['marca']) ?> <?= e((string) $v['modelo']) ?>,
                <?= e((string) $v['ano_fabricacao']) ?>/<?= e((string) $v['ano_modelo']) ?>,
                <?= e((string) $v['cor']) ?>,
                Placa <?= e((string) ($v['placa'] ?? '--')) ?>
              </div>
              <div class="status-stack" style="margin:12px 0;">
                <span class="badge <?= admin_veiculo_status_class((string) $v['status']) ?>">Veículo: <?=  e((string) $v['status']) ?></span>
              </div>
              <a class="button secondary" href="<?= e(admin_pendente_preview_link((string) $v['documento_url'], $q)) ?>">Abrir documento</a>

              <form method="post" action="revisar_veiculo.php" style="margin-top:12px;">
                <input type="hidden" name="id_veiculo" value="<?= e((string) $v['id']) ?>">
                <div class="grid">
                  <div class="field">
                    <label>Marca</label>
                    <input type="text" name="marca" value="<?= e((string) $v['marca']) ?>">
                  </div>
                  <div class="field">
                    <label>Modelo</label>
                    <input type="text" name="modelo" value="<?= e((string) $v['modelo']) ?>">
                  </div>
                  <div class="field">
                    <label>Ano fabricação</label>
                    <input type="number" name="ano_fabricacao" value="<?= e((string) $v['ano_fabricacao']) ?>">
                  </div>
                  <div class="field">
                    <label>Ano modelo</label>
                    <input type="number" name="ano_modelo" value="<?= e((string) $v['ano_modelo']) ?>">
                  </div>
                  <div class="field">
                    <label>Cor</label>
                    <input type="text" name="cor" value="<?= e((string) $v['cor']) ?>">
                  </div>
                  <div class="field">
                    <label>Placa</label>
                    <input type="text" name="placa" value="<?= e((string) ($v['placa'] ?? '')) ?>">
                  </div>
                  <div class="field">
                    <label>Vencimento do documento</label>
                    <input type="date" name="vencimento" value="<?= e((string) ($v['documento_vencimento'] ?? '')) ?>">
                  </div>
                </div>
                <input type="text" name="observacao" placeholder="Observação ao reprovar" style="margin-top:12px;">
                <div class="actions">
                  <button class="button" type="submit" name="acao" value="aprovar">Aprovar</button>
                  <button class="button secondary" type="submit" name="acao" value="reprovar">Reprovar</button>
                </div>
              </form>
                </div>
              </div>
            <?php endforeach; ?>

            <?php if (!$rows && !$veiculosPendentes): ?>
              <div class="panel"><div class="panel-body">Nenhum documento pendente encontrado.</div></div>
            <?php endif; ?>
          </div>

          <aside class="preview-pane" id="visualizador">
            <h2>Visualizador</h2>
            <?php if ($preview !== ''): ?>
              <p><?= e($preview) ?></p>
              <?php if ($previewIsImage): ?>
                <img class="preview-image" src="../<?= e($preview) ?>" alt="Documento selecionado">
              <?php else: ?>
                <iframe class="preview-frame" src="../<?= e($preview) ?>" title="Documento selecionado"></iframe>
              <?php endif; ?>
            <?php else: ?>
              <div class="preview-empty">Clique em Abrir arquivo para visualizar o documento aqui ao lado.</div>
            <?php endif; ?>
          </aside>
        </div>
      </div>
    </section>
  </main>
</body>
</html>
