<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
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 && isset($inner_data['mac_address'])) {
            // Normalize & sanitize MAC address
            $raw_mac = $inner_data['mac_address'];

            // Convert to lowercase
            $raw_mac = strtolower($raw_mac);

            // Replace any Unicode lookalike colon with real colon
            $raw_mac = str_replace(['：','﹕','꞉'], ':', $raw_mac);

            // Remove anything not valid (only allow 0-9, a-f, and :)
            $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){
    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;

?>
