<?php
include 'db.php';
include 'formulario_utils.php';

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die('Formulário inválido!');
}
$formId = (int) $_GET['id'];

$stmt = $pdo->prepare('SELECT * FROM formularios WHERE id = :id');
$stmt->execute(['id' => $formId]);
$form = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$form) {
    die('Formulário não encontrado!');
}

$stmt = $pdo->prepare('SELECT * FROM formulario_campos WHERE formulario_id = :id ORDER BY id ASC');
$stmt->execute(['id' => $formId]);
$campos = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$visibleItems = [];
foreach ($campos as $campo) {
    if ((int) ($campo['hidden'] ?? 0) === 1) {
        continue;
    }
    $visibleItems[] = $campo;
}

$fieldsPerStep = 5;
$steps = [];
$currentStep = [];
foreach ($visibleItems as $campo) {
    if (($campo['tipo'] ?? '') === 'warning') {
        if ($currentStep !== []) {
            $steps[] = $currentStep;
            $currentStep = [];
        }
        $steps[] = [$campo];
        continue;
    }

    $currentStep[] = $campo;
    if (count($currentStep) >= $fieldsPerStep) {
        $steps[] = $currentStep;
        $currentStep = [];
    }
}
if ($currentStep !== []) {
    $steps[] = $currentStep;
}
if ($steps === []) {
    $steps = [[]];
}

?>
<!doctype html>
<html lang="pt-BR">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title><?= htmlspecialchars((string) ($form['nome'] ?? 'Formulário'), ENT_QUOTES, 'UTF-8') ?></title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script src="https://unpkg.com/imask"></script>
  <link rel="icon" type="image/png" href="img/Logo.png">
  <style>
    @keyframes blob {0%,100%{transform:translate(0,0) scale(1)}33%{transform:translate(30px,-50px) scale(1.1)}66%{transform:translate(-20px,20px) scale(0.9)}}
    .animate-blob{animation:blob 20s infinite}
    .form-step{transition:opacity .35s ease, transform .35s ease}
    .form-step.hidden{opacity:0;transform:translateX(24px);pointer-events:none;position:absolute;width:100%}
    .form-step.active{opacity:1;transform:translateX(0);pointer-events:auto;position:relative}
    .error-msg{color:#dc2626;font-size:.875rem;margin-top:.35rem}
  </style>
</head>
<body class="min-h-screen bg-slate-100 px-4 py-10 sm:px-6 lg:px-8">
  <div class="hidden sm:block absolute left-10 top-10 h-80 w-80 rounded-full bg-pink-300/40 blur-3xl animate-blob"></div>
  <div class="hidden sm:block absolute right-10 top-32 h-80 w-80 rounded-full bg-blue-300/40 blur-3xl animate-blob"></div>

  <div class="relative mx-auto w-full max-w-4xl rounded-3xl bg-white p-6 shadow-2xl sm:p-8">
    <h1 class="text-center text-2xl font-bold text-slate-900 sm:text-3xl"><?= htmlspecialchars((string) ($form['nome'] ?? 'Formulário'), ENT_QUOTES, 'UTF-8') ?></h1>
    <div class="mt-5 h-2 w-full overflow-hidden rounded-full bg-slate-200">
      <div id="progressBar" class="h-2 w-0 rounded-full bg-blue-600 transition-all duration-500"></div>
    </div>

    <form id="multiStepForm" method="post" enctype="multipart/form-data" action="processa_formulario.php?id=<?= $formId ?>" class="relative mt-6 space-y-4">
      <?php foreach ($steps as $index => $stepFields): ?>
        <div class="form-step <?= $index === 0 ? 'active' : 'hidden' ?>">
          <?php if ($stepFields === []): ?>
            <div class="rounded-2xl border border-dashed border-slate-300 bg-slate-50 p-6 text-center text-slate-500">Nenhum campo disponível neste formulário.</div>
          <?php endif; ?>

          <?php foreach ($stepFields as $campo): ?>
            <?php
              $type = (string) ($campo['tipo'] ?? 'text');
              $label = (string) ($campo['label'] ?? 'Campo');
              $required = (int) ($campo['required'] ?? 0) === 1;
              $fieldName = 'campo_' . (int) $campo['id'];
              $maskAttr = '';
              $maxLength = '';
              if ($type === 'cpf') {
                  $maskAttr = 'data-mask="cpf"';
                  $maxLength = '14';
              } elseif ($type === 'cnpj') {
                  $maskAttr = 'data-mask="cnpj"';
                  $maxLength = '18';
              } elseif ($type === 'telefone') {
                  $maskAttr = 'data-mask="phone"';
                  $maxLength = '15';
              } elseif ($type === 'cep') {
                  $maskAttr = 'data-mask="cep"';
                  $maxLength = '9';
              } elseif ($type === 'rg') {
                  $maskAttr = 'data-mask="rg"';
                  $maxLength = '12';
              }
            ?>

            <?php if ($type === 'warning'): ?>
              <div class="mb-4 rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm leading-6 text-amber-900">
                <?= nl2br(htmlspecialchars($label, ENT_QUOTES, 'UTF-8')) ?>
              </div>
              <?php continue; ?>
            <?php endif; ?>

            <div class="mb-4 flex flex-col">
              <label class="mb-2 font-semibold text-slate-700"><?= htmlspecialchars($label, ENT_QUOTES, 'UTF-8') ?><?= $required ? ' *' : '' ?></label>

              <?php if ($type === 'porcentagem'): ?>
                <div class="relative">
                  <input type="number" name="<?= $fieldName ?>" min="0" max="100" step="0.01" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 pr-10 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">
                  <span class="absolute right-3 top-1/2 -translate-y-1/2 font-semibold text-slate-500">%</span>
                </div>

              <?php elseif (in_array($type, ['text', 'cpf', 'cnpj', 'telefone', 'cep', 'rg'], true)): ?>
                <input type="text" name="<?= $fieldName ?>" <?= $required ? 'required' : '' ?> <?= $maskAttr ?> <?= $maxLength !== '' ? 'maxlength="' . $maxLength . '"' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">

              <?php elseif ($type === 'email'): ?>
                <input type="email" name="<?= $fieldName ?>" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">

              <?php elseif ($type === 'date'): ?>
                <input type="date" name="<?= $fieldName ?>" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">

              <?php elseif ($type === 'number'): ?>
                <input type="number" name="<?= $fieldName ?>" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">

              <?php elseif ($type === 'textarea'): ?>
                <textarea name="<?= $fieldName ?>" rows="4" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base"></textarea>

              <?php elseif ($type === 'select'): ?>
                <select name="<?= $fieldName ?>" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">
                  <option value="">Selecione</option>
                  <?php foreach (splitOptions($campo['opcoes'] ?? null) as $op): ?>
                    <option value="<?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?></option>
                  <?php endforeach; ?>
                </select>

              <?php elseif (in_array($type, ['radio', 'checkbox'], true)): ?>
                <div class="flex flex-wrap gap-3" data-required-group="<?= $required ? '1' : '0' ?>" data-field-name="<?= $fieldName . ($type === 'checkbox' ? '[]' : '') ?>">
                  <?php foreach (splitOptions($campo['opcoes'] ?? null) as $op): ?>
                    <label class="flex cursor-pointer items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 transition hover:border-blue-300 hover:bg-blue-50">
                      <input type="<?= $type ?>" name="<?= $fieldName ?><?= $type === 'checkbox' ? '[]' : '' ?>" value="<?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?>" class="h-4 w-4 accent-blue-600">
                      <span class="text-sm text-slate-700"><?= htmlspecialchars($op, ENT_QUOTES, 'UTF-8') ?></span>
                    </label>
                  <?php endforeach; ?>
                </div>

              <?php elseif (in_array($type, ['image', 'file'], true)): ?>
                <input type="file" name="<?= $fieldName ?>" accept="<?= htmlspecialchars(getFileInputAccept($type), ENT_QUOTES, 'UTF-8') ?>" <?= $required ? 'required' : '' ?> class="w-full rounded-2xl border border-slate-300 p-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100 sm:text-base">
              <?php endif; ?>
            </div>
          <?php endforeach; ?>
        </div>
      <?php endforeach; ?>

      <div class="mt-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
        <button type="button" id="prevBtn" class="hidden w-full rounded-2xl bg-slate-300 px-6 py-3 font-semibold text-slate-800 transition hover:bg-slate-400 sm:w-auto">Anterior</button>
        <button type="button" id="nextBtn" class="w-full rounded-2xl bg-blue-600 px-6 py-3 font-semibold text-white transition hover:bg-blue-700 sm:w-auto">Próximo</button>
        <button type="submit" id="submitBtn" class="hidden w-full items-center justify-center gap-2 rounded-2xl bg-emerald-600 px-6 py-3 font-semibold text-white transition hover:bg-emerald-700 sm:w-auto">
          <span id="submitText">Enviar</span>
          <svg id="loadingSpinner" class="hidden h-5 w-5 animate-spin text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8H4z"></path>
          </svg>
        </button>
      </div>
    </form>
  </div>

<script>
let currentStep = 0;
const steps = Array.from(document.querySelectorAll('.form-step'));
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');
const submitBtn = document.getElementById('submitBtn');
const progressBar = document.getElementById('progressBar');
const form = document.getElementById('multiStepForm');

function showStep(index) {
  steps.forEach((step, i) => {
    step.classList.remove('active', 'hidden');
    step.classList.add(i === index ? 'active' : 'hidden');
  });
  prevBtn.style.display = index === 0 ? 'none' : 'inline-block';
  nextBtn.style.display = index === steps.length - 1 ? 'none' : 'inline-block';
  submitBtn.style.display = index === steps.length - 1 ? 'flex' : 'none';
  progressBar.style.width = `${((index + 1) / steps.length) * 100}%`;
}
showStep(currentStep);

document.querySelectorAll('input[data-mask]').forEach((input) => {
  const mask = input.getAttribute('data-mask');
  if (mask === 'cpf') IMask(input, { mask: '000.000.000-00' });
  if (mask === 'cnpj') IMask(input, { mask: '00.000.000/0000-00' });
  if (mask === 'phone') IMask(input, { mask: '(00) 00000-0000' });
  if (mask === 'cep') IMask(input, { mask: '00000-000' });
  if (mask === 'rg') IMask(input, { mask: '00.000.000-0' });
});

function clearStepErrors(step) {
  step.querySelectorAll('.error-msg').forEach((element) => element.remove());
  step.querySelectorAll('.border-red-500').forEach((element) => element.classList.remove('border-red-500'));
}

function appendError(target, message) {
  const error = document.createElement('span');
  error.className = 'error-msg';
  error.textContent = message;
  target.appendChild(error);
}

function validateStep(index) {
  const step = steps[index];
  let valid = true;
  let firstInvalid = null;
  clearStepErrors(step);

  step.querySelectorAll('[required]').forEach((element) => {
    const value = element.type === 'file' ? '' : (element.value || '').trim();
    const emptyFile = element.type === 'file' && (!element.files || element.files.length === 0);
    if (value === '' || emptyFile) {
      element.classList.add('border-red-500');
      appendError(element.parentNode, 'Este campo é obrigatório.');
      valid = false;
      if (!firstInvalid) firstInvalid = element;
    }
  });

  step.querySelectorAll('[data-required-group="1"]').forEach((group) => {
    const name = group.getAttribute('data-field-name');
    const inputs = Array.from(group.querySelectorAll(`input[name="${CSS.escape(name)}"]`));
    const anyChecked = inputs.some((input) => input.checked);
    if (!anyChecked) {
      appendError(group.parentNode, 'Selecione pelo menos uma opção.');
      valid = false;
      if (!firstInvalid && inputs[0]) firstInvalid = inputs[0];
    }
  });

  if (firstInvalid) {
    setTimeout(() => {
      firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
      firstInvalid.focus();
    }, 120);
  }

  return valid;
}

function validateAllSteps() {
  for (let i = 0; i < steps.length; i += 1) {
    if (!validateStep(i)) {
      currentStep = i;
      showStep(currentStep);
      return false;
    }
  }
  return true;
}

nextBtn.addEventListener('click', () => {
  if (validateStep(currentStep) && currentStep < steps.length - 1) {
    currentStep += 1;
    showStep(currentStep);
  }
});

prevBtn.addEventListener('click', () => {
  if (currentStep > 0) {
    currentStep -= 1;
    showStep(currentStep);
  }
});

form.addEventListener('submit', (event) => {
  if (!validateAllSteps()) {
    event.preventDefault();
    return;
  }
  document.getElementById('submitText').textContent = 'Enviando...';
  document.getElementById('loadingSpinner').classList.remove('hidden');
  submitBtn.disabled = true;
});
window.addEventListener('pageshow', () => {
  submitBtn.disabled = false;
  document.getElementById('submitText').textContent = 'Enviar';
  document.getElementById('loadingSpinner').classList.add('hidden');
});
</script>
</body>
</html>
