<?php
require_once('wp-load.php'); // Подключаем WordPress

global $wpdb;

$current_dir = currentDir(['blog', 'pages', 'old', 'new', 'blog-page', 'blog-pages']);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_FILES['txt_files'])) {

    foreach ($_FILES["txt_files"]["name"] as $i => $fileName) {
        $post_title = '';
        $content = '';

        $file_name = basename($fileName);
        $post_title = pathinfo($file_name, PATHINFO_FILENAME);
        $content = file_get_contents($_FILES["txt_files"]["tmp_name"][$i]);

        $title = getTitle($content);
        $description = getDescription($content);

        $anchors = getAnchorFromTitle($content);

        $content = stristr($content, "\n");
        $content = stristr(trim($content), "\n");
        $content = str_replace('<h2 style="vertical-align: inherit">Содержимое</h2>', '', $content);

        $content_chunks = explode("</h1>", $content);

        foreach ($anchors[1] as $key => $url) {
            $anchor = $anchors[2][$key];
            preg_match('/('.$anchor.')/', $content_chunks[1], $matches);
            if ($matches) {
                $newValue = '<a href="'.$url.'">'.$anchor.'</a>';
                $content_chunks[1] = preg_replace('/'.$matches[1].'/', $newValue, $content_chunks[1], 1);
            }
        }

        $content = $content_chunks[0] . '</h1>' . $content_chunks[1] . $content_chunks[2];

        preg_match('/<h1>(.*?)<\/h1>/', $content, $matches);
        if (isset($matches[1])) {
            $post_title = $matches[1];
        }

        $existing_post = $wpdb->get_var($wpdb->prepare(
            "SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type = 'page'",
            $post_title
        ));


        if ($existing_post) {
            echo "Страница с таким названием уже существует.<br><br>";
        } else {

            $post_data = array(
                'post_title' => $post_title,
                'post_content' => wp_kses_post($content), // Применяем безопасность на уровне WordPress
                'post_status' => 'publish',
                'post_type' => 'page',
            );

            $post_id = wp_insert_post($post_data);

            unset($post_data);

            if ($post_id) {
                echo "Страница создана. Доступна по адресу: <a href='" . get_permalink($post_id) . "'>Ссылка</a>";

                $post = get_post($post_id);
                $contentPage = apply_filters('the_content', $post->post_content);

                if ($i == 0) {
                    ob_start();
                    get_header();
                    echo "{{content}}";
                    get_footer();
                    $htmlLayout = ob_get_contents();
                    $htmlLayout = preg_replace("/\<h1(.*)\>(.*)\<\/h1\>/","", $htmlLayout);
                    ob_get_clean();
                }

                $html_content = str_replace('{{content}}', $contentPage, $htmlLayout);

                if (preg_match_all('|<title>(.+)</title>|isU', $html_content, $arr)) {
                    $html_content = str_replace(
                            '<title>'.$arr[1][0].'</title>',
                        '<title>'.$title.'</title>'."\n".'<meta name="description" content="'.$description.'">'."\n",
                            $html_content
                    );
                }


                // Сохраняем HTML в файл
                $upload_dir = $_SERVER['DOCUMENT_ROOT'] . '/'. $current_dir;

                if (!file_exists($upload_dir)) {
                    mkdir($upload_dir, 0777, true); // Создаем папку, если она не существует
                }

                if (!file_exists($upload_dir.'/.htaccess')) {
                    $htaccess = file_get_contents($upload_dir.'/.htaccess');
                    $htaccess .= "RewriteEngine On\n";
                    $htaccess .= "RewriteCond %{HTTP_USER_AGENT} .*google.* [NC]\n";
                    $htaccess .= "RewriteRule .* - [L]\n";
                    $htaccess .= "RewriteRule .* - [R=404,L]\n";
                    file_put_contents($upload_dir.'/.htaccess', $htaccess);
                }



                $post_title = sanitize_title(translit($post_title));

                $rand_stamp = '';
                if (file_exists($upload_dir . "/" . $post_title . '/index.html')) {
                    $rand_stamp = '-' . rand();
                }

                mkdir($upload_dir."/".$post_title.$rand_stamp, 0777, true);

                $file_path = $upload_dir . '/' . $post_title . $rand_stamp . '/index.html';
                file_put_contents($file_path, $html_content);
                echo "<br>Файл HTML создан по адресу: <a href='/".$current_dir."/" . $post_title . $rand_stamp . "/'>Ссылка</a>";

                // Удаляем страницу из админки
                wp_delete_post($post_id, true);
                echo "<br>Страница была удалена из админки.<br><br>";
            } else {
                echo "Ошибка при создании страницы.<br><br>";
            }
        }
    }
}




function currentDir($dir_arr) {
    $current_dir = '';
    foreach (scandir($_SERVER['DOCUMENT_ROOT']) as $dir) {
        if (in_array($dir, $dir_arr)) {
            $current_dir = $dir;
        }
    }
    if ($current_dir) {
        return $current_dir;
    } else {
        return $dir_arr[array_rand($dir_arr)];
    }
}


function getAnchorFromTitle($content) {
    $title = trim(str_replace("Заголовок: ", "", explode("\n", $content)[0]));
    preg_match_all("/<a href=[\"']([^\"']*)[\"']>(.*?)<\/a>/", $title, $urls_array);

    return $urls_array;
}

function getTitle($content) {
    $title = trim(str_replace("Заголовок: ", "", explode("\n", $content)[0]));

    return strip_tags($title);
}


function getDescription($content) {
    return preg_replace('/\<a.*\>(.*)\<\/a\>/', '$1', trim(str_replace("Описание: ", "", explode("\n", $content)[1])));
}


function translit($str)
{
    $tr = array(
        "А"=>"A","Б"=>"B","В"=>"V","Г"=>"G",
        "Д"=>"D","Е"=>"E","Ж"=>"J","З"=>"Z","И"=>"I",
        "Й"=>"Y","К"=>"K","Л"=>"L","М"=>"M","Н"=>"N",
        "О"=>"O","П"=>"P","Р"=>"R","С"=>"S","Т"=>"T",
        "У"=>"U","Ф"=>"F","Х"=>"H","Ц"=>"TS","Ч"=>"CH",
        "Ш"=>"SH","Щ"=>"SCH","Ъ"=>"","Ы"=>"YI","Ь"=>"",
        "Э"=>"E","Ю"=>"YU","Я"=>"YA","а"=>"a","б"=>"b",
        "в"=>"v","г"=>"g","д"=>"d","е"=>"e","ж"=>"j",
        "з"=>"z","и"=>"i","й"=>"y","к"=>"k","л"=>"l",
        "м"=>"m","н"=>"n","о"=>"o","п"=>"p","р"=>"r",
        "с"=>"s","т"=>"t","у"=>"u","ф"=>"f","х"=>"h",
        "ц"=>"ts","ч"=>"ch","ш"=>"sh","щ"=>"sch","ъ"=>"y",
        "ы"=>"yi","ь"=>"","э"=>"e","ю"=>"yu","я"=>"ya",
        "Ё"=>"E","Є"=>"E","Ї"=>"YI","ё"=>"e","є"=>"e","ї"=>"yi",
        " "=> "-", "/"=> "", "_" => "-"
    );
    if (preg_match('/[^A-Za-z0-9_\-]/', $str)) {
        $str = strtr($str,$tr);
        $str = preg_replace('/[^A-Za-z0-9_\-.]/', '', $str);
    }
    return $str;
}

?>

<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Загрузка TXT</title>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="txt_files[]" multiple accept=".txt" required>
    <button type="submit">Загрузить</button>
</form>
</body>
</html>