<?php
	
// Функция для проверки, является ли строка потенциальным именем модели
function isPotentialModel($name) {
    if(strlen($name) < 3) return false;
    if(!preg_match('/^[a-zA-Z0-9_-]+$/', $name)) return false;
    $excludedNames = ['api', 'admin', 'css', 'js', 'img', 'cams', 'couples', 'ruletka'];
    if(in_array(strtolower($name), $excludedNames)) return false;
    return true;
}

// Функция для получения данных модели из кеша
function getCachedModelData($username) {
    $modelsCacheDir = './cache/models/';
    $modelFile = $modelsCacheDir . md5($username) . '.json';
    
    if(file_exists($modelFile)) {
        $data = json_decode(file_get_contents($modelFile), true);
        if(is_array($data) && !empty($data)) {
            return $data;
        }
    }
    return null;
}

// Функция для получения содержимого файла
function getFileContent($file, $default = '') {
    if(file_exists($file)) {
        return trim(file_get_contents($file));
    }
    return $default;
}

// Функция склонения возраста
function pluralizeAge($number) {
    $number = intval($number);
    if ($number % 100 >= 11 && $number % 100 <= 19) return 'лет';
    $last = $number % 10;
    if ($last == 1) return 'год';
    if ($last >= 2 && $last <= 4) return 'года';
    return 'лет';
}

// Функция конвертации роста в см
function convertHeightToCm($height) {
    if(preg_match('/^(\d+)\s*см$/i', $height, $matches)) {
        return $matches[1];
    }
    if(preg_match('/(\d+)\s*[\'\"]\s*(\d+)\s*[\'\"]/', $height, $matches)) {
        $feet = $matches[1];
        $inches = $matches[2] ?? 0;
        return round(($feet * 30.48) + ($inches * 2.54));
    }
    if(preg_match('/^(\d+)$/', $height, $matches)) {
        return $matches[1];
    }
    return null;
}

// Функция конвертации веса в кг
function convertWeightToKg($weight) {
    if(preg_match('/^(\d+)\s*кг$/i', $weight, $matches)) {
        return $matches[1];
    }
    if(preg_match('/^(\d+)\s*-\s*(\d+)\s*фунтов?/i', $weight, $matches)) {
        $lbs = ($matches[1] + $matches[2]) / 2;
        return round($lbs * 0.4536);
    }
    if(preg_match('/^(\d+)\s*фунтов?/i', $weight, $matches)) {
        return round($matches[1] * 0.4536);
    }
    if(preg_match('/^(\d+)$/', $weight, $matches)) {
        return $matches[1];
    }
    return null;
}

// Включим кеширование на 30 секунд для статических страниц
$cache_time = 30;
$cache_dir = './cache/';

$cache_file = $cache_dir . md5($_SERVER['REQUEST_URI']) . '.html';

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

// Проверка несуществующих страниц
$request_uri = $_SERVER['REQUEST_URI'];
$excluded_paths = ['/api/', '/admin/', '/css/', '/js/', '/img/', '/name/'];

// Список существующих страниц сайта
$existing_pages = ['/', '/couples', '/ruletka', '/chatroulette'];

// Пропускаем API запросы, существующие страницы и страницы чатов
$is_existing_page = in_array($request_uri, $existing_pages) || (strpos($request_uri, '/?') === 0);
$is_chat_page = strpos($request_uri, '/name/') !== false;
$is_api_page = strpos($request_uri, '/api/') === 0;
$has_extension = strpos($request_uri, '.') !== false;

if ($is_api_page) {
    // Пропускаем API запросы - они обрабатываются отдельно
} else if (!$is_existing_page && !$is_chat_page && !$has_extension && 
           !file_exists($_SERVER['DOCUMENT_ROOT'] . $request_uri) && 
           !is_dir($_SERVER['DOCUMENT_ROOT'] . $request_uri) &&
           !in_array($request_uri, $excluded_paths)) {
    
    error_log("404 Not Found: " . $request_uri);
    header("HTTP/1.0 404 Not Found");
    include('404.php');
    exit;
}

// Включаем буферизацию вывода для кеширования
ob_start();

// ОСНОВНАЯ ЛОГИКА - ВАШ ПАРТНЕРСКИЙ ID
$reqPath = explode('?', $_SERVER['REQUEST_URI'])[0];
$partnerId = '842667';
$pageBody = '~main.html';
$seoTitle = './seo/index/title.txt';
$seoDesc = './seo/index/desc.txt';
$seoKeys = './seo/index/keys.txt';

// Инициализируем переменные для Schema.org разметки
$schemaMarkup = null;
$useDefaultSchema = true;

// Включаем api.php ПЕРЕД основным кодом
include 'api.php';

switch($reqPath) {
    case '/api/girls':
    case '/api/couples':
        break;
    
    case '/couples':
        $seoTitle = './seo/couples/title.txt';
        $seoDesc = './seo/couples/desc.txt';
        $seoKeys = './seo/couples/keys.txt';
        $apiPath = 'couples';
        $pageBody = '~couples.html';
        include 'main.php';
        
        if (ob_get_level() > 0) {
            $content = ob_get_contents();
            file_put_contents($cache_file, $content);
        }
        exit;

    // ========== НОВЫЙ РАЗДЕЛ: Чат-рулетка ==========
    case '/ruletka':
    case '/chatroulette':
        // Создаём папку для SEO этой страницы, если её нет
        $seoDir = './seo/ruletka/';
        if(!file_exists($seoDir)) mkdir($seoDir, 0777, true);
        
        $seoTitle = $seoDir . 'title.txt';
        $seoDesc  = $seoDir . 'desc.txt';
        $seoKeys  = $seoDir . 'keys.txt';
        
        // Если файлы пустые — записываем дефолтные значения
        if(!file_exists($seoTitle) || filesize($seoTitle) == 0) {
            file_put_contents($seoTitle, 'Чат-рулетка — живое общение с реальными людьми | Runetki.space');
        }
        if(!file_exists($seoDesc) || filesize($seoDesc) == 0) {
            file_put_contents($seoDesc, 'Чат-рулетка на Runetki.space — случайные видеозвонки с девушками и парами. Общайся в реальном времени, знакомься, флиртуй. Без регистрации и анонимно.');
        }
        if(!file_exists($seoKeys) || filesize($seoKeys) == 0) {
            file_put_contents($seoKeys, 'чат-рулетка, видеочат, случайные знакомства, онлайн общение, рунетки, вебкам');
        }
        
        $apiPath = 'ruletka'; // для подсветки меню (можно оставить)
        $pageBody = '~ruletka.html';
        include 'main.php';
        
        if (ob_get_level() > 0) {
            $content = ob_get_contents();
            file_put_contents($cache_file, $content);
        }
        exit;
    
    case '/':
        $apiPath = 'girls';
        include 'main.php';
        
        if (ob_get_level() > 0) {
            $content = ob_get_contents();
            file_put_contents($cache_file, $content);
        }
        exit;
        
    default:
        if(strpos($reqPath, '/name/') !== false) {
            $girlId = str_replace('/name/', '', $reqPath);
            $girlId = trim($girlId, '/');
            $girlId = str_replace('.html', '', $girlId);
            
            $chatsList = [];
            if(file_exists('chats.json')) {
                $chatsData = file_get_contents('chats.json');
                $chatsList = json_decode($chatsData, true);
                if(!is_array($chatsList)) {
                    $chatsList = [];
                }
            }
            
            $chatUrl = '';
            $apiPath = 'girls';
            $cGirl = null;
            
            // Сначала ищем в онлайн списке
            foreach($chatsList as $value) {
                if(!is_array($value)) continue;
                
                if((isset($value['username']) && $value['username'] == $girlId) ||
                   (isset($value['display_name']) && strtolower($value['display_name']) == strtolower($girlId))) {
                    $cGirl = $value;
                    if(isset($value['chat_url']) && !empty($value['chat_url'])) {
                        $chatUrl = $value['chat_url'];
                    }
                    break;
                }
            }
            
            // Если не нашли в онлайн списке, ищем в кеше
            if(!$cGirl) {
                $cachedModel = getCachedModelData($girlId);
                if($cachedModel) {
                    $cGirl = $cachedModel;
                    $chatUrl = '';
                }
            }
            
            // Если все равно не нашли, пробуем поиск по частичному совпадению
            if(!$cGirl && isPotentialModel($girlId)) {
                foreach($chatsList as $value) {
                    if(!is_array($value)) continue;
                    
                    if(isset($value['username']) && stripos($value['username'], $girlId) !== false) {
                        $cGirl = $value;
                        if(isset($value['chat_url']) && !empty($value['chat_url'])) {
                            $chatUrl = $value['chat_url'];
                        }
                        break;
                    }
                }
            }
            
            // Если все равно не нашли, создаем базовые данные
            if(!$cGirl && isPotentialModel($girlId)) {
                $cGirl = [
                    'display_name' => $girlId,
                    'display_age' => '',
                    'username' => $girlId,
                    'gender' => 'Женщины',
                    'homecountry' => '',
                    'hometown' => '',
                    'height' => '',
                    'weight' => '',
                    'hair_color' => '',
                    'eye_color' => '',
                    'primary_language' => '',
                    'members_count' => '0',
                    'profile_images' => [
                        'thumbnail_image_medium' => '/assets/images/default-avatar.jpg',
                        'thumbnail_image_big' => '/assets/images/default-avatar.jpg'
                    ]
                ];
            }
            
            if($cGirl || isPotentialModel($girlId)) {
                if(!$cGirl) {
                    $cGirl = [
                        'display_name' => $girlId,
                        'display_age' => 'Не указан',
                        'username' => $girlId,
                        'gender' => '',
                        'homecountry' => '',
                        'hometown' => '',
                        'height' => '',
                        'weight' => '',
                        'hair_color' => '',
                        'eye_color' => '',
                        'primary_language' => '',
                        'members_count' => '',
                        'profile_images' => [
                            'thumbnail_image_medium' => '/assets/images/default-avatar.jpg',
                            'thumbnail_image_big' => '/assets/images/default-avatar.jpg'
                        ]
                    ];
                }
                
                // Убедимся, что все поля существуют
                $requiredFields = ['display_name', 'display_age', 'username', 'gender', 'homecountry', 'hometown', 'height', 'weight', 'hair_color', 'eye_color', 'primary_language', 'members_count'];
                foreach($requiredFields as $field) {
                    if(!isset($cGirl[$field])) {
                        $cGirl[$field] = '';
                    }
                }
                
                // Обработка изображений
                if(!isset($cGirl['profile_images']) || !is_array($cGirl['profile_images'])) {
                    $cGirl['profile_images'] = [];
                }
                
                $profileImages = $cGirl['profile_images'];
                $cGirl['profile_images']['thumbnail_image_medium'] = $profileImages['thumbnail_image_medium_live'] ?? 
                                                                    $profileImages['thumbnail_image_medium'] ?? 
                                                                    '/assets/images/default-avatar.jpg';
                $cGirl['profile_images']['thumbnail_image_big'] = $profileImages['thumbnail_image_big_live'] ?? 
                                                                  $profileImages['thumbnail_image_big'] ?? 
                                                                  '/assets/images/default-avatar.jpg';
                
                // Создаем папку для SEO файлов модели
                $seoDir = './seo/chats/';
                if(!file_exists($seoDir)) mkdir($seoDir, 0777, true);
                
                // Пути к файлам meta-тегов
                $seoTitleFile = $seoDir . md5($girlId) . '_title.txt';
                $seoDescFile = $seoDir . md5($girlId) . '_desc.txt';
                $seoKeysFile = $seoDir . md5($girlId) . '_keys.txt';
                
                // Путь к файлу статического описания для страницы
                $seoDescPageFile = $seoDir . md5($girlId) . '_desc_page.txt';
                
                // ============================================
                // 1. ГЕНЕРИРУЕМ META-TITLE, META-DESCRIPTION, META-KEYWORDS (ГИБРИД 1+3)
                // ============================================
                $name = $cGirl['display_name'] ?? 'Модель';
                $age = $cGirl['display_age'] ?? '';
                $hair = $cGirl['hair_color'] ?? '';
                $eyes = $cGirl['eye_color'] ?? '';
                $country = $cGirl['homecountry'] ?? '';
                $city = $cGirl['hometown'] ?? '';
                $height = $cGirl['height'] ?? '';
                $weight = $cGirl['weight'] ?? '';
                $members = $cGirl['members_count'] ?? '0';
                $gender = $cGirl['gender'] ?? '';

                // Маппинг цвета волос (для title)
                $hairMap = [
                    'светлые' => 'блондинка',
                    'светлый' => 'блондинка',
                    'темные' => 'брюнетка',
                    'темный' => 'брюнетка',
                    'тёмные' => 'брюнетка',
                    'тёмный' => 'брюнетка',
                    'русые' => 'шатенка',
                    'русый' => 'шатенка',
                    'рыжие' => 'рыжая',
                    'рыжий' => 'рыжая',
                    'черные' => 'брюнетка',
                    'черный' => 'брюнетка',
                    'каштановые' => 'шатенка',
                    'каштановый' => 'шатенка',
                    'блонд' => 'блондинка',
                    'блондинка' => 'блондинка',
                    'брюнет' => 'брюнетка',
                    'брюнетка' => 'брюнетка',
                    'шатен' => 'шатенка',
                    'шатенка' => 'шатенка'
                ];

                // Маппинг цвета глаз для title (с "с")
                $eyesMapTitle = [
                    'зеленые' => 'с зелеными глазами',
                    'зеленый' => 'с зелеными глазами',
                    'зелёные' => 'с зелеными глазами',
                    'зелёный' => 'с зелеными глазами',
                    'голубые' => 'с голубыми глазами',
                    'голубой' => 'с голубыми глазами',
                    'карие' => 'с карими глазами',
                    'карий' => 'с карими глазами',
                    'серые' => 'с серыми глазами',
                    'серый' => 'с серыми глазами',
                    'синие' => 'с синими глазами',
                    'синий' => 'с синими глазами',
                    'светлые' => 'со светлыми глазами',
                    'светлый' => 'со светлыми глазами'
                ];

                // Склонение названий стран
                $countryMap = [
                    'россия' => 'России',
                    'russia' => 'России',
                    'украина' => 'Украины',
                    'ukraine' => 'Украины',
                    'беларусь' => 'Беларуси',
                    'belarus' => 'Беларуси',
                    'казахстан' => 'Казахстана',
                    'kazakhstan' => 'Казахстана',
                    'сша' => 'США',
                    'usa' => 'США',
                    'america' => 'США',
                    'германия' => 'Германии',
                    'germany' => 'Германии',
                    'франция' => 'Франции',
                    'france' => 'Франции',
                    'италия' => 'Италии',
                    'italy' => 'Италии',
                    'испания' => 'Испании',
                    'spain' => 'Испании',
                    'англия' => 'Англии',
                    'england' => 'Англии',
                    'великобритания' => 'Великобритании',
                    'uk' => 'Великобритании',
                    'китай' => 'Китая',
                    'china' => 'Китая',
                    'япония' => 'Японии',
                    'japan' => 'Японии',
                    'индия' => 'Индии',
                    'india' => 'Индии',
                    'бразилия' => 'Бразилии',
                    'brazil' => 'Бразилии',
                    'австралия' => 'Австралии',
                    'australia' => 'Австралии'
                ];

                $cityMap = [
    'москва' => 'Москвы',
    'moscow' => 'Москвы',
    'спб' => 'Санкт-Петербурга',
    'санкт-петербург' => 'Санкт-Петербурга',
    'st petersburg' => 'Санкт-Петербурга',
    'киев' => 'Киева',
    'kyiv' => 'Киева',
    'kiev' => 'Киева',
    'минск' => 'Минска',
    'minsk' => 'Минска',
    'алматы' => 'Алматы',
    'almaty' => 'Алматы',
    'нью-йорк' => 'Нью-Йорка',
    'new york' => 'Нью-Йорка',
    'ростов' => 'Ростова',
    'ростов-на-дону' => 'Ростова-на-Дону',
    'екатеринбург' => 'Екатеринбурга',
    'новосибирск' => 'Новосибирска',
    'нижний новгород' => 'Нижнего Новгорода',
    'казань' => 'Казани',
    'челябинск' => 'Челябинска',
    'омск' => 'Омска',
    'самара' => 'Самары',
    'уфа' => 'Уфы',
    'краснодар' => 'Краснодара',
    'воронеж' => 'Воронежа',
    'пермь' => 'Перми',
    'волгоград' => 'Волгограда',
];

                // ----- TITLE (ГИБРИД 1+3) -----
                // Формат: Онлайн-чат с Имя 🔥 возраст, внешность (страна)
                $ageText = '';
                if($age && $age != 'Не указан') {
                    $ageText = $age . ' ' . pluralizeAge($age);
                }

                $appearanceText = '';
                $appearanceParts = [];
                if($hair) {
                    $hairLower = mb_strtolower(trim($hair));
                    $appearanceParts[] = $hairMap[$hairLower] ?? $hair;
                }
                if($eyes) {
                    $eyesLower = mb_strtolower(trim($eyes));
                    $appearanceParts[] = $eyesMapTitle[$eyesLower] ?? 'с ' . $eyes . ' глазами';
                }
                if(!empty($appearanceParts)) {
                    $appearanceText = implode(' ', $appearanceParts);
                }

                $countryText = '';
                if($country) {
                    $countryLower = mb_strtolower(trim($country));
                    $countryName = $countryMap[$countryLower] ?? $country;
                    $countryText = '(' . $countryName . ')';
                }

                $titleParts = [];
                $titleParts[] = 'Онлайн-чат с ' . $name . ' 🔥';
                if($ageText) {
                    $titleParts[] = $ageText;
                }
                if($appearanceText) {
                    $titleParts[] = $appearanceText;
                }
                if($countryText) {
                    $titleParts[] = $countryText;
                }

                $newTitle = implode(', ', $titleParts);
                $newTitle = trim($newTitle);
                // Убираем обрезание
// if(mb_strlen($newTitle) > 70) $newTitle = mb_substr($newTitle, 0, 67) . '...';

                // ----- DESCRIPTION (ГИБРИД 1+3) -----
                // Формат: 💬 Общайся с Имя в прямом эфире! возраст, внешность, из города/страны. Уже X+ зрителей смотрят. Приватный чат и живое общение на Runetki.space!
                $descParts = [];
                $descParts[] = '💬 Общайся с ' . $name . ' в прямом эфире!';

                $descAgeText = '';
                if($age && $age != 'Не указан') {
                    $genderText = ($gender == 'Женщины' || $gender == 'Женщина') ? 'девушка' : 'модель';
                    $descAgeText = $age . ' ' . pluralizeAge($age) . ', ';
                }

                $descAppearance = [];
                if($hair) {
                    $hairLower = mb_strtolower(trim($hair));
                    $hairMapDesc = [
                        'светлые' => 'светлыми',
                        'светлый' => 'светлыми',
                        'темные' => 'темными',
                        'темный' => 'темными',
                        'тёмные' => 'тёмными',
                        'тёмный' => 'тёмными',
                        'русые' => 'русыми',
                        'русый' => 'русыми',
                        'рыжие' => 'рыжими',
                        'рыжий' => 'рыжими',
                        'черные' => 'черными',
                        'черный' => 'черными',
                        'каштановые' => 'каштановыми',
                        'каштановый' => 'каштановыми',
                        'блонд' => 'светлыми',
                        'блондинка' => 'светлыми',
                        'брюнет' => 'темными',
                        'брюнетка' => 'темными',
                        'шатен' => 'русыми',
                        'шатенка' => 'русыми'
                    ];
                    $descAppearance[] = ($hairMapDesc[$hairLower] ?? $hair) . ' волосами';
                }
                if($eyes) {
                    $eyesLower = mb_strtolower(trim($eyes));
                    $eyesMapDesc = [
                        'зеленые' => 'зелеными',
                        'зеленый' => 'зелеными',
                        'зелёные' => 'зелеными',
                        'зелёный' => 'зелеными',
                        'голубые' => 'голубыми',
                        'голубой' => 'голубыми',
                        'карие' => 'карими',
                        'карий' => 'карими',
                        'серые' => 'серыми',
                        'серый' => 'серыми',
                        'синие' => 'синими',
                        'синий' => 'синими',
                        'светлые' => 'светлыми',
                        'светлый' => 'светлыми'
                    ];
                    $descAppearance[] = ($eyesMapDesc[$eyesLower] ?? $eyes) . ' глазами';
                }
                if($height) {
                    $heightCm = convertHeightToCm($height);
                    $descAppearance[] = 'рост ' . ($heightCm ? $heightCm . ' см' : $height);
                }
                if($weight) {
                    $weightKg = convertWeightToKg($weight);
                    $descAppearance[] = 'вес ' . ($weightKg ? $weightKg . ' кг' : $weight);
                }

                $descLocation = '';
                if($city && $country) {
    $cityLower = mb_strtolower(trim($city));
    $cityName = $cityMap[$cityLower] ?? $city;
    $countryLower = mb_strtolower(trim($country));
    $countryName = $countryMap[$countryLower] ?? $country;
    
    // Если город и страна одинаковые — показываем только одно значение
    if(mb_strtolower($cityName) == mb_strtolower($countryName)) {
        $descLocation = $cityName;
    } else {
        $descLocation = $cityName . ', ' . $countryName;
    }
} elseif($country) {
    $countryLower = mb_strtolower(trim($country));
    $countryName = $countryMap[$countryLower] ?? $country;
    $descLocation = $countryName;
}

                // Собираем описание
                $descFullParts = [];
                $descFullParts[] = '💬 Общайся с ' . $name . ' в прямом эфире!';

                $descMiddle = '';
                if($descAgeText) $descMiddle .= $descAgeText;
                if(!empty($descAppearance)) $descMiddle .= implode(', ', $descAppearance) . ', ';
                if($descLocation) $descMiddle .= $descLocation . '. ';
                $descMiddle = trim($descMiddle);

                if($descMiddle) {
                    $descFullParts[] = $descMiddle;
                }

                if($members > 50) {
                    $descFullParts[] = 'Уже ' . $members . '+ зрителей смотрят.';
                }

                $descFullParts[] = 'Приватный чат и живое общение на Runetki.space!';

                $newDescFull = implode(' ', $descFullParts);
                $newDescFull = preg_replace('/\s{2,}/', ' ', $newDescFull);
// if(mb_strlen($newDescFull) > 160) $newDescFull = mb_substr($newDescFull, 0, 157) . '...';

                // Базовое описание для сравнения (без зрителей)
                $descPartsBase = $descFullParts;
                $newDescBase = implode(' ', $descPartsBase);
                $newDescBase = preg_replace('/\s{2,}/', ' ', $newDescBase);
                if(mb_strlen($newDescBase) > 160) $newDescBase = mb_substr($newDescBase, 0, 157) . '...';

                // ----- KEYWORDS (ГИБРИД 1+3) -----
                $keysParts = [];
                $keysParts[] = 'видеочат с ' . $name;
                $keysParts[] = 'живое общение ' . $name;
                $keysParts[] = 'приватный чат онлайн';
                $keysParts[] = 'вебкам модель ' . $name;

                if($age && $age != 'Не указан') {
                    $keysParts[] = $age . ' лет';
                }

                if($hair) {
                    $hairLower = mb_strtolower(trim($hair));
                    $hairKeywords = [
                        'светлые' => 'блондинка',
                        'светлый' => 'блондинка',
                        'темные' => 'брюнетка',
                        'темный' => 'брюнетка',
                        'тёмные' => 'брюнетка',
                        'тёмный' => 'брюнетка',
                        'русые' => 'шатенка',
                        'русый' => 'шатенка',
                        'рыжие' => 'рыжая',
                        'рыжий' => 'рыжая',
                        'черные' => 'брюнетка',
                        'черный' => 'брюнетка',
                        'каштановые' => 'шатенка',
                        'каштановый' => 'шатенка'
                    ];
                    $keysParts[] = $hairKeywords[$hairLower] ?? $hair;
                }

                if($eyes) {
                    $eyesLower = mb_strtolower(trim($eyes));
                    $eyesKeywords = [
                        'зеленые' => 'зеленоглазая',
                        'зеленый' => 'зеленоглазая',
                        'зелёные' => 'зеленоглазая',
                        'зелёный' => 'зеленоглазая',
                        'голубые' => 'голубоглазая',
                        'голубой' => 'голубоглазая',
                        'карие' => 'кареглазая',
                        'карий' => 'кареглазая',
                        'серые' => 'сероглазая',
                        'серый' => 'сероглазая',
                        'синие' => 'синеглазая',
                        'синий' => 'синеглазая'
                    ];
                    $keysParts[] = $eyesKeywords[$eyesLower] ?? $eyes;
                }

                $keysParts[] = 'знакомства без регистрации';
                $keysParts[] = 'Runetki.space';

                $newKeys = implode(', ', array_slice(array_unique($keysParts), 0, 15));

                // ============================================
                // 2. СОХРАНЯЕМ META-ФАЙЛЫ (обновляем только если изменились)
                // ============================================
                $oldTitle = getFileContent($seoTitleFile);
                $oldDesc = getFileContent($seoDescFile);
                $oldKeys = getFileContent($seoKeysFile);

                if($oldTitle !== $newTitle || $oldDesc !== $newDescBase || $oldKeys !== $newKeys) {
                    file_put_contents($seoTitleFile, $newTitle);
                    file_put_contents($seoDescFile, $newDescFull);
                    file_put_contents($seoKeysFile, $newKeys);
                }

                // ============================================
                // 3. СОЗДАЕМ СТАТИЧЕСКОЕ ОПИСАНИЕ ДЛЯ СТРАНИЦЫ (если нет)
                // ============================================
                if(!file_exists($seoDescPageFile)) {
                    file_put_contents($seoDescPageFile, '');
                }

                $cGirl['desc_page_file'] = $seoDescPageFile;
                
// ============================================
// 4. ПОДКЛЮЧАЕМ СТРАНИЦУ МОДЕЛИ
// ============================================
$seoTitle = $seoTitleFile;
$seoDesc = $seoDescFile;
$seoKeys = $seoKeysFile;

$isModelPage = true; 

$pageBody = 'chat.php';
include 'main.php';
                
                if (ob_get_level() > 0) {
                    $content = ob_get_contents();
                    file_put_contents($cache_file, $content);
                }
                exit;
            } else {
                header("HTTP/1.0 404 Not Found");
                include('404.php');
                exit;
            }
        } else {
            header("HTTP/1.0 404 Not Found");
            include('404.php');
            exit;
        }
        break;
}

if (ob_get_level() > 0) {
    ob_end_flush();
}