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

$mac_address = '00:00:00:00:00';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $json_data = file_get_contents('php://input');
    $payload = json_decode($json_data, true);
    if ($payload !== null && isset($payload['data'])) {
        $inner_data = json_decode($payload['data'], true);
        if ($inner_data !== null) {
            $mac_address = strtolower($inner_data['mac_address']);
        }
    } 
} else {
    
}

function processdevicekey($mac) {
    $digits = preg_replace('/[^0-9]/', '', $mac);
    $sum = array_sum(str_split($digits));
    $sum *= 12556;
    return substr($sum, 0, 6);
}


function getUserData($mac_address_get){
    global $db;
    $res = $db->select('ibof', '*', 'macad = :macad', '', [':macad' => $mac_address_get]);
    $urls = [];
    foreach ($res as $row) {
        $baseUrl = getuuidtodns($row['uuid'], 2);
        $urls[] = [
            'is_protected' => '1',
            'id' => $row['plid'],
            'url' => sprintf('%s/get.php?username=%s&password=%s&type=m3u_plus&output=ts',
                    $baseUrl, urlencode($row['username']), urlencode($row['password'])),
            'playlist_name' => $row['name'],
            'username' => $row['username'],
            'password' => $row['password'],
            'epg_url' => getuuidtodns($row['uuid'],2) . "/xmltv.php?username=" . $row['username'] . "&password=" . $row['password'],
            'playlist_type' => 'xc',
            'origin_type' => 'general',
            'origin_url' => sprintf('%s/get.php?username=%s&password=%s&type=m3u_plus&output=ts',
                    $baseUrl, urlencode($row['username']), urlencode($row['password']))
            
            
        ];
    }
    return $urls;
}


function getuuidtodns($uuid,$type){
    global $db;
    $ret = $db->select('dns', '*', 'uid = :uid', '', [':uid' => $uuid]);
    
    $dnsname =  $ret[0]['title'];
    $dnsurl =  $ret[0]['url'];
    
    if($type == 1){
        return $dnsname;
    }else{
        return $dnsurl;
    }
    
}

function getnotification($type){
    global $db;
    $ret = $db->select('noti', '*', 'id = :id', '', [':id' => 1]);
    
    $tital = !empty($ret[0]['tital']) ? $ret[0]['tital'] : 'IBO PLAYER doesnt sell playlists or subscriptions';
    $content = !empty($ret[0]['content']) ? $ret[0]['content'] : 'Disclaimer: IBO PLAYER is a general media player and it does not include any content. You have to provide you own content. IBO PLAYER is not responsible for the content you use in the app';
    
    if($type == 1){
        return $tital;
    }else{
        return $content;
    }
}

function setupexp($mac,$trial){
    global $db;
    $ret = $db->select('mactb', '*', 'macad = :macad', '', [':macad' => $mac]);
    
    $NonExpDate = 'Unlimited';
    $BlockExpDate = '2000-09-09';
    $ExpDate =  $ret[0]['expir'] ? : '';
    $Block =  $ret[0]['blok']? : '';
  
    
    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;
}

$devicekey = processdevicekey($mac_address);
$expire = setupexp($mac_address,1);
$trial_days = setupexp($mac_address,2);
$tperiad = setupexp($mac_address,3);
$playlist = getUserData($mac_address);
$getnoti_tital = getnotification(1);
$getnoti_content = getnotification(2);
$myip = getUserIP();

//setup language
$filetext = 'lang.json';
$language = file_get_contents($filetext);
$languagedata = json_decode($language, true);

//echo echoing($mac_address,$playlist,$devicekey,$expire,$trayal,$getnoti_tital,$getnoti_content,$languagedata,$myip);



function echoing($mac,$list,$devkey,$expdate,$trail,$istrail,$ntital,$ncontent,$lang,$ip){
    
    $output = [
        'mac_registered' => true,
        'urls' => $list,
        'themes' => [
            [
                'name' => 'black screen',
                'url' => 'https://iboplayerpro.com/images/upload/698079.png'
            ],
            [
                'name' => 'honor wallpaper',
                'url' => 'https://iboplayerpro.com/images/upload/166531.jpg'
            ]
        ],
        'has_own_playlist' => true,
        'trial_days' => $trail,
        'parent_pin' => '0000',
        'ip_address' => $ip,
        'notification' => [
            'title' => $ntital,
            'content' => $ncontent
        ],
        'languages' => $lang,
        'android_version_code' => '1.1',
        'apk_url' => 'https://iboiptv.com/upload/android_1.1.apk',
        'mac_address' => $mac,
        'device_key' => $devkey,
        'is_trial' => $istrail,
        'expire_date' => $expdate
];

return $output;
    
}

$finaloutput =  json_encode(["data" => echoing($mac_address,$playlist,$devicekey,$expire,$trial_days,$tperiad,$getnoti_tital,$getnoti_content,$languagedata,$myip)]);

$chunks = str_split($finaloutput, 200);

$result = [];
foreach ($chunks as $index => $chunk) {
    $partName = "part" . ($index + 1);
    $result[] = [$partName => base64_encode($chunk)];
}


echo $finaloutput;

?>