<?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.";
    }
}


function getnotification($type) {
    $db = new SQLite3('./.db.db');
    $stmt = $db->prepare('SELECT * FROM noti WHERE id = :id LIMIT 1');
    $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);

    $tital   = 'IBO PLAYER doesnt sell playlists or subscriptions';
    $content = 'Disclaimer: IBO PLAYER is a general media player and it does not include any content. You have to provide your own content. IBO PLAYER is not responsible for the content you use in the app';

    if (!empty($row)) {
        if (!empty($row['tital'])) {
            $tital = $row['tital'];
        }
        if (!empty($row['content'])) {
            $content = $row['content'];
        }
    }

    if ($type == 1) {
        return $tital;
    } else {
        return $content;
    }
}


function playlistui() {
    $db = new SQLite3('./.db.db');
    $stmt = $db->prepare('SELECT * FROM plmod WHERE id = :id LIMIT 1');
    $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);

    $plstyle   = '1';


    if (!empty($row)) {
        if (!empty($row['mod'])) {
            $plstyle = $row['mod'];
        }

    }

    return $plstylel;
   
}



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


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


echo $finalgood;
