<?php
ini_set("log_errors", 1);
ini_set("error_log", "errorlog.txt");

// FUNÇÕES DE CRIPTOGRAFIA E FORMATAÇÃO DO SEU APP
function decode($encoded) {
    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        $length = strlen($encoded);
            $pos1 = strpos($chars, $encoded[$length - 2]);
                $pos2 = strpos($chars, $encoded[$length - 1]);
                    $decoded = substr($encoded, 0, $length - 2);
                        $decoded = substr($decoded, 0, $pos1) . substr($decoded, $pos1 + $pos2);
                            return base64_decode($decoded);
                            }

                            function formatMac($mac) {
                                $mac = preg_replace('/[^A-Za-z0-9]/', '', $mac);
                                    if (strlen($mac) < 12) $mac = str_pad($mac, 12, '0');
                                        elseif (strlen($mac) > 12) $mac = substr($mac, 0, 12);
                                            $mac = preg_replace('~..(?!$)~', '\0:', $mac);
                                                return strtoupper($mac);
                                                }

                                                // LOGICA DE TRIAL E CADASTRO
                                                function trial($mac) {
                                                    global $db2, $res;
                                                        $res = $db2->query('SELECT * FROM ibo WHERE mac_address="'.$mac .'"');
                                                            $count = 0;
                                                                while ($row = $res->fetchArray()) { $count++; }
                                                                    
                                                                        if ($count == 0) {
                                                                                $json = '{"receiveMessageAppId":"com.whatsapp","receiveMessagePattern":["*"],"senderName":"API DE CADASTRO","groupName":"","senderMesage":"api_cadastro","senderMessage":"api_cadastro","messageDateTime":' . time() . ',"isMessageFromGroup":false}';
                                                                                        $url_server = file_get_contents("../app_url");
                                                                                                $dns = file_get_contents("../app_dns");
                                                                                                        $ch = curl_init($url_server);
                                                                                                                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
                                                                                                                        curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
                                                                                                                                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                                                                                                                                        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0');
                                                                                                                                                curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
                                                                                                                                                        $jsonRetorno = json_decode(curl_exec($ch), true);

                                                                                                                                                                $username = $jsonRetorno['username'] ?? null;
                                                                                                                                                                        $password = $jsonRetorno['password'] ?? null;

                                                                                                                                                                                if (!empty($username) && !empty($password)) {
                                                                                                                                                                                            $expire_date2 = '2050-01-01';
                                                                                                                                                                                                        $url = $dns . "/get.php?username=" . $username . "&password=" . $password . "&type=m3u_plus&output=ts";
                                                                                                                                                                                                                    $db2->exec("INSERT INTO ibo (mac_address, username, password, expire_date, title, url, type) VALUES ('$mac', '$username', '$password', '$expire_date2', 'NOVO*** (TESTE CADASTRADO)', '$url', 1)");
                                                                                                                                                                                                                            } else {
                                                                                                                                                                                                                                        $db2->exec("INSERT INTO ibo (mac_address, title, expire_date, type) VALUES ('$mac', 'NOVO*** (SEM DNS)', '2050-01-01', 1)");
                                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                                    }
                                                                                                                                                                                                                                                    }

                                                                                                                                                                                                                                                    function defaultHandle($mac) {
                                                                                                                                                                                                                                                        global $db2, $res;
                                                                                                                                                                                                                                                            if(!isset($mac)) return;
                                                                                                                                                                                                                                                                $res = $db2->query('SELECT * FROM ibo WHERE mac_address="'.$mac .'"');
                                                                                                                                                                                                                                                                    $count = 0;
                                                                                                                                                                                                                                                                        while ($row = $res->fetchArray()) { $count++; }
                                                                                                                                                                                                                                                                            if ($count == 0) {
                                                                                                                                                                                                                                                                                    $expire_date = date('Y-m-d', strtotime("+9651 DAYS"));
                                                                                                                                                                                                                                                                                            $db2->exec("INSERT INTO ibo (mac_address, title, expire_date, type) VALUES ('$mac', 'CADASTRO', '$expire_date', 1)");
                                                                                                                                                                                                                                                                                                }
                                                                                                                                                                                                                                                                                                }

                                                                                                                                                                                                                                                                                                // RECEBIMENTO DE DADOS DO DISPOSITIVO
                                                                                                                                                                                                                                                                                                $data = json_decode(file_get_contents('php://input'), true);
                                                                                                                                                                                                                                                                                                if($data){
                                                                                                                                                                                                                                                                                                    $data = $data['data'];
                                                                                                                                                                                                                                                                                                        $data = json_decode(decode($data), true);
                                                                                                                                                                                                                                                                                                            $mac = base64_decode($data['app_device_id']);
                                                                                                                                                                                                                                                                                                                $mac = formatMac($mac);
                                                                                                                                                                                                                                                                                                                }

                                                                                                                                                                                                                                                                                                                // LENDO DADOS DO SEU ibo.json (SALVOS PELO NOVO PAINEL)
                                                                                                                                                                                                                                                                                                                $ibo_json = file_get_contents('./ibo.json');
                                                                                                                                                                                                                                                                                                                $ibo_data = json_decode($ibo_json,true);
                                                                                                                                                                                                                                                                                                                $android_version_code = $ibo_data['app_info']['android_version_code'];
                                                                                                                                                                                                                                                                                                                $apk_url = $ibo_data['app_info']['apk_url'];

                                                                                                                                                                                                                                                                                                                $db1 = new SQLite3('./.ansdb.db');
                                                                                                                                                                                                                                                                                                                $res1 = $db1->query('SELECT * FROM theme');
                                                                                                                                                                                                                                                                                                                $themes = [];
                                                                                                                                                                                                                                                                                                                while ($row1 = $res1->fetchArray()) {
                                                                                                                                                                                                                                                                                                                    $themes[] = ['name'=>$row1['name'],'url'=>$row1['url']];
                                                                                                                                                                                                                                                                                                                    }

                                                                                                                                                                                                                                                                                                                    $languages = file_get_contents('./language.json');
                                                                                                                                                                                                                                                                                                                    $notification = file_get_contents('./note.json');

                                                                                                                                                                                                                                                                                                                    if (isset($mac)) {
                                                                                                                                                                                                                                                                                                                        $mode = file_get_contents('../trial_mode');
                                                                                                                                                                                                                                                                                                                            $db2 = new SQLite3('./.ansdb.db');
                                                                                                                                                                                                                                                                                                                                if ($mode == 'trial'){ trial($mac); } else { defaultHandle($mac); }
                                                                                                                                                                                                                                                                                                                                    
                                                                                                                                                                                                                                                                                                                                        $res3 = $db2->query('SELECT *, custom_message FROM ibo WHERE mac_address="'.$mac .'"');
                                                                                                                                                                                                                                                                                                                                            $personal_note = ""; 
                                                                                                                                                                                                                                                                                                                                                $urls = [];
                                                                                                                                                                                                                                                                                                                                                    $expire_date = "2050-01-01";

                                                                                                                                                                                                                                                                                                                                                        while ($row3 = $res3->fetchArray()) {
                                                                                                                                                                                                                                                                                                                                                                $expire_date = $row3['expire_date'];
                                                                                                                                                                                                                                                                                                                                                                        $url = $row3['url'];
                                                                                                                                                                                                                                                                                                                                                                                $username = $row3['username'];
                                                                                                                                                                                                                                                                                                                                                                                        $password = $row3['password'];
                                                                                                                                                                                                                                                                                                                                                                                                if (!empty($row3['custom_message'])) { $personal_note = $row3['custom_message']; }
                                                                                                                                                                                                                                                                                                                                                                                                        
                                                                                                                                                                                                                                                                                                                                                                                                                $url_final = $url ? $url . "/get.php?username=" . $username . "&password=" . $password . "&type=m3u_plus&output=ts" : "";
                                                                                                                                                                                                                                                                                                                                                                                                                        $urls[] = ['is_protected'=>1,'id'=>md5($password .$row3['id']),'url'=>$url_final,'name'=>$row3['title'],'username'=>$username ,'password'=>$row3['password'],'epg_url'=>$row3['url'] .'/xmltv.php','pin'=>'0000','playlist_type'=>'xc'];
                                                                                                                                                                                                                                                                                                                                                                                                                            }
                                                                                                                                                                                                                                                                                                                                                                                                                                
                                                                                                                                                                                                                                                                                                                                                                                                                                    $notification_to_send = !empty($personal_note) ? json_encode(["title" => "Aviso Particular","description" => $personal_note,"type" => "text"]) : $notification;

                                                                                                                                                                                                                                                                                                                                                                                                                                        // MONTAGEM DO ARRAY COM OS CAMPOS QUE O SMALI PRECISA (app_version e apk_link)
                                                                                                                                                                                                                                                                                                                                                                                                                                            $api_array = [
                                                                                                                                                                                                                                                                                                                                                                                                                                                    "android_version_code" => $android_version_code,
                                                                                                                                                                                                                                                                                                                                                                                                                                                            "apk_url" => $apk_url,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "mac_address" => $mac,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "device_key" => "136115",
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "expire_date" => $expire_date,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "is_google_paid" => true,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "is_google_pay" => true,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "is_trial" => 0,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "notification" => json_decode($notification_to_send),
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "urls" => $urls,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "mac_registered" => true,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "trial_days" => 9651,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "pin" => "0000",
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "app_version" => $android_version_code,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "apk_link" => $apk_url,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            "themes" => $themes,
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    "languages" => json_decode($languages)
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        ];

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            $api = json_encode($api_array);
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            } else {
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                $api = 'invalid';
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                }

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                // CRIPTOGRAFIA FINAL DO IBO PLAYER (BASE64 + "aa")
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                $api_encoded = base64_encode($api) . "aa";
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                echo "{\"data\": \"$api_encoded\"}";
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                return;
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                ?>
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                