<?php     
include(__DIR__ . '/../includes/functions.php');    
include ('APIkey.php');
session_start();      


$res = $db->select('dns', '*', '', '');   
$int = $db->select('int', '*', 'id = :id', '', [':id' => 1]);


//$keysp = $api_key;
$intro = !empty($int[0]['intro']) ? $int[0]['intro'] : 'enable';




$rowsJson = array();      

foreach ($res as $row) {      
    $row_array = array( 
        'name' => $row['title'],    
        'url' => $row['url'],
        'uuid' => $row['uid']
    );
    $rowsJson[] = $row_array;    
}     

function generateSingleNumberWithSum45() {
    $numbers = [];
    $targetSum = 95;
    $currentSum = 0;
    
    while ($currentSum < $targetSum) {
        $remaining = $targetSum - $currentSum;
        if ($remaining > 9) {
            $num = rand(0, 9);
        } else {
            $num = $remaining;
        }
        
        $numbers[] = $num;
        $currentSum += $num;
    }
    

    if (array_sum($numbers) == 95) {
        $letterMap = [
            9 => 'a',
            8 => 'b',
            7 => 'c',
            6 => 'd',
            5 => 'e',
            4 => 'f',
            3 => 'g',
            2 => 'h',
            1 => 'i',
            0 => 'j'
        ];
        
        $letterSequence = '';
        foreach ($numbers as $num) {
            $letterSequence .= $letterMap[$num];
        }
        
        return $letterSequence;
    } else {
        return generateSingleNumberWithSum45();
    }
}

function insertRandomLettersIntoText($originalText) {
    
    $letterSequence = generateSingleNumberWithSum45();
    $textArray = str_split($originalText);
    $textLength = strlen($originalText);
    
    $letterArray = str_split($letterSequence);
    $letterCount = count($letterArray);
    
    $randomIndexes = [];
    while (count($randomIndexes) < $letterCount) {
        $index = rand(0, $textLength);
        if (!in_array($index, $randomIndexes)) {
            $randomIndexes[] = $index;
        }
    }
    sort($randomIndexes); 
    
    $resultArray = $textArray;
    $offset = 0;
    foreach ($randomIndexes as $i => $index) {
        array_splice($resultArray, $index + $offset, 0, $letterArray[$i]);
        $offset++; 
    }
    
    return implode('', $resultArray);
}



function generateStrictRandomString($length = 120) {

    $excluded = str_split('ABCDEFGHIJabcdefghij');
    $allCharacters = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
    $allowedCharacters = array_diff($allCharacters, $excluded);
    $characters = implode('', $allowedCharacters);
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
}

function extractLettersWithSum45($inputString) {
    $letterMap = [
        'a' => 9,
        'b' => 8,
        'c' => 7,
        'd' => 6,
        'e' => 5,
        'f' => 4,
        'g' => 3,
        'h' => 2,
        'i' => 1,
        'j' => 0
    ];
    
    $extractedLetters = '';
    $sum = 0;
    
    foreach (str_split($inputString) as $char) {
        $charLower = strtolower($char);
        if (array_key_exists($charLower, $letterMap)) {
            $extractedLetters .= $charLower;
            $sum += $letterMap[$charLower];
        }
    }
    
    if ($sum == 95) {
        return $sum;
    } else {
        return "Error: Extracted letters do not sum to 45. Sum is $sum.";
    }
}



$randomtext = generateStrictRandomString();
$finalText = insertRandomLettersIntoText($randomtext);
$text45 = extractLettersWithSum45($finalText);


header('Content-Type: application/json');
$finalgood = json_encode(array(
    'uuid' => $finalText,
    'portals' => $rowsJson,
    'intro' => $intro,
    'sport_api' => $api_key
    
));


echo $finalgood;
