<?php
include(__DIR__ . '/db.php');
//parse config options
try {
	@$config_ini = parse_ini_file("./config.ini");
} catch (Exception $e) {
	@$config_ini = parse_ini_file("../config.ini");
}

if (@$config_ini['debug'] == 1 ){
	ini_set('display_errors', 1);
	ini_set('display_startup_errors', 1);
	error_reporting(E_ALL);
}else{
	ini_set('display_errors', 0);
}

$status = session_status();
if($status == PHP_SESSION_NONE){
	session_start();
}else
if($status == PHP_SESSION_DISABLED){
	//Sessions are not available
}else
if($status == PHP_SESSION_ACTIVE){
	//Destroy current and start new one
	session_destroy();
	session_start();
}


function generate_token() {
	if(!isset($_SESSION["ftg"])) {
		$token = random_bytes(64);
		$_SESSION["ftg"] = $token;
	} else {
		$token = $_SESSION["ftg"];
	}
	return $token;
}

function createTables($tables, $dbLoc) {
	try {
		$db = new SQLite3($dbLoc);
	} catch (Exception $e) {
		$db = new SQLite3('.db.db');
	}

	if (!$db) {
		die("Error connecting to the database");
	}

	foreach ($tables as $tableName => $columns) {
		$sql = "CREATE TABLE IF NOT EXISTS $tableName (";
		foreach ($columns as $columnName => $columnType) {
			$sql .= "$columnName $columnType, ";
		}
		$sql = rtrim($sql, ', ');
		$sql .= ");";
		if ($db->exec($sql)) {
		} else {
			echo "Error creating table: " . $db->lastErrorMsg();
		}
	}
	$db->close();
}


$tables = [
	"user" => [
		"id" => "INTEGER PRIMARY KEY",
		"username" => "TEXT NOT NULL",
		"password" => "TEXT NOT NULL",
	],
	"dns" => [
		"id" => "INTEGER PRIMARY KEY",
		"title" => "TEXT",
		"url" => "TEXT",
	],
	"announcements" => [
		"id" => "INTEGER PRIMARY KEY",
		"title" => "TEXT",
		"message" => "TEXT",
		"created_on" => "TEXT",
	],
	"seen_announ" => [
		"id" => "INTEGER PRIMARY KEY",
		"device_id" => "TEXT",
		"annouse_is" => "TEXT",
		"status" => "TEXT",
	],
	"reports" => [
		"id" => "INTEGER PRIMARY KEY",
		"username" => "TEXT",
		"macaddress" => "TEXT",
		"section" => "TEXT",
		"section_category" => "TEXT",
		"report_title" => "TEXT",
		"stream_name" => "TEXT",
		"stream_id" => "TEXT",
		"report_sub_title" => "TEXT",
		"report_cases" => "TEXT",
		"report_custom_message" => "TEXT",
	],
	"feedback" => [
		"id" => "INTEGER PRIMARY KEY",
		"username" => "TEXT",
		"macaddress" => "TEXT",
		"feedback_content" => "TEXT",
	],
	"vpn" => [
		"id" => "INTEGER PRIMARY KEY",
		"location" => "TEXT",
		"file_name" => "TEXT",
		"username" => "TEXT",
		"password" => "TEXT",
	],
	"credentials" => [
		"id" => "INTEGER PRIMARY KEY",
		"visibal" => "TEXT",
		"type" => "TEXT",
	],
	"maintenance" => [
		"id" => "INTEGER PRIMARY KEY",
		"title" => "TEXT",
		"body" => "TEXT",
		"mode" => "TEXT",
	],
	"devices" => [
		"id" => "INTEGER PRIMARY KEY",
		"deviceid" => "TEXT",
		"deviceusername" => "TEXT",
		"added_on" => "TEXT",
	],
	"textads" => [
		"id" => "INTEGER PRIMARY KEY",
		"adstext" => "TEXT",
		"status" => "TEXT",
	],
	"modsetings" => [
		"id" => "INTEGER PRIMARY KEY",
		"preffile" => "TEXT",
		"preftype" => "TEXT",
		"prefname" => "TEXT",
    	"mods" => "TEXT",
	],
	"adssettings" => [
		"id" => "INTEGER PRIMARY KEY",
		"adstype" => "TEXT",
	],
	"autolayout" => [
		"id" => "INTEGER PRIMARY KEY",
		"layout" => "TEXT",
	],
	"extlink" => [
		"id" => "INTEGER PRIMARY KEY",
		"link" => "TEXT",
	],
	"pop" => [
		"id" => "INTEGER PRIMARY KEY",
		"status" => "TEXT",
		"uuid" => "TEXT",
		"link" => "TEXT",
	],
	"leaguesx" => [
		"id" => "INTEGER PRIMARY KEY",
    	"league" => "TEXT",
    	"leagueId" => "TEXT",
    	
	],
	"leaguestable" => [
		"id" => "INTEGER PRIMARY KEY",
    	"league" => "TEXT",
    	"leagueId" => "TEXT",
    	
	],
	"leagueshift" => [
		"id" => "INTEGER PRIMARY KEY",
    	"cla" => "TEXT",
    	"time" => "TEXT",
    	
	],
	"addui" => [
		"id" => "INTEGER PRIMARY KEY",
    	"theme_name" => "TEXT",
    	"assets_name" => "TEXT",
    	"priv_image" => "TEXT",
    	
	],
	"landing" => [
		"id" => "INTEGER PRIMARY KEY",
    	"main_titial" => "TEXT",
    	"main_sub_titial" => "TEXT",
    	"info_titial" => "TEXT",
    	"info_sub_titial" => "TEXT",
    	"info_cat1_titial" => "TEXT",
    	"info_cat2_titial" => "TEXT",
    	"info_cat3_titial" => "TEXT",
    	"info_sub1_titial" => "TEXT",
    	"info_sub2_titial" => "TEXT",
    	"info_sub3_titial" => "TEXT",
    	"getapp_titial" => "TEXT",
    	"getapp_sub_titial" => "TEXT",
    	"download_apk_link" => "TEXT",
    	"downloade_link" => "TEXT",
    	"contact_us_link" => "TEXT",
    	
    	
	],
	"exsport" => [
		"id" => "INTEGER PRIMARY KEY",
    	"name" => "TEXT",
    	"link" => "TEXT",
    	
	],
	"tsdbapi" => [
		"id" => "INTEGER PRIMARY KEY",
    	"methord" => "TEXT",
    	"key" => "TEXT",
    	
	],
	"bdimage" => [
		"id" => "INTEGER PRIMARY KEY",
    	"link" => "TEXT",
    	
	],
	"bdtube" => [
		"id" => "INTEGER PRIMARY KEY",
    	"link" => "TEXT",
    	
	],
	"bdtextanim" => [
		"id" => "INTEGER PRIMARY KEY",
    	"text" => "TEXT",
    	"layout" => "TEXT",
    	
	],
	"menuads" => [
		"id" => "INTEGER PRIMARY KEY",
    	"title" => "TEXT",
		"url" => "TEXT",
	],
];

createTables($tables, $dbPath);

class SQLiteWrapper {
	private $db;

	public function __construct($dbLoc) {
		
		try {
			$this->db = new SQLite3($dbLoc);
		} catch (Exception $e) {
			$this->db = new SQLite3('.db.db');
		}
		if (!$this->db) {
			die("Error: Unable to open database.");
		}
	}

	public function select($tableName, $columns = "*", $where = "", $orderBy = "", $placeholders = array()) {
		$query = "SELECT $columns FROM $tableName";
		if (!empty($where)) {
			$query .= " WHERE $where";
		}
		if (!empty($orderBy)) {
			$query .= " ORDER BY $orderBy";
		}
	
		$stmt = $this->db->prepare($query);
	
		foreach ($placeholders as $key => $value) {
			$stmt->bindValue($key, $value);
		}
	
		$result = $stmt->execute();
	
		$data = array();
		while ($row = $result->fetchArray(SQLITE3_ASSOC)) {
			$data[] = $row;
		}
		return $data;
	}
	
	
	
	public function insert($tableName, $data) {
		$columns = implode(', ', array_keys($data));
		$placeholders = ':' . implode(', :', array_keys($data));
		$query = "INSERT INTO $tableName ($columns) VALUES ($placeholders)";
	
		$stmt = $this->db->prepare($query);
	
		foreach ($data as $key => $value) {
			$stmt->bindValue(':' . $key, $value);
		}
	
		return $stmt->execute();
	}
	
	public function insertOrReplace($tableName, $data) {
        $columns = implode(', ', array_keys($data));
        $placeholders = ':' . implode(', :', array_keys($data));
        $query = "INSERT OR REPLACE INTO $tableName ($columns) VALUES ($placeholders)";

        $stmt = $this->db->prepare($query);

        foreach ($data as $key => $value) {
            $stmt->bindValue(':' . $key, $value);
        }

        return $stmt->execute();
    }

	
	public function update($tableName, $data, $where = "", $placeholders = array()) {
		$setValues = [];
		foreach ($data as $column => $value) {
			$setValues[] = "$column = :$column";
		}
		$setClause = implode(', ', $setValues);
		$query = "UPDATE $tableName SET $setClause";
		if (!empty($where)) {
			$query .= " WHERE $where";
		}
		
		$stmt = $this->db->prepare($query);
	
		foreach ($data as $key => $value) {
			$stmt->bindValue(':' . $key, $value);
		}
	
		foreach ($placeholders as $key => $value) {
			$stmt->bindValue($key, $value);
		}
	
		return $stmt->execute();
	}


	public function delete($tableName, $where = "", $placeholders = array()) {
		$query = "DELETE FROM $tableName";
		if (!empty($where)) {
			$query .= " WHERE $where";
		}
	
		$stmt = $this->db->prepare($query);
	
		foreach ($placeholders as $key => $value) {
			$stmt->bindValue($key, $value);
		}
	
		return $stmt->execute();
	}
	
    public function deletetable($tableName) {
        try {
            // Sanitize table name to prevent injection
            if (!preg_match('/^[a-zA-Z0-9_]+$/', $tableName)) {
                throw new Exception("Invalid table name");
            }

            // Build query
            $query = "DELETE FROM `$tableName`"; // Backticks for safety

            // Prepare and execute
            $stmt = $this->db->prepare($query);
            return $stmt->execute();
        } catch (Exception $e) {
            // Log error for debugging
            error_log("Delete error: " . $e->getMessage());
            return false;
        }
    }


	public function insertIfEmpty($tableName, $data) {
		$isEmpty = $this->isEmptyTable($tableName);

		if ($isEmpty) {
			$columns = implode(', ', array_keys($data));
			$values = "'" . implode("', '", $data) . "'";
			$query = "INSERT INTO $tableName ($columns) VALUES ($values)";
			return $this->db->exec($query);
		} else {
			return false;
		}
	}
	private function isEmptyTable($tableName) {
		$result = $this->db->query("SELECT COUNT(*) as count FROM $tableName");
		$row = $result->fetchArray(SQLITE3_ASSOC);
		return ($row['count'] == 0);
	}

	public function getLastInsertId() {
		return $this->db->lastInsertRowID();
	}

	public function close() {
		$this->db->close();
	}
}


class Encryption {

    public static function run($input) {
    	$main = bin2hex($input);
    	$output = strrev($main);
    	return $output;
	} 
}

class calllink {

	public static function run($api_link){
        $returnData = "0";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $api_link);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        $result = json_decode(curl_exec($ch));
        if (!empty($result)) {
            $returndata = $result;
            return ["result" => "success", "data" => $returndata];
        }
	}
}


////Get User IP
function real_ip() {
	$ip = 'undefined';
	if (isset($_SERVER)) {
		$ip = $_SERVER['REMOTE_ADDR'];
		if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
		elseif (isset($_SERVER['HTTP_CLIENT_IP'])) $ip = $_SERVER['HTTP_CLIENT_IP'];
	} else {
		$ip = getenv('REMOTE_ADDR');
		if (getenv('HTTP_X_FORWARDED_FOR')) $ip = getenv('HTTP_X_FORWARDED_FOR');
		elseif (getenv('HTTP_CLIENT_IP')) $ip = getenv('HTTP_CLIENT_IP');
	}
	$ip = htmlspecialchars($ip, ENT_QUOTES, 'UTF-8');
	return $ip;
}
