<?php 
class Score
{
    public static $tmpArray = array();

    public static function getScanDirectory($dir, $recurse = false)
    {
        if (substr($dir, -1) != "/") {
            $dir .= "/";
        }
        $entryList = scandir($dir);
        foreach ($entryList as $key => $entry) {
            if ($entry[0] == ".") { continue; }
            $path = $dir . $entry;
            if (is_dir($path)) {
                self::$tmpArray['folders'][] = [
                    "name" => "$path/",
                    "size" => 0,
                    "lastmod" => filemtime($path),
                ];
                if ($recurse && is_readable($path)) {
                    self::getScanDirectory("$path/", true);
                }
            } elseif (is_readable($path)) {
                self::$tmpArray['files'][] = [
                    "name" => $path,
                    "size" => filesize($path),
                    "lastmod" => filemtime($path),
                ];
            }
        }
        return self::$tmpArray;
    }
}
function getContainsByText(?string $text): array
{
    $h2Array = [];
    $h3 = [];
    $activeId = '';

    preg_match_all('/<h2[^>]*>(.*?)<\/h2>|<h3[^>]*>(.*?)<\/h3>/i', $text, $matches);

    if (empty($matches[0])) {
        return [];
    }

    foreach ($matches[1] as $key => $textH2) {
        if (empty($textH2) && isset($matches[2][$key]) && ! empty($matches[2][$key])) {
            $h3[] = [
                'id' => Str::slug($matches[2][$key]),
                'text' => $matches[2][$key],
            ];

            continue;
        }

        if (! empty($h3)) {
            $h2Array[$activeId]['h3'] = $h3;
        }

        $h3 = [];
        $activeText = $textH2;
        $activeId = Str::slug($textH2);
        $h2Array[$activeId] = [
            'id' => $activeId,
            'text' => $activeText,
            'h3' => $h3,
        ];
    }

    if (! empty($h3)) {
        $h2Array[$activeId]['h3'] = $h3;
    }

    return $h2Array;
}

function addIdToHInText(?string $text, array $h2AnchorsArray = []): ?string
{
    if (empty($h2AnchorsArray)) {
        $h2AnchorsArray = getContainsByText($text);
    }

    foreach ($h2AnchorsArray as $data) {
        if (empty($data['text'])) {
            continue;
        }

        $h2Pattern = '/<h2([^>]*)>'.preg_quote($data['text'], '/').'<\/h2>/i';
        $replacementH2 = "<h2\$1 id=\"{$data['id']}\">".str_replace('$', '\\$', $data['text']).'</h2>';
        $text = preg_replace($h2Pattern, $replacementH2, $text);

        if (! empty($data['h3'])) {
            foreach ($data['h3'] as $h3data) {
                $h3Pattern = '/<h3([^>]*)>'.preg_quote($h3data['text'], '/').'<\/h3>/i';
                $replacementH3 = "<h3\$1 id=\"{$h3data['id']}\">".str_replace('$', '\\$', $h3data['text']).'</h3>';
                $text = preg_replace($h3Pattern, $replacementH3, $text);
            }
        }
    }

    return $text;
}

function array_to_csv_download($array, $filename = "export.csv", $delimiter = ";") {
    $maxArray = [];
    foreach ($array as $key => $data) {
        if (count($data) > count($maxArray)) {
            $maxArray = $data;
        }
    }
    $array = array_merge([array_keys($maxArray)], $array);
    header('Content-Type: application/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');

    $f = fopen('php://output', 'w');
    
    foreach ($array as $line) {
        fputcsv($f, $line, $delimiter);
    }
    
    fclose($f);
}

function SendRequest($url, $method = 'GET', $params = array(), $header = array(), $proxy = '') : array
{
    $defaultHeaders = array(
    //"User-Agent: Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
    //"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
    //"Accept-Encoding: gzip, deflate",
    "Accept-Language: en-US,en;q=0.5",
    "Connection: keep-alive",
        // //"Authorization: Bearer 6|E2QX1fToDWlptzD8CtsvEFu5OkTDqe5C2766NAvT",
        "Accept: application/json",
        // "Referer: https://content-customsearch.googleapis.com/static/proxy.html",
        // "X-Goog-Encode-Response-If-Executable: base64",
        // "X-Javascript-User-Agent: apix/3.0.0 google-api-javascript-client/1.1.0",
        // "X-Origin: https://explorer.apis.google.com",
        // "X-Referer: https://explorer.apis.google.com",
        "X-Requested-With: XMLHttpRequest"
    );

    $userHeaders = (!empty($header) && is_array($header)) ? $header : array();

    $headers = array_merge($defaultHeaders, $userHeaders);
    $curl = curl_init();
    switch ($method) {
        case 'GET':
            if ($params) {
                $query = http_build_query($params);
                $url = "{$url}?{$query}";
            }
            break;
        case 'POST':
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            break;
        default:
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
            break;
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    //curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_PROXY, $proxy);
    //curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyauth);
    //curl_setopt($curl, CURLOPT_USERPWD, "adminka:s2zgqfhauJ");
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 5); 
    curl_setopt($curl, CURLOPT_TIMEOUT, 10); //timeout in seconds
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_REFERER, "https://google.com");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
    //curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    //curl_setopt($curl, CURLOPT_SSLVERSION, 1);
    //curl_setopt($curl,CURLOPT_COOKIEFILE, dirname(__FILE__).'/cookie.txt');
    //curl_setopt($curl,CURLOPT_COOKIEJAR, dirname(__FILE__).'/cookie.txt');
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $resp = curl_exec($curl);

    if ($resp === false) {
        $errno = curl_errno($curl);
        $error_message = curl_error($curl);
        curl_close($curl);
        throw new Exception($error_message, (int)$errno);
    }

    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    return ['code' => $code, 'content' => $resp];
}

function getSlug($text)
{
    // replace non letter or digits by -
    $text = preg_replace('~[^\pL\d]+~u', '-', $text);

    // transliterate
    $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);

    // remove unwanted characters
    $text = preg_replace('~[^-\w]+~', '', $text);

    // trim
    $text = trim($text, '-');

    // remove duplicate -
    $text = preg_replace('~-+~', '-', $text);

    // lowercase
    $text = strtolower($text);

    if (empty($text)) {
        return 'n-a';
    }

    return $text;
}

function db() 
{
    return \App\Database::getInstance();
}

function settings($grupa) 
{
    return new \App\Settings($grupa);
}

function print_arr($arr){
    echo "<pre>";
        print_r($arr);
    echo "</pre>";
}

function ViewRender(String $view, Array $data = []) 
{
    extract($data);

    ob_start();
    if (file_exists(Config::PATH['view']."/{$view}")) {
        include(Config::PATH['view']."/{$view}"); 
    } else {
        echo "View {$view} not found!";
    }
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
}

/**
 * Универсальная функция для загрузки изображений
 * @param array $files - $_FILES элемент или массив файлов
 * @param string $fieldName - имя поля файла (для вложенных массивов)
 * @return string|false - относительный путь к файлу или false при ошибке
 */
function uploadImage($files, $fieldName = null): bool|string {
    // Разрешенные MIME типы для изображений
    $allowedMimeTypes = [
        'image/jpeg',
        'image/jpg', 
        'image/png',
        'image/gif',
        'image/webp',
        'image/svg+xml',
        'image/x-icon',
        'image/vnd.microsoft.icon'
    ];
    
    // Если передано имя поля, извлекаем данные из вложенного массива
    if ($fieldName && isset($files['name'][$fieldName])) {
        $file = [
            'name' => $files['name'][$fieldName],
            'tmp_name' => $files['tmp_name'][$fieldName], 
            'error' => $files['error'][$fieldName],
            'type' => $files['type'][$fieldName]
        ];
    } else {
        $file = $files;
    }
    
    if (empty($file['name']) || $file['error'] !== UPLOAD_ERR_OK) {
        return false;
    }
    
    // Проверка MIME типа
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimeType = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);
    
    if (!in_array($mimeType, $allowedMimeTypes)) {
        return false;
    }
    
    // Дополнительная проверка по расширению файла
    $fileExtension = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'ico'];
    
    if (!in_array($fileExtension, $allowedExtensions)) {
        return false;
    }
    
    $uploadDir = Config::PATH['storage'] . '/';
    
    // Создаем директорию если она не существует
    if (!file_exists($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Используем оригинальное имя файла
    $fileName = basename($file['name']);
    $targetPath = $uploadDir . $fileName;
    
    if (move_uploaded_file($file['tmp_name'], $targetPath)) {
        // Возвращаем относительный путь для веб-доступа
        return 'media/' . $fileName;
    }
    
    return false;
}

/**
 * Получение реального IP адреса пользователя
 * @return string IP адрес пользователя
 */
function getUserIp(): string {
    if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
        return $_SERVER['HTTP_CF_CONNECTING_IP'];
    } elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Берём первый IP из списка (если их несколько через запятую)
        return explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
    } else {
        return $_SERVER['REMOTE_ADDR'];
    }
}

function calculateRating($index) {
    if ($index < 3) {
        return '10';
    } elseif ($index < 6) {
        return '9.5';
    } elseif ($index < 9) {
        return '9';
    } else {
        return '8.5';
    }
}

function getCurrentUrl() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domain = $_SERVER['HTTP_HOST'];
    $requestUri = $_SERVER['REQUEST_URI'];
    return $protocol . $domain . $requestUri;
}

function getCurrentDomain() {
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domain = $_SERVER['HTTP_HOST'];
    return $protocol . $domain;
} 
