<?php
declare(strict_types=1);

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

$marcas = admin_catalogo_veiculos_por_marca();
$cores = admin_catalogo_cores();
$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 - Configurações de veículos</title>
  <link rel="stylesheet" href="assets/admin.css?v=20260626-1">
</head>
<body>
  <?php admin_sidebar('configuracoes_veiculos'); ?>

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

    <section class="panel">
      <div class="panel-header">
        <h1>Catálogo de veículos</h1>
        <p>Modelos usados no cadastro do motorista. Por padrao, novos modelos entram na categoria Economica.</p>
      </div>
      <div class="panel-body">
        <form class="period-form import-form" method="post" action="salvar_configuracoes_veiculos.php">
          <input type="hidden" name="acao" value="importar_fipe">
          <div class="filter-fields">
            <div class="field">
              <label for="fipe_token">Token FIPE</label>
              <input id="fipe_token" name="fipe_token" placeholder="Opcional, se sua conta exigir">
              <small>Usado no header X-Subscription-Token.</small>
            </div>
            <div class="field">
              <label for="ano_minimo">Ano mínimo</label>
              <input id="ano_minimo" name="ano_minimo" type="number" min="2000" max="<?= e((string) ((int) date('Y') + 1)) ?>" value="<?= e((string) ((int) date('Y') - 12)) ?>">
              <small>O importador tenta puxar modelos com ano igual ou maior.</small>
            </div>
            <div class="field">
              <label for="offset_marcas">Pular marcas</label>
              <input id="offset_marcas" name="offset_marcas" type="number" min="0" step="1" value="0">
              <small>Use para continuar o próximo lote.</small>
            </div>
            <div class="field">
              <label for="limite_marcas">Marcas por lote</label>
              <input id="limite_marcas" name="limite_marcas" type="number" min="1" max="30" step="1" value="5">
              <small>5 a 10 marcas costuma ser mais seguro.</small>
            </div>
            <button class="button" type="submit">Importar FIPE</button>
          </div>
        </form>

        <hr class="soft-divider">

        <form class="period-form" method="post" action="salvar_configuracoes_veiculos.php">
          <input type="hidden" name="acao" value="adicionar_modelo">
          <div class="filter-fields">
            <div class="field">
              <label for="id_marca">Marca existente</label>
              <select id="id_marca" name="id_marca">
                <option value="">Nova marca...</option>
                <?php foreach ($marcas as $marca): ?>
                  <option value="<?= e((string) $marca['id']) ?>"><?= e((string) $marca['nome']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="field">
              <label for="nova_marca">Nova marca</label>
              <input id="nova_marca" name="nova_marca" placeholder="Ex.: Nova marca">
            </div>
            <div class="field">
              <label for="modelo">Modelo</label>
              <input id="modelo" name="modelo" placeholder="Ex.: Novo modelo" required>
            </div>
            <div class="field">
              <label>Categorias</label>
              <label class="check-line"><input type="checkbox" name="categoria_economica" value="1" checked> Economica</label>
              <label class="check-line"><input type="checkbox" name="categoria_plus" value="1"> Plus</label>
              <label class="check-line"><input type="checkbox" name="categoria_pro" value="1"> Pro</label>
            </div>
            <button class="button" type="submit">Adicionar veículo</button>
          </div>
        </form>
      </div>
    </section>

    <section class="panel">
      <div class="panel-header">
        <h1>Cores</h1>
        <p>Cores disponíveis no cadastro de veículos do motorista.</p>
      </div>
      <div class="panel-body">
        <form class="period-form" method="post" action="salvar_configuracoes_veiculos.php">
          <input type="hidden" name="acao" value="adicionar_cor">
          <div class="filter-fields">
            <div class="field">
              <label for="cor_nome">Nova cor</label>
              <input id="cor_nome" name="cor_nome" placeholder="Ex.: Azul escuro" required>
            </div>
            <button class="button" type="submit">Adicionar cor</button>
          </div>
        </form>
        <div class="tag-list">
          <?php foreach ($cores as $cor): ?>
            <span class="badge badge-muted"><?= e((string) $cor['nome']) ?></span>
          <?php endforeach; ?>
        </div>
      </div>
    </section>

    <form method="post" action="salvar_configuracoes_veiculos.php">
      <input type="hidden" name="acao" value="salvar_categorias">
      <?php foreach ($marcas as $marca): ?>
        <section class="panel">
          <div class="panel-header">
            <h1><?= e((string) $marca['nome']) ?></h1>
            <p><?= e((string) count($marca['modelos'])) ?> modelos cadastrados.</p>
          </div>
          <div class="panel-body">
            <div class="table-wrap">
              <table>
                <thead>
                  <tr>
                    <th>Modelo</th>
                    <th>Economica</th>
                    <th>Plus</th>
                    <th>Pro</th>
                    <th>Ativo</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($marca['modelos'] as $modelo): ?>
                    <tr>
                      <td>
                        <input type="hidden" name="modelos[<?= e((string) $modelo['id']) ?>][_seen]" value="1">
                        <strong><?= e((string) $modelo['nome']) ?></strong>
                      </td>
                      <td><input type="checkbox" name="modelos[<?= e((string) $modelo['id']) ?>][economica]" value="1" <?= (int) $modelo['categoria_economica'] === 1 ? 'checked' : '' ?>></td>
                      <td><input type="checkbox" name="modelos[<?= e((string) $modelo['id']) ?>][plus]" value="1" <?= (int) $modelo['categoria_plus'] === 1 ? 'checked' : '' ?>></td>
                      <td><input type="checkbox" name="modelos[<?= e((string) $modelo['id']) ?>][pro]" value="1" <?= (int) $modelo['categoria_pro'] === 1 ? 'checked' : '' ?>></td>
                      <td><input type="checkbox" name="modelos[<?= e((string) $modelo['id']) ?>][ativo]" value="1" <?= (int) $modelo['ativo'] === 1 ? 'checked' : '' ?>></td>
                    </tr>
                  <?php endforeach; ?>
                  <?php if (!$marca['modelos']): ?>
                    <tr><td colspan="5">Nenhum modelo cadastrado nesta marca.</td></tr>
                  <?php endif; ?>
                </tbody>
              </table>
            </div>
          </div>
        </section>
      <?php endforeach; ?>

      <div class="floating-actions">
        <button class="button" type="submit">Salvar categorias</button>
      </div>
    </form>
  </main>
</body>
</html>
<?php
function admin_catalogo_veiculos_por_marca(): array
{
    $stmt = db()->query(
        'SELECT ma.id AS id_marca, ma.nome AS marca_nome, ma.ativo AS marca_ativo,
                mo.id AS id_modelo, mo.nome AS modelo_nome, mo.categoria_economica,
                mo.categoria_plus, mo.categoria_pro, mo.ativo AS modelo_ativo
         FROM veiculo_marcas_catalogo ma
         LEFT JOIN veiculo_modelos_catalogo mo ON mo.id_marca = ma.id
         ORDER BY ma.nome ASC, mo.nome ASC'
    );

    $marcas = [];
    foreach ($stmt->fetchAll() as $row) {
        $idMarca = (int) $row['id_marca'];
        if (!isset($marcas[$idMarca])) {
            $marcas[$idMarca] = [
                'id' => $idMarca,
                'nome' => (string) $row['marca_nome'],
                'ativo' => (int) $row['marca_ativo'],
                'modelos' => [],
            ];
        }

        if ($row['id_modelo'] !== null) {
            $marcas[$idMarca]['modelos'][] = [
                'id' => (int) $row['id_modelo'],
                'nome' => (string) $row['modelo_nome'],
                'categoria_economica' => (int) $row['categoria_economica'],
                'categoria_plus' => (int) $row['categoria_plus'],
                'categoria_pro' => (int) $row['categoria_pro'],
                'ativo' => (int) $row['modelo_ativo'],
            ];
        }
    }

    return array_values($marcas);
}

function admin_catalogo_cores(): array
{
    return db()->query(
        'SELECT id, nome
         FROM veiculo_cores_catalogo
         WHERE ativo = 1
         ORDER BY nome ASC'
    )->fetchAll();
}
