<?php
// /youtivi/api/api.php — JSON-only API for the app

// ---- Hard-disable output leakage from notices/warnings
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL);
ini_set('log_errors', '1');
ini_set('error_log', __DIR__ . '/error_log');

// Buffer any accidental echoes from includes; we’ll discard them.
ob_start();

// ---- Includes (NO session_start here)
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/APIkey.php';

// ---- Read DB rows
$res = $db->select('dns', '*', '', '');
$int = $db->select('int', '*', 'id = :id', '', [':id' => 1]);
$intro = !empty($int[0]['intro']) ? $int[0]['intro'] : 'enable';

// ================== helpers (unchanged logic, minor hardening) ==================
function generateSingleNumberWithSum45() {
    $numbers = [];
    $targetSum = 95; // (legacy name says 45; code uses 95 — keep as-is)
    $currentSum = 0;

    while ($currentSum < $targetSum) {
        $remaining = $targetSum - $currentSum;
        $num = ($remaining > 9) ? rand(0, 9) : $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'];
        $seq = '';
        foreach ($numbers as $n) $seq .= $letterMap[$n];
        return $seq;
    }
    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) {
        $idx = rand(0, $textLength);
        if (!in_array($idx, $randomIndexes)) $randomIndexes[] = $idx;
    }
    sort($randomIndexes);

    $resultArray = $textArray;
    $offset = 0;
    foreach ($randomIndexes as $i => $idx) {
        array_splice($resultArray, $idx + $offset, 0, $letterArray[$i]);
        $offset++;
    }
    return implode('', $resultArray);
}

function generateStrictRandomString($length = 120) {
    $excluded = str_split('ABCDEFGHIJabcdefghij');
    $all = str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789');
    $allowed = array_diff($all, $excluded);
    $chars = implode('', $allowed);
    $L = strlen($chars);
    $out = '';
    for ($i = 0; $i < $length; $i++) {
        $out .= $chars[random_int(0, $L - 1)];
    }
    return $out;
}

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

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

    $tital   = 'TiVi PLAYER doesnt sell playlists or subscriptions';
    $content = 'Disclaimer: TiVi PLAYER is a general media player and it does not include any content. You have to provide your own content. TiVi 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'];
    }
    return ($type == 1) ? $tital : $content;
}

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

    $plstyle = '1';
    if (!empty($row) && !empty($row['mod'])) $plstyle = $row['mod'];
    return $plstyle;
}
// ===============================================================================

// Build portals array
$rowsJson = [];
foreach ($res as $row) {
    $rowsJson[] = [
        'name' => (string)$row['title'],
        'url'  => (string)rtrim($row['url'], '/'),
        'uuid' => (string)$row['uid']
    ];
}

// UUID-ish payload value
$randomtext = generateStrictRandomString();
$finalText  = insertRandomLettersIntoText($randomtext);
// $text45 = extractLettersWithSum45($finalText); // not used downstream

$payload = [
    'uuid'        => $finalText,
    'portals'     => $rowsJson,
    'intro'       => $intro,
    'notitial'    => getnotification(1),
    'noticontent' => getnotification(2),
    'sport_api'   => $api_key
];

// Clean header + output (discard buffer first)
if (!headers_sent()) {
    header('Content-Type: application/json; charset=UTF-8');
}
ob_end_clean();
echo json_encode($payload, JSON_UNESCAPED_SLASHES);
exit;
