<?php
$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 && isset($inner_data['mac_address'])) {
            $raw_mac = $inner_data['mac_address'];
            $raw_mac = strtolower($raw_mac);
            $raw_mac = str_replace(['：','﹕','꞉'], ':', $raw_mac);
            $mac_address = preg_replace('/[^0-9a-f:]/', '', $raw_mac);
        }
    }
}

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) {
    $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[] = [
            'is_protected'  => '1',
            'id'            => $ibo_row['plid'],
            'url'           => $base_url,
            'playlist_name' => $ibo_row['name'],
            'username'      => $ibo_row['username'],
            'password'      => $ibo_row['password'],
            'epg_url'       => $base_url . "/xmltv.php?username={$ibo_row['username']}&password={$ibo_row['password']}",
            'playlist_type' => 'xc',
            'origin_type'   => 'xc',
            'origin_url'    => $base_url
        ];
    }

    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 = 'Unlimited';
    $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;
}

$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)]);
echo $finaloutput;

?>
