<?php
require_once __DIR__ . '/debug_bootstrap.php';
require_once __DIR__ . '/auth.php';
require_once __DIR__ . '/db.php';
require_once __DIR__ . '/formulario_utils.php';

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

function currentListQueryFromRequest($source)
{
    $query = array();

    $busca = normalizeSearchTerm(isset($source['busca']) ? $source['busca'] : '');
    if ($busca !== '') {
        $query['busca'] = $busca;
    }

    $categoria = normalizeCategoria(isset($source['categoria']) ? $source['categoria'] : '');
    if ($categoria !== null) {
        $query['categoria'] = $categoria;
    }

    return $query;
}

function insertRow($pdo, $table, $row)
{
    return insertRowFromArray($pdo, $table, $row);
}

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

    $arquivos = array();

    $pdo->beginTransaction();
    try {
        $stmtForm = $pdo->prepare('SELECT id FROM formularios WHERE id = :id LIMIT 1');
        $stmtForm->execute(array('id' => $formId));
        if (!$stmtForm->fetchColumn()) {
            throw new RuntimeException('Formulário não encontrado para exclusão.');
        }

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

        if (!empty($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(array('fid' => $formId));

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

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

        $pdo->commit();
    } catch (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        mf_forms_log_error('DELETE_FORM', $e->getMessage(), array('id' => $formId, 'file' => $e->getFile(), 'line' => $e->getLine()));
        throw $e;
    }

    deleteStoredFiles($arquivos, __DIR__);
}

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

    $pdo->beginTransaction();
    try {
        $stmtFormulario = $pdo->prepare('SELECT * FROM formularios WHERE id = :id');
        $stmtFormulario->execute(array('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'] = truncateText(rtrim((string) (isset($original['nome']) ? $original['nome'] : 'Formulário')) . ' - Cópia', 150);
        if (array_key_exists('categoria', $novoFormulario)) {
            $novoFormulario['categoria'] = normalizeCategoria(isset($novoFormulario['categoria']) ? $novoFormulario['categoria'] : '');
        }

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

        $stmtCampos = $pdo->prepare('SELECT * FROM formulario_campos WHERE formulario_id = :id ORDER BY id ASC');
        $stmtCampos->execute(array('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 (Exception $e) {
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        mf_forms_log_error('DUPLICATE_FORM', $e->getMessage(), array('id' => $formId, 'file' => $e->getFile(), 'line' => $e->getLine()));
        throw $e;
    }
}

$feedback = array('type' => '', 'message' => '', 'open_modal' => false);
$modalValues = array('nome' => '', 'categoria' => '', 'categoria_nova' => '');

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

    try {
        if ($action === 'criar') {
            $nome = truncateText(normalizeSearchTerm(isset($_POST['nome']) ? $_POST['nome'] : ''), 150);
            $categoria = normalizeCategoria(truncateText(normalizeSearchTerm(isset($_POST['categoria']) ? $_POST['categoria'] : ''), 100));
            $categoriaNova = normalizeCategoria(truncateText(normalizeSearchTerm(isset($_POST['categoria_nova']) ? $_POST['categoria_nova'] : ''), 100));
            $modalValues = array(
                'nome' => $nome,
                'categoria' => $categoria === null ? '' : $categoria,
                'categoria_nova' => $categoriaNova === null ? '' : $categoriaNova,
            );

            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(array('nome' => $nome, 'categoria' => $categoria));

            redirectFormularios($returnQuery);
        }

        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($returnQuery);
        }

        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($returnQuery);
        }
    } catch (Exception $e) {
        $feedback = array(
            'type' => 'error',
            'message' => $e->getMessage() !== '' ? $e->getMessage() : 'Não foi possível concluir a ação agora.',
            'open_modal' => $action === 'criar',
        );
    }
}

$filtroCategoria = normalizeCategoria(isset($_GET['categoria']) ? $_GET['categoria'] : '');
$busca = normalizeSearchTerm(isset($_GET['busca']) ? $_GET['busca'] : '');

$stmtCat = $pdo->query("SELECT DISTINCT COALESCE(NULLIF(TRIM(categoria), ''), 'Sem categoria') AS categoria FROM formularios ORDER BY categoria");
$categorias = normalizeCategoryList($stmtCat->fetchAll(PDO::FETCH_COLUMN) ?: array());
$categoriasSelect = array_values(array_filter($categorias, function ($item) {
    return $item !== 'Sem categoria';
}));

if ($filtroCategoria !== null && !in_array($filtroCategoria, $categorias, true)) {
    $filtroCategoria = null;
}

$where = array();
$params = array();
if ($filtroCategoria !== null) {
    $where[] = "COALESCE(NULLIF(TRIM(f.categoria), ''), 'Sem categoria') = :categoria";
    $params['categoria'] = $filtroCategoria;
}
if ($busca !== '') {
    $where[] = "(f.nome LIKE :busca ESCAPE '\\' OR COALESCE(NULLIF(TRIM(f.categoria), ''), 'Sem categoria') LIKE :busca ESCAPE '\\')";
    $params['busca'] = '%' . escapeLike($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) ?: array();

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

$totalFormularios = count($formularios);
$totalNaoLidas = array_sum(array_map(function ($item) {
    return (int) (isset($item['nao_lidas']) ? $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" id="openCreateModal" 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="">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'] ?>">
                                    <input type="hidden" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="categoria" value="<?= htmlspecialchars((string) ($filtroCategoria === null ? '' : $filtroCategoria), ENT_QUOTES, 'UTF-8') ?>">
                                    <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'] ?>">
                                    <input type="hidden" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>">
                                    <input type="hidden" name="categoria" value="<?= htmlspecialchars((string) ($filtroCategoria === null ? '' : $filtroCategoria), ENT_QUOTES, 'UTF-8') ?>">
                                    <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" id="closeCreateModal" 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">
            <input type="hidden" name="busca" value="<?= htmlspecialchars($busca, ENT_QUOTES, 'UTF-8') ?>">
            <input type="hidden" name="categoria" value="<?= htmlspecialchars((string) ($filtroCategoria === null ? '' : $filtroCategoria), ENT_QUOTES, 'UTF-8') ?>">
            <div>
                <label class="mb-2 block text-sm font-semibold text-slate-700">Nome do formulário</label>
                <input type="text" name="nome" maxlength="150" value="<?= htmlspecialchars((string) $modalValues['nome'], ENT_QUOTES, 'UTF-8') ?>" 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 ($categoriasSelect as $cat): ?>
                        <option value="<?= htmlspecialchars((string) $cat, ENT_QUOTES, 'UTF-8') ?>" <?= $modalValues['categoria'] === $cat ? 'selected' : '' ?>><?= 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" maxlength="100" value="<?= htmlspecialchars((string) $modalValues['categoria_nova'], ENT_QUOTES, 'UTF-8') ?>" 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" id="cancelCreateModal" 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 () {
    const modal = document.getElementById('modal');
    const openBtn = document.getElementById('openCreateModal');
    const closeBtn = document.getElementById('closeCreateModal');
    const cancelBtn = document.getElementById('cancelCreateModal');

    function openModal() {
        modal.classList.remove('hidden');
    }

    function closeModal() {
        modal.classList.add('hidden');
    }

    openBtn.addEventListener('click', openModal);
    closeBtn.addEventListener('click', closeModal);
    cancelBtn.addEventListener('click', closeModal);

    modal.addEventListener('click', function (event) {
        if (event.target === modal) {
            closeModal();
        }
    });

    document.addEventListener('keydown', function (event) {
        if (event.key === 'Escape' && !modal.classList.contains('hidden')) {
            closeModal();
        }
    });

    <?php if (!empty($feedback['open_modal'])): ?>
    openModal();
    <?php endif; ?>
})();

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

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