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

function redirectFormularios(array $query = array())
{
    $url = 'formularios.php';
    if ($query !== array()) {
        $url .= '?' . http_build_query($query);
    }
    header('Location: ' . $url);
    exit;
}

function normalizeCategoria($categoria)
{
    $categoria = trim((string) $categoria);
    if ($categoria === '') {
        return null;
    }

    $categoriaLower = function_exists('mb_strtolower')
        ? mb_strtolower($categoria, 'UTF-8')
        : strtolower($categoria);

    return $categoriaLower === 'sem categoria' ? null : $categoria;
}

function insertRow(PDO $pdo, string $table, array $row): int
{
    if ($row === []) {
        throw new InvalidArgumentException('Nenhum dado informado para inserção.');
    }

    $columns = array_keys($row);
    $quotedColumns = array_map(function ($column) {
        return '`' . str_replace('`', '``', $column) . '`';
    }, $columns);
    $placeholders = array_map(function ($column) {
        return ':' . $column;
    }, $columns);

    $sql = sprintf(
        'INSERT INTO `%s` (%s) VALUES (%s)',
        str_replace('`', '``', $table),
        implode(', ', $quotedColumns),
        implode(', ', $placeholders)
    );

    $stmt = $pdo->prepare($sql);
    foreach ($row as $column => $value) {
        if ($value === null) {
            $stmt->bindValue(':' . $column, null, PDO::PARAM_NULL);
        } else {
            $stmt->bindValue(':' . $column, $value);
        }
    }
    $stmt->execute();

    return (int) $pdo->lastInsertId();
}

function filterDuplicableRow(array $row, array $exclude = ['id', 'created_at', 'updated_at']): array
{
    foreach ($exclude as $column) {
        unset($row[$column]);
    }
    return $row;
}

function deleteFormAndFiles(PDO $pdo, $formId)
{
    if ($formId <= 0) {
        return;
    }

    $arquivos = [];

    $pdo->beginTransaction();
    try {
        $stmtRespostas = $pdo->prepare('SELECT id FROM formulario_respostas WHERE formulario_id = :fid');
        $stmtRespostas->execute(['fid' => $formId]);
        $respostaIds = array_map('intval', $stmtRespostas->fetchAll(PDO::FETCH_COLUMN));

        if ($respostaIds !== []) {
            $placeholders = implode(',', array_fill(0, count($respostaIds), '?'));
            $stmtArquivos = $pdo->prepare(
                "SELECT frc.valor
                 FROM formulario_respostas_campos frc
                 INNER JOIN formulario_campos fc ON fc.id = frc.campo_id
                 WHERE frc.resposta_id IN ({$placeholders})
                   AND fc.tipo IN ('file', 'image')
                   AND frc.valor IS NOT NULL
                   AND frc.valor <> ''"
            );
            $stmtArquivos->execute($respostaIds);
            $arquivos = array_values(array_unique(array_filter(array_map('strval', $stmtArquivos->fetchAll(PDO::FETCH_COLUMN)))));

            $stmtDeleteCamposResposta = $pdo->prepare("DELETE FROM formulario_respostas_campos WHERE resposta_id IN ({$placeholders})");
            $stmtDeleteCamposResposta->execute($respostaIds);
        }

        $stmtDeleteRespostas = $pdo->prepare('DELETE FROM formulario_respostas WHERE formulario_id = :fid');
        $stmtDeleteRespostas->execute(['fid' => $formId]);

        $stmtDeleteCampos = $pdo->prepare('DELETE FROM formulario_campos WHERE formulario_id = :fid');
        $stmtDeleteCampos->execute(['fid' => $formId]);

        $stmtDeleteFormulario = $pdo->prepare('DELETE FROM formularios WHERE id = :fid');
        $stmtDeleteFormulario->execute(['fid' => $formId]);

        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        throw $e;
    }

    foreach ($arquivos as $arquivo) {
        $arquivo = ltrim($arquivo, '/');
        $filePath = __DIR__ . '/' . $arquivo;
        if (is_file($filePath)) {
            @unlink($filePath);
        }
    }
}

function duplicateFormulario(PDO $pdo, $formId)
{
    if ($formId <= 0) {
        return;
    }

    $pdo->beginTransaction();
    try {
        $stmtFormulario = $pdo->prepare('SELECT * FROM formularios WHERE id = :id');
        $stmtFormulario->execute(['id' => $formId]);
        $original = $stmtFormulario->fetch(PDO::FETCH_ASSOC);

        if (!$original) {
            throw new RuntimeException('Formulário não encontrado para duplicação.');
        }

        $novoFormulario = filterDuplicableRow($original);
        $novoFormulario['nome'] = rtrim((string) ($original['nome'] ?? 'Formulário')) . ' - Cópia';
        if (array_key_exists('categoria', $novoFormulario)) {
            $novoFormulario['categoria'] = normalizeCategoria((string) ($novoFormulario['categoria'] ?? ''));
        }

        $novoId = insertRow($pdo, 'formularios', $novoFormulario);

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

        foreach ($campos as $campo) {
            $novoCampo = filterDuplicableRow($campo);
            $novoCampo['formulario_id'] = $novoId;
            insertRow($pdo, 'formulario_campos', $novoCampo);
        }

        $pdo->commit();
    } catch (Throwable $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        throw $e;
    }
}

$feedback = ['type' => '', 'message' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = trim((string) ($_POST['action'] ?? ''));

    try {
        if ($action === 'criar') {
            $nome = trim((string) ($_POST['nome'] ?? ''));
            $categoria = normalizeCategoria((string) ($_POST['categoria'] ?? ''));
            $categoriaNova = normalizeCategoria((string) ($_POST['categoria_nova'] ?? ''));

            if ($categoriaNova !== null) {
                $categoria = $categoriaNova;
            }

            if ($nome === '') {
                throw new RuntimeException('Informe o nome do formulário.');
            }

            $stmt = $pdo->prepare('INSERT INTO formularios (nome, categoria) VALUES (:nome, :categoria)');
            $stmt->execute(['nome' => $nome, 'categoria' => $categoria]);

            redirectFormularios();
        }

        if ($action === 'delete') {
            $id = (int) ($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Formulário inválido para exclusão.');
            }
            deleteFormAndFiles($pdo, $id);
            redirectFormularios();
        }

        if ($action === 'duplicate') {
            $id = (int) ($_POST['id'] ?? 0);
            if ($id <= 0) {
                throw new RuntimeException('Formulário inválido para duplicação.');
            }
            duplicateFormulario($pdo, $id);
            redirectFormularios();
        }
    } catch (Throwable $e) {
        $feedback = [
            'type' => 'error',
            'message' => $e->getMessage() !== '' ? $e->getMessage() : 'Não foi possível concluir a ação agora.',
        ];
    }
}

$filtroCategoria = trim((string) ($_GET['categoria'] ?? ''));
$busca = trim((string) ($_GET['busca'] ?? ''));

$stmtCat = $pdo->query("SELECT DISTINCT COALESCE(NULLIF(TRIM(categoria), ''), 'Sem categoria') AS categoria FROM formularios ORDER BY categoria");
$categorias = $stmtCat->fetchAll(PDO::FETCH_COLUMN) ?: [];

$where = [];
$params = [];
if ($filtroCategoria !== '' && $filtroCategoria !== 'todos') {
    $where[] = "COALESCE(NULLIF(TRIM(f.categoria), ''), 'Sem categoria') = :categoria";
    $params['categoria'] = $filtroCategoria;
}
if ($busca !== '') {
    $where[] = '(f.nome LIKE :busca OR COALESCE(NULLIF(TRIM(f.categoria), ""), "Sem categoria") LIKE :busca)';
    $params['busca'] = '%' . $busca . '%';
}
$sqlWhere = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$sql = "SELECT
            f.id,
            f.nome,
            COALESCE(NULLIF(TRIM(f.categoria), ''), 'Sem categoria') AS categoria,
            (SELECT COUNT(*) FROM formulario_campos fc WHERE fc.formulario_id = f.id AND COALESCE(fc.hidden, 0) = 0 AND COALESCE(fc.tipo, '') <> 'warning') AS total_campos,
            (SELECT COUNT(*) FROM formulario_respostas fr WHERE fr.formulario_id = f.id) AS total_respostas,
            (SELECT COUNT(*) FROM formulario_respostas fr WHERE fr.formulario_id = f.id AND COALESCE(fr.lida, 0) = 0) AS nao_lidas
        FROM formularios f
        {$sqlWhere}
        ORDER BY categoria ASC, f.id DESC";
$stmt = $pdo->prepare($sql);
$stmt->execute($params);
$formularios = $stmt->fetchAll(PDO::FETCH_ASSOC) ?: [];

$grupos = [];
foreach ($formularios as $f) {
    $grupos[(string) $f['categoria']][] = $f;
}
ksort($grupos, SORT_NATURAL | SORT_FLAG_CASE);

$totalFormularios = count($formularios);
$totalNaoLidas = array_sum(array_map(static function (array $item): int {
    return (int) ($item['nao_lidas'] ?? 0);
}, $formularios));

$pageTitle = 'Formulários | Motion Fit';
include 'header.php';
?>

<style>
  .compact-btn{border-radius:.9rem;padding:.65rem .9rem;font-size:.85rem;font-weight:600}
  .compact-card{border:1px solid #e2e8f0;background:#fff;border-radius:1.25rem;padding:1rem;box-shadow:0 1px 2px rgba(15,23,42,.05)}
  .compact-scroll{max-height:calc(100vh - 280px);overflow:auto;padding-right:.25rem}
  .compact-scroll::-webkit-scrollbar{width:10px}.compact-scroll::-webkit-scrollbar-thumb{background:#cbd5e1;border-radius:999px}
  @media (max-width:1024px){.compact-scroll{max-height:none;overflow:visible;padding-right:0}}
</style>

<section class="mb-4 flex flex-wrap items-end justify-between gap-3">
    <div class="min-w-0">
        <div class="inline-flex rounded-full bg-blue-100 px-3 py-1 text-[11px] font-semibold uppercase tracking-wide text-blue-700">Administração</div>
        <h1 class="mt-2 text-2xl font-bold text-slate-900">Formulários</h1>
        <p class="mt-1 text-sm text-slate-500">Mais conteúdo na viewport, menos briga com scroll.</p>
    </div>

    <button type="button" onclick="document.getElementById('modal').classList.remove('hidden')" class="compact-btn bg-green-600 text-white shadow-sm hover:bg-green-700">
        Criar formulário
    </button>
</section>

<?php if ($feedback['message'] !== ''): ?>
    <div class="mb-4 rounded-2xl border <?= $feedback['type'] === 'error' ? 'border-red-200 bg-red-50 text-red-700' : 'border-emerald-200 bg-emerald-50 text-emerald-700' ?> px-4 py-3 text-sm">
        <?= htmlspecialchars($feedback['message'], ENT_QUOTES, 'UTF-8') ?>
    </div>
<?php endif; ?>

<section class="mb-4 grid gap-3 xl:grid-cols-[repeat(3,minmax(0,1fr))_minmax(360px,1.4fr)]">
    <div class="compact-card"><div class="text-xs text-slate-500">Formulários</div><div class="mt-1 text-2xl font-bold text-slate-900"><?= $totalFormularios ?></div></div>
    <div class="compact-card"><div class="text-xs text-slate-500">Categorias</div><div class="mt-1 text-2xl font-bold text-slate-900"><?= count($categorias) ?></div></div>
    <div class="compact-card"><div class="text-xs text-slate-500">Não lidas</div><div class="mt-1 text-2xl font-bold text-slate-900"><?= $totalNaoLidas ?></div></div>

    <form method="get" class="compact-card">
        <div class="grid gap-2 md:grid-cols-[minmax(0,1fr)_180px_auto]">
            <input type="text" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>" placeholder="Buscar por nome ou categoria" class="w-full rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
            <select name="categoria" class="w-full rounded-2xl border border-slate-300 px-3 py-2.5 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
                <option value="todos">Todas as categorias</option>
                <?php foreach ($categorias as $cat): ?>
                    <option value="<?= htmlspecialchars((string) $cat, ENT_QUOTES, 'UTF-8') ?>" <?= $filtroCategoria === $cat ? 'selected' : '' ?>><?= htmlspecialchars((string) $cat, ENT_QUOTES, 'UTF-8') ?></option>
                <?php endforeach; ?>
            </select>
            <div class="flex gap-2 md:justify-end">
                <button class="compact-btn bg-blue-600 text-white hover:bg-blue-700">Filtrar</button>
                <a href="formularios.php" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Limpar</a>
            </div>
        </div>
    </form>
</section>

<?php if (!$grupos): ?>
    <div class="rounded-3xl border border-dashed border-slate-300 bg-white p-8 text-center shadow-sm">
        <h2 class="text-xl font-bold text-slate-900">Nada encontrado</h2>
        <p class="mt-2 text-sm text-slate-500">Tente outro termo de busca ou crie um novo formulário.</p>
    </div>
<?php else: ?>
    <div class="compact-scroll space-y-4">
        <?php foreach ($grupos as $categoria => $lista): ?>
            <section class="rounded-3xl border border-slate-200 bg-white p-3 shadow-sm">
                <div class="mb-3 flex flex-wrap items-center justify-between gap-2 border-b border-slate-100 pb-2">
                    <div>
                        <h2 class="text-lg font-bold text-slate-900"><?= htmlspecialchars($categoria, ENT_QUOTES, 'UTF-8') ?></h2>
                        <p class="text-xs text-slate-500"><?= count($lista) ?> formulário(s)</p>
                    </div>
                </div>

                <div class="grid gap-3 xl:grid-cols-2">
                    <?php foreach ($lista as $f): ?>
                        <?php $publicUrl = 'formulario_view.php?id=' . (int) $f['id']; ?>
                        <article class="rounded-2xl border border-slate-200 bg-slate-50 p-4 transition hover:border-slate-300 hover:bg-white">
                            <div class="flex items-start justify-between gap-3">
                                <div class="min-w-0">
                                    <h3 class="truncate text-base font-bold text-slate-900"><?= htmlspecialchars((string) $f['nome'], ENT_QUOTES, 'UTF-8') ?></h3>
                                    <div class="mt-1 inline-flex rounded-full bg-white px-2.5 py-1 text-[11px] font-medium text-slate-600 ring-1 ring-slate-200"><?= htmlspecialchars((string) $f['categoria'], ENT_QUOTES, 'UTF-8') ?></div>
                                </div>
                                <?php if ((int) $f['nao_lidas'] > 0): ?>
                                    <span class="rounded-full bg-red-100 px-2.5 py-1 text-[11px] font-bold text-red-700"><?= (int) $f['nao_lidas'] ?> novas</span>
                                <?php endif; ?>
                            </div>

                            <div class="mt-3 grid grid-cols-2 gap-2 text-sm">
                                <div class="rounded-xl bg-white p-2.5 ring-1 ring-slate-200">
                                    <div class="text-xs text-slate-500">Campos</div>
                                    <div class="mt-1 text-lg font-bold text-slate-900"><?= (int) $f['total_campos'] ?></div>
                                </div>
                                <div class="rounded-xl bg-white p-2.5 ring-1 ring-slate-200">
                                    <div class="text-xs text-slate-500">Respostas</div>
                                    <div class="mt-1 text-lg font-bold text-slate-900"><?= (int) $f['total_respostas'] ?></div>
                                </div>
                            </div>

                            <div class="mt-3 flex flex-wrap gap-2">
                                <a href="<?= htmlspecialchars($publicUrl, ENT_QUOTES, 'UTF-8') ?>" class="compact-btn bg-slate-900 text-white hover:bg-slate-800">Abrir</a>
                                <a href="formulario_Resposta.php?id=<?= (int) $f['id'] ?>" class="compact-btn bg-blue-600 text-white hover:bg-blue-700">Respostas</a>
                                <a href="formulario_edit.php?id=<?= (int) $f['id'] ?>" class="compact-btn bg-amber-400 text-slate-900 hover:bg-amber-500">Editar</a>
                                <button type="button" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50" onclick="copiarLink('<?= htmlspecialchars($publicUrl, ENT_QUOTES, 'UTF-8') ?>')">Copiar</button>

                                <form method="post" class="contents" onsubmit="return confirm('Duplicar este formulário?')">
                                    <input type="hidden" name="action" value="duplicate">
                                    <input type="hidden" name="id" value="<?= (int) $f['id'] ?>">
                                    <button type="submit" class="compact-btn border border-slate-300 bg-white text-slate-700 hover:bg-slate-50">Duplicar</button>
                                </form>

                                <form method="post" class="contents" onsubmit="return confirm('Excluir este formulário e todas as respostas vinculadas?')">
                                    <input type="hidden" name="action" value="delete">
                                    <input type="hidden" name="id" value="<?= (int) $f['id'] ?>">
                                    <button type="submit" class="compact-btn bg-red-50 text-red-600 hover:bg-red-100">Excluir</button>
                                </form>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            </section>
        <?php endforeach; ?>
    </div>
<?php endif; ?>

<div id="modal" class="hidden fixed inset-0 z-50 flex items-center justify-center bg-slate-950/50 p-4">
    <div class="w-full max-w-lg rounded-3xl bg-white p-6 shadow-xl">
        <div class="mb-4 flex items-center justify-between gap-3">
            <div>
                <h2 class="text-xl font-bold text-slate-900">Novo formulário</h2>
                <p class="text-sm text-slate-500">Crie o esqueleto e depois ajuste os campos.</p>
            </div>
            <button type="button" onclick="document.getElementById('modal').classList.add('hidden')" class="rounded-full bg-slate-100 px-3 py-1 text-sm text-slate-600 hover:bg-slate-200">Fechar</button>
        </div>

        <form method="post" class="space-y-4">
            <input type="hidden" name="action" value="criar">
            <div>
                <label class="mb-2 block text-sm font-semibold text-slate-700">Nome do formulário</label>
                <input type="text" name="nome" placeholder="Ex.: Ficha de admissão" required class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
            </div>
            <div>
                <label class="mb-2 block text-sm font-semibold text-slate-700">Categoria existente</label>
                <select name="categoria" class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
                    <option value="">Sem categoria</option>
                    <?php foreach ($categorias as $cat): ?>
                        <option value="<?= htmlspecialchars((string) $cat, ENT_QUOTES, 'UTF-8') ?>"><?= htmlspecialchars((string) $cat, ENT_QUOTES, 'UTF-8') ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div>
                <label class="mb-2 block text-sm font-semibold text-slate-700">Ou crie nova categoria</label>
                <input type="text" name="categoria_nova" placeholder="Ex.: RH, Comercial, Onboarding" class="w-full rounded-2xl border border-slate-300 px-4 py-3 text-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-100">
            </div>
            <div class="flex flex-wrap justify-end gap-2 pt-2">
                <button type="button" onclick="document.getElementById('modal').classList.add('hidden')" class="rounded-2xl border border-slate-300 px-4 py-3 text-sm font-semibold text-slate-700 hover:bg-slate-50">Cancelar</button>
                <button type="submit" class="rounded-2xl bg-green-600 px-4 py-3 text-sm font-semibold text-white hover:bg-green-700">Salvar</button>
            </div>
        </form>
    </div>
</div>

<script>
function copiarLink(path) {
    const url = new URL(path, window.location.href).href;
    navigator.clipboard.writeText(url).then(() => {
        alert('Link copiado com sucesso.');
    }).catch(() => {
        prompt('Copie o link abaixo:', url);
    });
}
</script>

<?php include 'footer.php'; ?>
