<?php
error_reporting(0);
ini_set('display_errors', '0');
$Tag = isset($_GET['tag']) ? $_GET['tag'] : '';
$UserID = isset($_GET['userid']) ? $_GET['userid'] : '';
$IPADDRESS = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '';

$key = "mysecretkeywsdef";
$iv = "myuniqueivparamu";
$PING = date('d-m-Y H:i:s');

$json_file = "main.json";
$jsondata = file_exists($json_file) ? file_get_contents($json_file) : '{}';
$arrayData = json_decode($jsondata, true);
if (!is_array($arrayData)) { $arrayData = array(); }
$json = isset($arrayData['app']) && is_array($arrayData['app']) ? $arrayData['app'] : array();



$l = isset($_REQUEST['l']) ? $_REQUEST['l'] : '';
$an = isset($_REQUEST['an']) ? $_REQUEST['an'] : '';
$el = isset($_REQUEST['el']) ? $_REQUEST['el'] : '';
$ea = isset($_REQUEST['ea']) ? $_REQUEST['ea'] : '';
$eb = isset($_REQUEST['eb']) ? $_REQUEST['eb'] : '';
$key2 = $an.$json['customerid'];

function encode($str, $key){
	$sb = "";
	for ($i = 0; $i < strlen($str); $i++){
		 $sb .= (chr((ord($str[$i]) ^ ord($key[$i % strlen($key)]))));
	}
	return base64_encode($sb);
}

function sanitize($data) {
	$data = trim($data);
	$data = htmlspecialchars($data, ENT_QUOTES );
	$data = SQLite3::escapeString($data);
	return $data;
}

if (isset($_GET['tag'])){
	if ($Tag == "licV3"){
		echo bin2hex(openssl_encrypt(file_get_contents($json_file) , "AES-128-CBC", $key, OPENSSL_RAW_DATA, $iv));
	}
	if ($Tag == "licV4"){
		echo '
{
  "success": "1",
  "status": "ACTIVE",
  "cid": "'.$json["customerid"].'",
  "which": "licV4",
  "app": "'.encode(' {
    "id": "'.$json["id"].'",
    "appname": "'.$json["appname"].'",
    "expire": "'.$json["expire"].'",
    "login_type": "'.$json["login_type"].'",
    "version_code": "'.$json["version_code"].'",
    "filter_status": "'.$json["filter_status"].'",
    "epg_mode": "'.$json["epg_mode"].'",
    "apkautoupdate": "'.$json["apkautoupdate"].'",
    "show_expire": "'.$json["show_expire"].'"
  }', $key2.'app') .'",
  "portal": "'.encode(' {
    "panel": "'.$json["panel"].'",
    "portal": "'.$json["portal"].'",
    "portal2": "'.$json["portal2"].'",
    "portal3": "'.$json["portal3"].'",
    "portal4": "'.$json["portal4"].'",
    "portal5": "'.$json["portal5"].'",
    "portal_name": "'.$json["portal_name"].'",
    "portal2_name": "'.$json["portal2_name"].'",
    "portal3_name": "'.$json["portal3_name"].'",
    "portal4_name": "'.$json["portal4_name"].'",
    "portal5_name": "'.$json["portal5_name"].'",
    "portal_vod": "'.$json["portal_vod"].'",
    "portal_series": "'.$json["portal_series"].'"
  }', $key2.'portal') .'",
  "urls": "'.encode(' {
    "apkurl": "'.$json["apkurl"].'",
    "backupurl": "'.$json["backupurl"].'",
    "logurl": "'.$json["logurl"].'",
    "activation_url": "'.$json["activation_url"].'",
    "socket_url": "ottrun-ws",
    "epg_url": "'.$json["epg_url"].'",
    "ovpn_url": "'.$json["ovpn_url"].'"
  }', $key2.'urls') .'",
  "support": {
    "support_email": "'.$json["support_email"].'",
    "support_phone": "'.$json["support_phone"].'"
  },
  "button": "'.encode(' {
    "btn_live": "'.$json["btn_live"].'",
    "btn_live2": "'.$json["btn_live2"].'",
    "btn_live3": "'.$json["btn_live3"].'",
    "btn_live4": "'.$json["btn_live4"].'",
    "btn_live5": "'.$json["btn_live5"].'",
    "btn_vod": "'.$json["btn_vod"].'",
    "btn_vod2": "'.$json["btn_vod2"].'",
    "btn_vod3": "'.$json["btn_vod3"].'",
    "btn_vod4": "'.$json["btn_vod4"].'",
    "btn_vod5": "'.$json["btn_vod5"].'",
    "btn_epg": "'.$json["btn_epg"].'",
    "btn_epg2": "'.$json["btn_epg2"].'",
    "btn_epg3": "'.$json["btn_epg3"].'",
    "btn_epg4": "'.$json["btn_epg4"].'",
    "btn_epg5": "'.$json["btn_epg5"].'",
    "btn_series": "'.$json["btn_series"].'",
    "btn_series2": "'.$json["btn_series2"].'",
    "btn_series3": "'.$json["btn_series3"].'",
    "btn_series4": "'.$json["btn_series4"].'",
    "btn_series5": "'.$json["btn_series5"].'",
    "btn_radio": "'.$json["btn_radio"].'",
    "btn_radio2": "'.$json["btn_radio2"].'",
    "btn_radio3": "'.$json["btn_radio3"].'",
    "btn_radio4": "'.$json["btn_radio4"].'",
    "btn_radio5": "'.$json["btn_radio5"].'",
    "btn_catchup": "'.$json["btn_catchup"].'",
    "btn_catchup2": "'.$json["btn_catchup2"].'",
    "btn_catchup3": "'.$json["btn_catchup3"].'",
    "btn_catchup4": "'.$json["btn_catchup4"].'",
    "btn_catchup5": "'.$json["btn_catchup5"].'",
    "btn_account": "'.$json["btn_account"].'",
    "btn_account2": "'.$json["btn_account2"].'",
    "btn_account3": "'.$json["btn_account3"].'",
    "btn_pr": "'.$json["btn_pr"].'",
    "btn_rec": "'.$json["btn_rec"].'",
    "btn_vpn": "'.$json["btn_vpn"].'",
    "btn_noti": "'.$json["btn_noti"].'",
    "btn_update": "'.$json["btn_update"].'",
    "btn_login_settings": "'.$json["btn_login_settings"].'",
    "btn_login_account": "'.$json["btn_login_account"].'",
    "btn_fav": "'.$json["btn_fav"].'",
    "btn_fav2": "'.$json["btn_fav2"].'",
    "btn_fav3": "'.$json["btn_fav3"].'",
    "btn_signup": "'.$json["btn_signup"].'",
    "ms": "'.$json["ms"].'",
    "ms2": "'.$json["ms2"].'",
    "ms3": "'.$json["ms3"].'"
  }', $key2.'buttons') .'",
  "settings": "'.encode(' {
    "agent": "'.$json["agent"].'",
    "all_cat": "'.$json["all_cat"].'",
    "message_enabled": "'.$json["message_enabled"].'",
    "announcement_enabled": "'.$json["announcement_enabled"].'",
    "updateuserinfo_enabled": "'.$json["updateuserinfo_enabled"].'",
    "whatsupcheck_enabled": "'.$json["whatsupcheck_enabled"].'",
    "login_logo": "'.$json["login_logo"].'",
    "bjob": "'.$json["bjob"].'",
    "settings_app": "'.$json["settings_app"].'",
    "settings_account": "'.$json["settings_account"].'",
    "logs": "'.$json["logs"].'",
    "app_language": "'.$json["app_language"].'",
    "load_last_channel": "'.$json["load_last_channel"].'",
    "admob_banner_id": "'.$json["admob_banner_id"].'",
    "admob_interstitial_id": "'.$json["admob_interstitial_id"].'",
    "show_cat_count": "'.$json["show_cat_count"].'",
    "send_udid": "'.$json["send_udid"].'",
    "theme": "'.$json["theme"].'",
    "vpn_login_view": "yes"
  }', $key2.'sett') .'",
  "admobconfig":{
    "admob_enabled":"no"
  },
  "prebid":{
    "prebid_enabled":"no",
    "Host":"",
    "AdUnitId":"",
    "AccountId":"",
    "Banner":""
  },
  "vastconfig": {
    "vast_enabled":"no",
    "mid_roll_interval":"",
    "post_roll_start_at":"",
    "vod_mid_roll_interval":"",
    "vod_pre_roll_url":"",
    "vod_mid_roll_url":"",
    "vod_post_roll_url":"",
    "series_mid_roll_interval":"",
    "series_pre_roll_url":"",
    "series_mid_roll_url":"",
    "series_post_roll_url":""
  },
  "freestar":"no",
  "players":{
    "player":"EXO",
    "player_tv":"EXO",
    "player_vod":"VLC",
    "player_series":"VLC",
    "player_catchup":"VLC",
    "stream_type":"ts"
  },
  "ort_settings": {
    "vlc_hw":"yes",
    "last_volume_vlc":"100",
    "plyer_vlc_buffer":"5000",
    "video_resize_vlc":"0",
    "video_subtiltes_vlc":"yes",
    "exo_hw":"yes",
    "last_volume_exo":"100",
    "plyer_exo_buffer":"50000",
    "video_resize_exo":"0",
    "video_subtiltes_exo":"no"
  },
  "maintenance":{
    "mnt_message":"Maintenance Message",
    "mnt_status":"INACTIVE",
    "mnt_expire":"2019-05-31 23:59:00"
  }
}';
	}
	if ($Tag == "man" || $Tag == "ann"){
	echo file_get_contents("./connv2.json");
	}
	if ($Tag == "conn" || $Tag == "msg_conf"){
		echo '{"tag":"' . $Tag . '","success":"1","api_ver":"1.0v"}';
	}
	if ($Tag == "whatsup"){
		echo '{"tag":"whatsup","success":"0","api_ver":"1.0v","whatsup":"no"}';
	}
	if ($Tag == "gfilter"){
		echo '{"tag":"gfilter_n","success":"1","api_ver":"1.0v","status":"No","filter":[]}';
	}
    if ($Tag == "msg_cat_view" || $Tag == "msg")
    {
        $db = new SQLite3('./user_message.db');
        $res = $db->query("SELECT * FROM messages WHERE userid='" . $UserID . "'");
        $row = $res->fetchArray();
        $message = $row['message'];
        $userid = $row['userid'];
        $status = $row['status'];
        $expire = $row['expire'];
        if (empty($message))
        {
            echo '{"tag":"' . $Tag . '","success":"0","api_ver":"1.0v","message":"No Messages"}';
        }
        else
        {
            echo '{"tag":"' . $Tag . '","success":"1","api_ver":"1.0v","status":"$status","msgid":"1646","message":"$message"}';
        }
    }
	if($Tag == "connv2"){
		$LASTTIME = date('d-m-Y H:i:s');
		$TIME = date('d-m-Y H:i:s');

		if (isset($_GET['userid'])) {
			$UserID = $_GET['userid'];
		}else {
			$UserID = '';
		}

		$db1 = new SQLite3('./user_logs.db');
	$db1->exec('CREATE TABLE IF NOT EXISTS logging(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, appid TEXT, version TEXT, device TEXT, pkg TEXT, app TEXT, cid TEXT, uid TEXT, status TEXT, d TEXT, o TEXT, time TEXT, last_online TEXT, ping TEXT, IP_ADDRESS TEXT)');
		$res1 = $db1->query("SELECT * FROM logging WHERE uid='".$UserID."'" );

		while ($row5 = $res1->fetchArray()) {
			$app_id = $row5['appid'];
		}

          if (empty($app_id)) {
	$db1->exec("INSERT INTO logging(appid, version, device, pkg, app, cid, uid, status, d, time, ping, IP_ADDRESS) 
				VALUES( '" . $_GET['appid'] . "',
						'" . $_GET['version'] . "',
						'" . $_GET['device_type'] . "',
						'" . $_GET['p'] . "',
						'" . $_GET['an'] . "',
						'" . $_GET['customerid'] . "',
						'" . $_GET['userid'] . "',
						'" . $_GET['online'] . "',
						'" . $_GET['did'] . "',
						'" . $TIME . "',
						'" . $PING . "',
						'" . $IPADDRESS . "'
						)");
}
		else if ($_GET['online'] == 'yes') {
			$db1->exec("UPDATE logging SET  appid='" . $_GET['appid'] . "',
											version='" . $_GET['version'] . "',
											device='" . $_GET['device_type'] . "',
											pkg='" . $_GET['p'] . "',
											app='" . $_GET['an'] . "',
											cid='" . $_GET['customerid'] . "',
											status='" . $_GET['online'] . "',
											d='" . $_GET['did'] . "',
											last_online='" . $LASTTIME . "',
											ping='" . $PING . "',
											IP_ADDRESS='" . $IPADDRESS . "'
										WHERE uid='" . $_GET['userid'] . "'
										");
		}
		else {
			$db1->exec("UPDATE logging SET  appid='" . $_GET['appid'] . "',
											version='" . $_GET['version'] . "',
											device='" . $_GET['device_type'] . "',
											pkg='" . $_GET['p'] . "',
											app='" . $_GET['an'] . "',
											cid='" . $_GET['customerid'] . "',
											status='" . $_GET['online'] . "',
											d='" . $_GET['did'] . "',
											ping='" . $PING . "',
											IP_ADDRESS='" . $IPADDRESS . "'
										WHERE uid='" . $_GET['userid'] . "'
										");
		}



		$db = new SQLite3('./user_message.db');
		$stmt = $db->prepare("SELECT * FROM messages WHERE userid=?");
		$stmt->bindValue(1, sanitize($UserID));
		$res = $stmt->execute();
		$row = $res->fetchArray() ;
		$msgid = $row['id'];
		$message = $row['message'];
		$userid = $row['userid'];
		$status = $row['status'];
		$expire = $row['expire'];
		$jsonData = file_get_contents("./connv2.json");
		if($message != ''){
			$arrayData = json_decode($jsonData, true);
			$replacementData = array(
				'success' => '1',
				'message' => $message,
				'msg_status' => $status,
				'msg_expire' => $expire,
				'msgid' => '1646'
			);
			$newArrayData = array_replace_recursive($arrayData, $replacementData);
			$newJsonData = json_encode($newArrayData, JSON_PRETTY_PRINT);
			echo $newJsonData;
		}else{
			echo file_get_contents("./connv2.json");
		}
	}
    if($Tag == "vpnconfigV2")
    {
        $output = '{"tag":"vpnconfigV2","success":"1","api_ver":"1.0v","vpnconfigs":[';

        $db = new SQLite3('./vpn.db');
        $res = $db->query("SELECT * FROM vpnconfig");

        while ($row = $res->fetchArray()) {
            $id = $row['id'];
            $userid = $row['userid'];
            $vpn_appid = $row['vpn_appid'];
            $vpn_country = $row['vpn_country'];
            $vpn_state = $row['vpn_state'];
            $vpn_config = $row['vpn_config'];
            $vpn_status = $row['vpn_status'];
            $auth_type = $row['auth_type'];
            $auth_embedded = $row['auth_embedded'];
            $username = $row['username'];
            $password = $row['password'];
            $vdate = $row['vdate'];
            if(!empty($vpn_config))
            {
                $output.='{"id":"'.$id.'","userid":"'.$cid.'","vpn_appid":"'.$aid.'","vpn_country":"'.$vpn_country.'","vpn_state":"'.$vpn_state.'","vpn_config":"'.$vpn_config.'","vpn_status":"'.$vpn_status.'","auth_type":"'.$auth_type.'","auth_embedded":"'.$auth_embedded.'","username":"'.$username.'","password":"'.$password.'","date":"'.$vdate.'"},';
            }
        }
        $x = substr($output, -1);
        if($x == ",")
        {
            $output=substr_replace($output,"",-1);
        }
        $output.=']}';
        echo bin2hex(openssl_encrypt($output, "AES-128-CBC", "mysecretkeywsdef", OPENSSL_RAW_DATA, "myuniqueivparamu"));
    }




// API per generare MAC fittizio nuovo per portale.
// Può essere richiamata dall'app modificata o dal pannello: ApiIPTV.php?tag=generateMac&portal_slot=2
if (isset($_GET['tag']) && $_GET['tag'] == 'generateMac') {
    header('Content-Type: application/json; charset=utf-8');
    $portal_slot = 1;
    if (isset($_GET['portal_slot'])) { $portal_slot = intval($_GET['portal_slot']); }
    elseif (isset($_GET['portal'])) { $portal_slot = intval($_GET['portal']); }
    elseif (isset($_GET['slot'])) { $portal_slot = intval($_GET['slot']); }
    if ($portal_slot < 1 || $portal_slot > 5) { $portal_slot = 1; }

    try {
        if (!class_exists('SQLite3')) { throw new Exception('SQLite3 not enabled'); }
        $db = new SQLite3(__DIR__ . '/mac_users.db');
        $exists = $db->querySingle("SELECT name FROM sqlite_master WHERE type='table' AND name='mac_auth'");
        if (!$exists) {
            $db->exec("CREATE TABLE mac_auth (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                mac_address TEXT NOT NULL,
                portal_slot INTEGER NOT NULL DEFAULT 1,
                username TEXT NOT NULL DEFAULT '',
                password TEXT NOT NULL DEFAULT '',
                status TEXT DEFAULT 'ACTIVE',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_access DATETIME,
                notes TEXT,
                UNIQUE(mac_address, portal_slot)
            )");
        }
        $columns = [];
        $colsRes = $db->query('PRAGMA table_info(mac_auth)');
        while ($col = $colsRes->fetchArray(SQLITE3_ASSOC)) { $columns[] = $col['name']; }
        if (!in_array('portal_slot', $columns)) { $db->exec('ALTER TABLE mac_auth ADD COLUMN portal_slot INTEGER NOT NULL DEFAULT 1'); }

        $mac = '';
        for ($i = 0; $i < 50; $i++) {
            $candidate = strtoupper(sprintf('%02X:%02X:%02X:%02X', 0x02, random_int(0,255), random_int(0,255), random_int(0,255)));
            $stmt = $db->prepare('SELECT COUNT(*) AS c FROM mac_auth WHERE mac_address = ? AND portal_slot = ?');
            $stmt->bindValue(1, $candidate, SQLITE3_TEXT);
            $stmt->bindValue(2, $portal_slot, SQLITE3_INTEGER);
            $row = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
            if (intval($row['c']) === 0) { $mac = $candidate; break; }
        }
        if ($mac === '') { throw new Exception('generate failed'); }
        echo json_encode(['success'=>'1','mac'=>$mac,'portal_slot'=>(string)$portal_slot]);
        $db->close();
    } catch (Throwable $e) {
        echo json_encode(['success'=>'0','message'=>'Generate MAC error']);
    }
    exit;
}

// API para autenticação por MAC Address - MULTI PORTALE
// Compatibile con vecchia app: se portal_slot non viene inviato, usa il primo servizio ACTIVE del MAC.
if (isset($_GET['tag']) && $_GET['tag'] == 'getMacAuth') {
    $mac = isset($_GET['mac']) ? trim($_GET['mac']) : '';
    $mac_clean = preg_replace('/[^A-Fa-f0-9]/', '', (string)$mac);
    if (strlen($mac_clean) >= 8) {
        $mac = strtoupper(implode(':', str_split(substr($mac_clean, 0, 8), 2)));
    }
    $portal_slot = 0;

    if (isset($_GET['portal_slot'])) {
        $portal_slot = intval($_GET['portal_slot']);
    } elseif (isset($_GET['portal'])) {
        $portal_slot = intval($_GET['portal']);
    } elseif (isset($_GET['slot'])) {
        $portal_slot = intval($_GET['slot']);
    } elseif (isset($_GET['service'])) {
        $portal_slot = intval($_GET['service']);
    }

    if ($portal_slot < 1 || $portal_slot > 5) {
        $portal_slot = 0;
    }

    header('Content-Type: application/json; charset=utf-8');

    if (empty($mac)) {
        echo json_encode(['success' => '0', 'message' => 'MAC address required']);
        exit;
    }

    if (!class_exists('SQLite3')) {
        echo json_encode(['success' => '0', 'message' => 'SQLite3 not enabled on server']);
        exit;
    }

    try {
        $db = new SQLite3(__DIR__ . '/mac_users.db');

        $exists = $db->querySingle("SELECT name FROM sqlite_master WHERE type='table' AND name='mac_auth'");
        if (!$exists) {
            $db->exec("CREATE TABLE mac_auth (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                mac_address TEXT NOT NULL,
                portal_slot INTEGER NOT NULL DEFAULT 1,
                username TEXT NOT NULL,
                password TEXT NOT NULL,
                status TEXT DEFAULT 'ACTIVE',
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
                last_access DATETIME,
                notes TEXT,
                UNIQUE(mac_address, portal_slot)
            )");
        }

        $columns = [];
        $colsRes = $db->query('PRAGMA table_info(mac_auth)');
        while ($col = $colsRes->fetchArray(SQLITE3_ASSOC)) {
            $columns[] = $col['name'];
        }
        if (!in_array('portal_slot', $columns)) {
            $db->exec('ALTER TABLE mac_auth ADD COLUMN portal_slot INTEGER NOT NULL DEFAULT 1');
        }

        if ($portal_slot > 0) {
            $stmt = $db->prepare('SELECT id, username, password, status, portal_slot FROM mac_auth WHERE mac_address = ? AND portal_slot = ? LIMIT 1');
            $stmt->bindValue(1, $mac, SQLITE3_TEXT);
            $stmt->bindValue(2, $portal_slot, SQLITE3_INTEGER);
        } else {
            $stmt = $db->prepare('SELECT id, username, password, status, portal_slot FROM mac_auth WHERE mac_address = ? AND status = "ACTIVE" ORDER BY portal_slot ASC, id ASC LIMIT 1');
            $stmt->bindValue(1, $mac, SQLITE3_TEXT);
        }

        $result = $stmt->execute();
        $row = $result->fetchArray(SQLITE3_ASSOC);

        if ($row && $row['status'] == 'ACTIVE') {
            $updateStmt = $db->prepare('UPDATE mac_auth SET last_access = CURRENT_TIMESTAMP WHERE id = ?');
            $updateStmt->bindValue(1, intval($row['id']), SQLITE3_INTEGER);
            $updateStmt->execute();

            echo json_encode([
                'success' => '1',
                'username' => $row['username'],
                'password' => $row['password'],
                'portal_slot' => (string)$row['portal_slot']
            ]);
        } else {
            echo json_encode(['success' => '0', 'message' => 'MAC not found or inactive']);
        }

        $db->close();
    } catch (Throwable $e) {
        echo json_encode(['success' => '0', 'message' => 'Database error']);
    }
    exit;
}


}
else
{
// IPCfkLggR2l6bW8g8J+QuA==
    include ('index.php');
}
?>