<?php
$mac_address = '00:00:00:00:00';

function safe_base64_decode($base64Text) {
    $base64Text = preg_replace('/\s+/', '', $base64Text);
    if (!preg_match('/^[A-Za-z0-9+\/=]*$/', $base64Text)) {
        throw new Exception("Invalid Base64 string");
    }
    $decoded = base64_decode($base64Text, true); 
    if ($decoded === false) {
        throw new Exception("Base64 decode failed");
    }
    return $decoded;
}


if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    $payload = json_decode($json_data, true);
    if ($payload !== null && isset($payload['data'])) {
        try {
            $encodedData = str_replace("\n", "", $payload['data']);
            $inner_data_string = safe_base64_decode($encodedData); 
            $inner_data = json_decode($inner_data_string, true);
            if ($inner_data !== null && isset($inner_data['app_device_id'])) {
                $mac_address = mainmac($inner_data['app_device_id']);
                $mac_address = strtolower($mac_address);
                $mac_address = preg_replace('/[^0-9a-f:]/', '', $mac_address);
                if (!preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/', $mac_address)) {
                    throw new Exception('Generated MAC address is invalid');
                }
            } else {
                throw new Exception('Missing app_device_id in decoded data');
            }
        } catch (Exception $e) {
            $mac_address = '00:00:00:00:00:00';
            error_log('Error processing payload: ' . $e->getMessage());
        }
    } else {
        error_log('Invalid or missing data field in payload');
    }
}



function mainmac($uniqueId){
    $db = new SQLite3('./.db.db');
    $stmt = $db->prepare('SELECT * FROM devop WHERE id = :id LIMIT 1');
    $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);
    
    $mac_mothrd = 1;
    
    if (!empty($row) && !empty($row['macmod'])) {
        $mac_mothrd = (int)$row['macmod'];
    }

    if($mac_mothrd == 1){
        return generateMacAddressbase($uniqueId);
    } else if ($mac_mothrd == 2){
        return generateMacAddress($uniqueId);
    } else if ($mac_mothrd == 3){
        return generateNumericMacAddress($uniqueId);
    } else if($mac_mothrd == 4){
        return generateLetterMacAddress($uniqueId);
    } else {
        return generateMacAddressbase($uniqueId); // default
    }
}


function parentPin($macAddress) {
    $db = new SQLite3('./.db.db');
    $macNormalized = strtolower($macAddress);
    $stmt = $db->prepare('SELECT pin FROM pintb WHERE LOWER(macad) = :mac');
    $stmt->bindValue(':mac', $macNormalized, SQLITE3_TEXT);
    $result = $stmt->execute();

    if ($row = $result->fetchArray(SQLITE3_ASSOC)) {
        $pin = $row['pin'];
        return !empty($pin) ? $pin : '0000';
    }
    return '0000';
}


function generateMacAddressbase($uniqueId) {
    $mac_length = 12;
    $bdecode = base64_decode($uniqueId, true);
    if ($bdecode === false) {
        throw new Exception("Invalid uniqueId: Base64 decode failed");
    }
    $reversed = strrev($bdecode);
    $hash = hash('sha256', $reversed);
    $hex  = substr($hash, 0, $mac_length);
    $macParts = str_split($hex, 2);
    $mac = implode(":", $macParts);
    return strtolower($mac);
}



function generateMacAddress($uniqueId) {
    $reversed = strrev($uniqueId);
    $hash = md5($reversed);
    $macParts = [];
    for ($i = 0; $i < 6; $i++) {
        $macParts[] = substr($hash, $i * 2, 2);
    }
    return strtoupper(implode(":", $macParts));
}

function generateNumericMacAddress($uniqueId, $length = 12) {
    $reversed = strrev($uniqueId);
    $hash = md5($reversed);
    $numbersOnly = preg_replace('/[^0-9]/', '', $hash);

    while (strlen($numbersOnly) < $length) {
        $numbersOnly .= $numbersOnly;
    }

    $numbersOnly = substr($numbersOnly, 0, $length);

    $macParts = str_split($numbersOnly, 2);
    return implode(":", $macParts);
}


function generateLetterMacAddress($uniqueId) {
    $reversed = strrev($uniqueId);
    $hash = md5($reversed);
    $lettersOnly = preg_replace('/[^a-f]/i', '', $hash); 
    while (strlen($lettersOnly) < 12) {
        $lettersOnly .= $lettersOnly;
    }   
    $lettersOnly = substr($lettersOnly, 0, 12); 
    $macParts = str_split(strtoupper($lettersOnly), 2); 
    return implode(":", $macParts);
}



function processdevicekey($mac, $length = 6) {
    $normalized = strtolower(str_replace([':', '-', '.'], '', $mac));
    $hash = hash('sha256', $normalized);
    $bigInt = base_convert($hash, 16, 10);
    $deviceKey = substr($bigInt, 0, $length);
    return str_pad($deviceKey, $length, "0", STR_PAD_LEFT);
}



function getUserData($mac_address) {
    $db = new SQLite3('./.db.db');

    // Normalize MAC address
    $mac_address = strtolower(trim($mac_address));
    $mac_address = str_replace(['：','﹕','꞉'], ':', $mac_address);
    $mac_address = preg_replace('/[^0-9a-f:]/', '', $mac_address);

    // Prepare safe SQL (prevent SQL injection)
    $stmt = $db->prepare('SELECT * FROM ibof WHERE LOWER(macad) = :macad');
    $stmt->bindValue(':macad', $mac_address, SQLITE3_TEXT);
    $ibo_query = $stmt->execute();

    $urls = [];
    while ($ibo_row = $ibo_query->fetchArray(SQLITE3_ASSOC)) {
        $base_url = getuuidtodns($ibo_row['uuid'], 2);

        $urls[] = [
            'id' => $ibo_row['plid'],
            'name' => $ibo_row['name'],
            'url' => $base_url."/get.php?username={$ibo_row['username']}&password={$ibo_row['password']}",
            'created_at' => $ibo_row['cdate'],
            'updated_at' => $ibo_row['udate'],
            'is_protected' => $ibo_row['protec']
        ];
    }
    
    if (!empty($urls)) {
        return $urls;
    } else {
        return getdemopls();
    }

    
}


function getdemopls() {
    $db = new SQLite3('./.db.db');
    $stmt = $db->prepare('SELECT * FROM demoplay WHERE id = :id LIMIT 1');
    $stmt->bindValue(':id', 1, SQLITE3_INTEGER);
    $result = $stmt->execute();
    $row = $result->fetchArray(SQLITE3_ASSOC);
    
    $tital = '';
    $dns = '';
    $username = '';
    $password = '';
    
    $urls = [];
    
    if (!empty($row)) {
        $tital = $row['name'];
        $dns = $row['dns'];
        $username = $row['uname'];
        $password = $row['pass'];
        
        if(!empty($tital) && !empty($dns) && !empty($username) && !empty($password)) {
            
          $urls[] = [
            'id' => 0,
            'name' => $tital,
            'url' => $dns."/get.php?username=$username&password=$password&type=m3u_plus&output=mpegts",
            'created_at' => '2025-08-22 09:36:55',
            'updated_at' => '2025-08-22 09:36:55',
            'is_protected' => '1'
        ];  
            
        }else{
            
           $urls = []; 
            
        }
        
        
    }else{
        $urls = [];
    }
        
    return $urls;
    
}


function getuuidtodns($uuid,$type){
    $db = new SQLite3('./.db.db');
    $uuid = strtolower($uuid);
    $ibo_query = $db->query('SELECT * FROM dns WHERE LOWER(uid)="' . $uuid . '"');
    $dnsname = "";
    $dnsurl = "";
    while ($ibo_row = $ibo_query->fetchArray()) {
        $dnsname = $ibo_row['title'];
        $dnsurl = $ibo_row['url'];
    }
    
    if($type == 1){
        return $dnsname;
    }else{
        return $dnsurl;
    }
    
}

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 setupexp($mac_address,$trial){
    $db = new SQLite3('./.db.db');
    $mac_address = strtolower($mac_address);
    $ibo_query = $db->query('SELECT * FROM mactb WHERE LOWER(macad)="' . $mac_address . '"');
    $ExpDate = "";
    $Block = "";
    while ($ibo_row = $ibo_query->fetchArray()) {
        $ExpDate = $ibo_row['expir'];
        $Block = $ibo_row['blok'];
    }
    
    $NonExpDate = '2099-09-09';
    $BlockExpDate = '2000-09-09';
  
    
    if($Block == '' || $Block == 0){
        if($ExpDate == ''){
            if($trial == 1){
               return $NonExpDate;  
            }elseif ($trial == 2){
               return 9999999;
            }else{
                return 2;
            }
        }else{
            if($trial == 1){
                return $ExpDate;  
            }elseif ($trial == 2){
                return 9999999;
            }else{
                return 2;
            }
        }
    }elseif($Block == 1){
        if($trial == 1){
            return $BlockExpDate;
        }elseif ($trial == 2){
            return 0;
        }else{
            return 0;
        }
        
    }
}

function getUserIP() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return $ip;
}


function php_encrypt($text) {
    $result = [];
    $len = strlen($text);

    // Chunk size = 2
    $chunkSize = 2;
    $partNumber = 1;

    // Helper function to generate random hex string
    function random_hex($length) {
        $chars = '0123456789abcdef';
        $str = '';
        for ($i = 0; $i < $length; $i++) {
            $str .= $chars[random_int(0, 15)]; // cryptographically secure
        }
        return $str;
    }

    for ($i = 0; $i < $len; $i += $chunkSize) {
        $chunk = substr($text, $i, $chunkSize);

        // Base64 encode
        $encoded = base64_encode($chunk);

        // Convert Base64 to Hex
        $hex = bin2hex($encoded);

        // Reverse hex string
        $reversed = strrev($hex);

        // Generate random bogus hex chars
        $front = random_hex(5); // 5 chars in front
        $back  = random_hex(4); // 4 chars at back

        // Combine
        $secured = $front . $reversed . $back;

        // Add to result
        $result[] = ["part" . $partNumber => $secured];
        $partNumber++;
    }

    return $result;
}


$iboplaylist = getUserData($mac_address);

/*if($iboplaylist == 'demo'){
    $iboplaylist = getdemopls();
}*/

$devicekey = processdevicekey($mac_address);

$expire = setupexp($mac_address,1);
$trial_days = setupexp($mac_address,2);
$tperiad = setupexp($mac_address,3);
$getnoti_tital = getnotification(1);
$getnoti_content = getnotification(2);
$get_perantpin = parentPin($mac_address);
$myip = getUserIP();



function echosend($mMacaddress , $mDevkey , $mExpire , $mPlaylist, $pinparent){
   $output = [
    'android_version_code' => '1.20',
    'apk_url' => 'https://iboiptv.com/upload/android_1.1.apk',
    'device_key' => $mDevkey,
    'expire_date' => $mExpire,
    'is_google_paid' => false,
    'is_trial' => 2,
    'urls' => $mPlaylist,
    'trial_days' => 7,
    'tmdbKey' => '36247ceb0449a76b89b98f30fc9b6f84',
    'mac_address' => $mMacaddress,
    'price' => 9.99,
    'app_version' => '1.20',
    'serverTime' => 1755855415,
    'pay' => [
        'enabled' => false,
        'path' => '5Uz7UDTfDw'
    ],
    'has_own_playlist' => true,
    'apk_link' => 'https://store.4kapps.com/android/YouTivi.apk',
    'parent_control' => $pinparent,
    'parent_synced' => 1
];

return $output;
}

/*$finaloutput =  json_encode(["data" => encodertx(echosend($mac_address,$devicekey,$expire,$iboplaylist,$get_perantpin))]);
echo $finaloutput;*/

$finaloutput = json_encode(echosend($mac_address,$devicekey,$expire,$iboplaylist,$get_perantpin));

$encryp_data =  json_encode(php_encrypt($finaloutput));
$finaldata_echo = json_encode(["data" => $encryp_data]);

echo $finaldata_echo;
?>