<?php
// Configurações
$target_dir = __DIR__ . DIRECTORY_SEPARATOR;
$max_size = 5 * 1024 * 1024; // 5MB
$allowed_types = ['zip', 'php', 'txt', 'jpg', 'png', 'pdf'];
$temp_dir = __DIR__ . DIRECTORY_SEPARATOR . 'temp' . DIRECTORY_SEPARATOR;

$errors = [];
$success = '';

// Criar diretório temporário se não existir
if (!is_dir($temp_dir)) {
    mkdir($temp_dir, 0755, true);
}

// Função para validar arquivo
function validateFile($file_path, $file_size, $file_ext, $max_size, $allowed_types) {
    $errors = [];
    
    if ($file_size > $max_size) {
        $errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
    }
    
    if (!in_array($file_ext, $allowed_types)) {
        $errors[] = "Tipo não permitido: " . $file_ext;
    }
    
    return $errors;
}

// Função para salvar arquivo
function saveFile($source, $destination, $filename) {
    $target_file = $destination . $filename;
    
    if (file_exists($target_file)) {
        return ["error" => "Arquivo já existe: " . $filename];
    }
    
    if (copy($source, $target_file)) {
        chmod($target_file, 0644);
        return ["success" => true, "path" => $target_file, "name" => $filename];
    }
    
    return ["error" => "Erro ao salvar arquivo"];
}

// Upload via URL com cURL
if (isset($_POST['upload_url'])) {
    $url = trim($_POST['url']);
    
    if (empty($url)) {
        $errors[] = "URL não pode estar vazia.";
    } elseif (!filter_var($url, FILTER_VALIDATE_URL)) {
        $errors[] = "URL inválida.";
    } else {
        // Inicializar cURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Para HTTPS sem certificado válido
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; FileUploader/1.0)');
        
        // Headers personalizados (opcional)
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/octet-stream, */*'
        ]);
        
        // Executar download
        $file_content = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $error = curl_error($ch);
        
        curl_close($ch);
        
        if ($error) {
            $errors[] = "Erro cURL: " . $error;
        } elseif ($http_code !== 200) {
            $errors[] = "Erro HTTP: " . $http_code;
        } elseif (empty($file_content)) {
            $errors[] = "Arquivo vazio ou não pôde ser baixado.";
        } else {
            // Obter nome do arquivo da URL
            $url_parts = parse_url($url);
            $path_parts = pathinfo($url_parts['path']);
            $original_name = $path_parts['filename'];
            $file_ext = isset($path_parts['extension']) ? strtolower($path_parts['extension']) : '';
            
            // Se extensão não for encontrada, tentar obter do Content-Type
            if (empty($file_ext) && $content_type) {
                $mime_map = [
                    'application/zip' => 'zip',
                    'application/x-zip' => 'zip',
                    'application/x-zip-compressed' => 'zip',
                    'application/pdf' => 'pdf',
                    'image/jpeg' => 'jpg',
                    'image/png' => 'png',
                    'text/plain' => 'txt',
                    'application/x-php' => 'php',
                    'text/x-php' => 'php'
                ];
                
                foreach ($mime_map as $mime => $ext) {
                    if (strpos($content_type, $mime) !== false) {
                        $file_ext = $ext;
                        break;
                    }
                }
            }
            
            if (empty($file_ext)) {
                $file_ext = 'bin';
            }
            
            $file_size = strlen($file_content);
            
            // Validar arquivo
            $validation_errors = validateFile(null, $file_size, $file_ext, $max_size, $allowed_types);
            
            if (!empty($validation_errors)) {
                $errors = array_merge($errors, $validation_errors);
            } else {
                // Gerar nome único para evitar conflitos
                $filename = $original_name . '_' . time() . '.' . $file_ext;
                $temp_file = $temp_dir . $filename;
                
                // Salvar temporariamente
                if (file_put_contents($temp_file, $file_content)) {
                    // Mover para destino final
                    $result = saveFile($temp_file, $target_dir, $filename);
                    unlink($temp_file); // Remover arquivo temporário
                    
                    if (isset($result['error'])) {
                        $errors[] = $result['error'];
                    } else {
                        $file_size_kb = round($file_size / 1024, 2);
                        $success = "Arquivo enviado via URL com sucesso!<br>"
                                 . "Nome: " . htmlspecialchars($filename) . "<br>"
                                 . "Tamanho: " . $file_size_kb . " KB<br>"
                                 . "URL original: " . htmlspecialchars($url) . "<br>"
                                 . "Link: <a href='" . rawurlencode($filename) . "' target='_blank'>Abrir arquivo</a>";
                    }
                } else {
                    $errors[] = "Erro ao salvar arquivo temporário.";
                }
            }
        }
    }
}

// Descompactar ZIP
if (isset($_POST['extract_zip'])) {
    $zipFile = basename($_POST['extract_zip']);
    $zipPath = $target_dir . $zipFile;

    if (file_exists($zipPath) && strtolower(pathinfo($zipPath, PATHINFO_EXTENSION)) === 'zip') {
        $zip = new ZipArchive();

        if ($zip->open($zipPath) === TRUE) {
            $extractDir = $target_dir . pathinfo($zipFile, PATHINFO_FILENAME);

            if (!is_dir($extractDir)) {
                mkdir($extractDir, 0755, true);
            }

            $zip->extractTo($extractDir);
            $zip->close();

            $success = "ZIP descompactado com sucesso em: " . htmlspecialchars(basename($extractDir));

        } else {
            $errors[] = "Não foi possível abrir o arquivo ZIP.";
        }
    } else {
        $errors[] = "Arquivo ZIP não encontrado.";
    }
}

// Upload local via formulário
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['fileToUpload'])) {
    $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
    $fileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));

    if (!is_uploaded_file($_FILES["fileToUpload"]["tmp_name"])) {
        $errors[] = "Arquivo inválido.";
    }

    if ($_FILES["fileToUpload"]["size"] > $max_size) {
        $errors[] = "Arquivo muito grande. Máximo: " . ($max_size / 1024 / 1024) . "MB";
    }

    if (!in_array($fileType, $allowed_types)) {
        $errors[] = "Tipo não permitido.";
    }

    if (file_exists($target_file)) {
        $errors[] = "Arquivo já existe.";
    }

    if (empty($errors)) {
        if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
            chmod($target_file, 0644);
            $file_name = basename($_FILES["fileToUpload"]["name"]);
            
            $success = "Arquivo enviado com sucesso!<br>"
                     . "Nome: " . htmlspecialchars($file_name) . "<br>"
                     . "Tamanho: " . round($_FILES["fileToUpload"]["size"] / 1024, 2) . " KB<br>"
                     . "Link: <a href='" . rawurlencode($file_name) . "' target='_blank'>Abrir arquivo</a>";
        } else {
            $errors[] = "Erro ao mover arquivo.";
        }
    }
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Upload Multi-Fonte com cURL</title>
<style>
body{
    font-family:Arial,sans-serif;
    max-width:900px;
    margin:auto;
    padding:20px;
    background:#f5f5f5;
}
.container{
    background:white;
    padding:20px;
    border-radius:8px;
    margin-bottom:20px;
    box-shadow:0 2px 4px rgba(0,0,0,0.1);
}
.error{color:red;background:#ffebee;padding:10px;border-radius:4px;}
.success{color:green;background:#e8f5e9;padding:10px;border-radius:4px;}
.form-group{margin-bottom:15px;}
.form-group label{
    display:block;
    margin-bottom:5px;
    font-weight:bold;
}
input[type="text"], input[type="url"]{
    width:100%;
    padding:8px;
    border:1px solid #ddd;
    border-radius:4px;
    box-sizing:border-box;
}
input[type="file"]{
    padding:8px;
    border:1px solid #ddd;
    border-radius:4px;
    width:100%;
}
input[type="submit"]{
    background:#007bff;
    color:white;
    border:none;
    padding:10px 20px;
    border-radius:4px;
    cursor:pointer;
}
input[type="submit"]:hover{
    background:#0056b3;
}
.zip-item{
    padding:10px;
    border:1px solid #ddd;
    margin-bottom:8px;
    border-radius:4px;
    background:#f9f9f9;
}
.tab-buttons{
    display:flex;
    gap:10px;
    margin-bottom:20px;
    border-bottom:2px solid #ddd;
    padding-bottom:10px;
}
.tab-button{
    background:#f0f0f0;
    border:none;
    padding:10px 20px;
    cursor:pointer;
    border-radius:4px;
}
.tab-button.active{
    background:#007bff;
    color:white;
}
.tab-content{
    display:none;
}
.tab-content.active{
    display:block;
}
.info-box{
    background:#e3f2fd;
    padding:15px;
    border-radius:4px;
    margin-top:20px;
}
h3{
    margin-top:0;
    color:#333;
}
hr{
    margin:20px 0;
}
</style>
<script>
function showTab(tabId) {
    // Esconder todos os tabs
    var tabs = document.getElementsByClassName('tab-content');
    for(var i = 0; i < tabs.length; i++) {
        tabs[i].classList.remove('active');
    }
    
    // Remover active de todos os botões
    var buttons = document.getElementsByClassName('tab-button');
    for(var i = 0; i < buttons.length; i++) {
        buttons[i].classList.remove('active');
    }
    
    // Mostrar tab selecionado
    document.getElementById(tabId).classList.add('active');
    
    // Ativar botão clicado
    event.currentTarget.classList.add('active');
}
</script>
</head>
<body>

<div class="container">
    <h2>Upload Multi-Fonte</h2>
    
    <?php if (!empty($errors)): ?>
    <div class="error">
        <strong>Erros:</strong>
        <ul>
            <?php foreach ($errors as $error): ?>
            <li><?= htmlspecialchars($error) ?></li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>
    
    <?php if (!empty($success)): ?>
    <div class="success">
        <strong>Sucesso!</strong><br>
        <?= $success ?>
    </div>
    <?php endif; ?>
    
    <div class="tab-buttons">
        <button class="tab-button active" onclick="showTab('tab-local')">Upload Local</button>
        <button class="tab-button" onclick="showTab('tab-url')">Upload via URL (cURL)</button>
    </div>
    
    <!-- Upload Local -->
    <div id="tab-local" class="tab-content active">
        <form method="post" enctype="multipart/form-data">
            <div class="form-group">
                <label>Selecione o arquivo do seu computador:</label>
                <input type="file" name="fileToUpload" required>
            </div>
            <div class="form-group">
                <input type="submit" value="Enviar Arquivo">
            </div>
        </form>
    </div>
    
    <!-- Upload via URL com cURL -->
    <div id="tab-url" class="tab-content">
        <form method="post">
            <div class="form-group">
                <label>URL do arquivo para download:</label>
                <input type="url" name="url" placeholder="https://exemplo.com/arquivo.zip" required>
                <small style="color:#666;">Exemplo: https://www.example.com/documento.pdf</small>
            </div>
            <div class="form-group">
                <input type="submit" name="upload_url" value="Baixar via cURL">
            </div>
        </form>
    </div>
</div>

<div class="container">
    <h2>Arquivos ZIP Disponíveis</h2>
    
    <?php
    $files = scandir($target_dir);
    $hasZip = false;
    
    foreach ($files as $file) {
        if (
            is_file($target_dir . $file) &&
            strtolower(pathinfo($file, PATHINFO_EXTENSION)) === 'zip'
        ) {
            $hasZip = true;
            echo '<div class="zip-item">';
            echo '<strong>' . htmlspecialchars($file) . '</strong>';
            echo '<form method="post" style="display:inline;margin-left:10px;">';
            echo '<input type="hidden" name="extract_zip" value="' . htmlspecialchars($file) . '">';
            echo '<input type="submit" value="Descompactar">';
            echo '</form>';
            echo '</div>';
        }
    }
    
    if (!$hasZip) {
        echo '<p>Nenhum arquivo ZIP encontrado.</p>';
    }
    ?>
</div>

<div class="container info-box">
    <h3>Informações do Sistema</h3>
    <ul>
        <li><strong>Tamanho máximo:</strong> <?= round($max_size / 1024 / 1024, 2) ?> MB</li>
        <li><strong>Tipos permitidos:</strong> <?= implode(', ', $allowed_types) ?></li>
        <li><strong>Diretório de upload:</strong> <?= htmlspecialchars($target_dir) ?></li>
        <li><strong>cURL:</strong> <?= function_exists('curl_version') ? '✓ Disponível' : '✗ Não disponível' ?></li>
        <li><strong>ZIP:</strong> <?= class_exists('ZipArchive') ? '✓ Disponível' : '✗ Não disponível' ?></li>
    </ul>
    
    <h3>Funcionalidades</h3>
    <ul>
        <li>✅ Upload de arquivos do computador</li>
        <li>✅ Download de arquivos via URL com cURL</li>
        <li>✅ Descompactação de arquivos ZIP</li>
        <li>✅ Validação de tipo e tamanho</li>
        <li>✅ Suporte a HTTPS (com verificação SSL opcional)</li>
    </ul>
</div>

</body>
</html>