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

$formId = isset($_GET['formId']) ? (int) $_GET['formId'] : (int) ($_POST['formId'] ?? 0);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    if ($formId <= 0) {
        echo json_encode(['success' => false, 'error' => 'Formulário inválido.']);
        exit;
    }

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        echo json_encode(['success' => false, 'error' => 'Nenhum arquivo enviado ou erro no upload.']);
        exit;
    }

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

    if ($campos === []) {
        echo json_encode(['success' => false, 'error' => 'Este formulário não possui campos para importar.']);
        exit;
    }

    $file = $_FILES['file']['tmp_name'];
    $importCount = 0;

    try {
        $handle = fopen($file, 'r');
        if ($handle === false) {
            throw new RuntimeException('Não foi possível abrir o arquivo.');
        }

        $primeiraLinha = fgets($handle);
        if ($primeiraLinha === false) {
            throw new RuntimeException('Arquivo vazio.');
        }

        $delimiter = substr_count($primeiraLinha, ';') >= substr_count($primeiraLinha, ',') ? ';' : ',';
        rewind($handle);

        $header = fgetcsv($handle, 0, $delimiter);
        if (!$header) {
            throw new RuntimeException('Cabeçalho inválido no CSV.');
        }
        $header[0] = preg_replace('/^\xEF\xBB\xBF/', '', (string) $header[0]);

        $pdo->beginTransaction();

        while (($data = fgetcsv($handle, 0, $delimiter)) !== false) {
            $hasContent = false;
            if ($data !== array(null)) {
                foreach ((array) $data as $item) {
                    if (trim((string) $item) !== '') {
                        $hasContent = true;
                        break;
                    }
                }
            }
            if (!$hasContent) {
                continue;
            }

            $createdAt = trim((string) ($data[1] ?? ''));
            $createdAt = $createdAt !== '' ? $createdAt : date('Y-m-d H:i:s');

            $stmtResposta = $pdo->prepare('INSERT INTO formulario_respostas (formulario_id, created_at) VALUES (:form_id, :created_at)');
            $stmtResposta->execute([
                'form_id' => $formId,
                'created_at' => $createdAt,
            ]);

            $respostaId = (int) $pdo->lastInsertId();
            $stmtCampo = $pdo->prepare('INSERT INTO formulario_respostas_campos (resposta_id, campo_id, valor) VALUES (:resposta_id, :campo_id, :valor)');

            foreach ($campos as $index => $campo) {
                $valor = trim((string) ($data[$index + 2] ?? ''));
                $stmtCampo->execute([
                    'resposta_id' => $respostaId,
                    'campo_id' => (int) $campo['id'],
                    'valor' => $valor !== '' ? $valor : null,
                ]);
            }

            $importCount++;
        }

        fclose($handle);
        $pdo->commit();

        echo json_encode(['success' => true, 'count' => $importCount]);
    } catch (Throwable $e) {
        if (isset($handle) && is_resource($handle)) {
            fclose($handle);
        }
        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }
        echo json_encode(['success' => false, 'error' => $e->getMessage()]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Importar Respostas</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="icon" type="image/png" href="img/Logo.png">
</head>
<body class="bg-gray-100 min-h-screen">
<nav class="bg-white shadow p-4 flex flex-wrap items-center justify-between gap-3">
    <h1 class="font-bold text-xl text-blue-600">Gestão</h1>
    <div class="flex flex-wrap items-center gap-4">
        <a href="home.php" class="hover:text-blue-600">Home</a>
        <a href="formularios.php" class="hover:text-blue-600">Formulários</a>
        <a href="pesquisas.php" class="hover:text-blue-600">Pesquisas</a>
        <a href="logout.php" class="text-red-500 hover:text-red-600">Sair</a>
    </div>
</nav>

<div class="max-w-3xl mx-auto p-6">
    <div class="bg-white rounded-xl shadow p-6">
        <div class="flex items-center justify-between gap-4 flex-wrap mb-6">
            <h1 class="text-2xl font-bold text-gray-800 flex items-center gap-2">
                <i class="fas fa-file-import text-blue-500"></i>
                Importar Respostas
            </h1>
            <a href="formulario_Resposta.php?id=<?= $formId ?>" class="px-4 py-2 rounded border hover:bg-gray-50">Voltar</a>
        </div>

        <div class="bg-amber-50 border-l-4 border-amber-400 p-4 rounded mb-6 text-amber-800">
            <p class="font-medium">Use um CSV exportado pelo próprio sistema.</p>
            <ul class="list-disc pl-5 mt-2 text-sm space-y-1">
                <li>Formato esperado: <strong>ID</strong>, <strong>Data de Resposta</strong> e depois os campos do formulário.</li>
                <li>O delimitador pode ser <strong>;</strong> ou <strong>,</strong>.</li>
                <li>Arquivos e imagens são importados como caminho de texto; o upload físico não é recriado.</li>
            </ul>
        </div>

        <form id="importForm" enctype="multipart/form-data" class="space-y-4">
            <input type="hidden" name="formId" value="<?= $formId ?>">
            <div class="border-2 border-dashed border-blue-400 rounded-lg p-8 text-center bg-gray-50">
                <i class="fas fa-cloud-upload-alt text-4xl text-blue-500 mb-3"></i>
                <p class="text-gray-600">Arraste e solte o CSV aqui ou</p>
                <label for="csvFile" class="cursor-pointer text-blue-500 font-medium hover:text-blue-700">
                    escolha um arquivo
                </label>
                <input type="file" id="csvFile" name="file" accept=".csv" class="hidden">
            </div>

            <div id="fileInfo" class="hidden items-center justify-between p-3 bg-gray-50 rounded border">
                <div>
                    <i class="fas fa-file-csv text-blue-500 mr-2"></i>
                    <span id="fileName" class="font-medium"></span>
                    <span id="fileSize" class="text-gray-500 text-sm ml-2"></span>
                </div>
                <button type="button" id="removeFile" class="text-red-500 hover:text-red-700">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="h-2 bg-gray-200 rounded overflow-hidden hidden" id="progressContainer">
                <div class="h-full bg-blue-500 w-0 transition-all" id="progressBar"></div>
            </div>

            <div class="flex justify-end gap-3">
                <a href="formulario_Resposta.php?id=<?= $formId ?>" class="px-4 py-2 border border-gray-300 rounded-md text-gray-700 hover:bg-gray-50">Cancelar</a>
                <button type="submit" id="importBtn" class="px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 disabled:opacity-50 disabled:cursor-not-allowed" disabled>
                    <i class="fas fa-upload mr-1"></i> Importar
                </button>
            </div>
        </form>

        <div id="resultMessage" class="mt-4 p-4 rounded-md hidden"></div>
    </div>
</div>

<script>
const fileInput = document.getElementById('csvFile');
const fileInfo = document.getElementById('fileInfo');
const fileName = document.getElementById('fileName');
const fileSize = document.getElementById('fileSize');
const removeFileBtn = document.getElementById('removeFile');
const importBtn = document.getElementById('importBtn');
const importForm = document.getElementById('importForm');
const progressContainer = document.getElementById('progressContainer');
const progressBar = document.getElementById('progressBar');
const resultMessage = document.getElementById('resultMessage');

function updateFileInfo(file) {
    fileName.textContent = file.name;
    fileSize.textContent = `${(file.size / 1024).toFixed(1)} KB`;
    fileInfo.classList.remove('hidden');
    fileInfo.classList.add('flex');
    importBtn.disabled = false;
}

fileInput.addEventListener('change', function () {
    if (this.files.length) updateFileInfo(this.files[0]);
});

removeFileBtn.addEventListener('click', function () {
    fileInput.value = '';
    fileInfo.classList.add('hidden');
    fileInfo.classList.remove('flex');
    importBtn.disabled = true;
});

importForm.addEventListener('submit', function (e) {
    e.preventDefault();

    const formData = new FormData(this);
    const xhr = new XMLHttpRequest();

    xhr.upload.addEventListener('progress', function (e) {
        if (e.lengthComputable) {
            const percentComplete = (e.loaded / e.total) * 100;
            progressBar.style.width = percentComplete + '%';
        }
    });

    xhr.addEventListener('loadstart', function () {
        progressContainer.classList.remove('hidden');
        importBtn.disabled = true;
        resultMessage.classList.add('hidden');
    });

    xhr.addEventListener('load', function () {
        progressContainer.classList.add('hidden');
        importBtn.disabled = false;

        try {
            const response = JSON.parse(xhr.responseText);
            if (response.success) {
                showResult(`Importação concluída com sucesso. ${response.count} resposta(s) importada(s).`, 'success');
            } else {
                showResult(`Erro na importação: ${response.error}`, 'error');
            }
        } catch (e) {
            showResult('Erro ao processar a resposta do servidor.', 'error');
        }
    });

    xhr.addEventListener('error', function () {
        progressContainer.classList.add('hidden');
        importBtn.disabled = false;
        showResult('Erro na conexão. Tente novamente.', 'error');
    });

    xhr.open('POST', 'importar_respostas.php', true);
    xhr.send(formData);
});

function showResult(message, type) {
    resultMessage.textContent = message;
    resultMessage.classList.remove('hidden', 'bg-green-100', 'text-green-700', 'bg-red-100', 'text-red-700');
    if (type === 'success') {
        resultMessage.classList.add('bg-green-100', 'text-green-700');
    } else {
        resultMessage.classList.add('bg-red-100', 'text-red-700');
    }
}
</script>
</body>
</html>
