<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->


// ================= CONFIG =================
try {
    @$config_ini = parse_ini_file(dirname(__DIR__) . "/config.ini");
} catch (Exception $e) {
    @$config_ini = [];
}

if (!empty($config_ini['debug']) && $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);
}

// ================= SESSION =================
if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}

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

// ================= PATHS (FORA DE /includes) =================
$apiDir = dirname(__DIR__) . '/api';
$dbPath = $apiDir . '/.db.db';

// cria pasta /api se não existir
if (!is_dir($apiDir)) {
    mkdir($apiDir, 0755, true);
}

// ================= SQLITE WRAPPER =================
class SQLiteWrapper {
    private $db;

    public function __construct($dbLoc) {
        $this->db = new SQLite3($dbLoc);
    }

    public function select($table, $columns="*", $where="", $orderBy="", $params=[]) {
        $sql = "SELECT $columns FROM $table";
        if ($where) $sql .= " WHERE $where";
        if ($orderBy) $sql .= " ORDER BY $orderBy";

        $stmt = $this->db->prepare($sql);
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }

        $res = $stmt->execute();
        $rows = [];
        while ($row = $res->fetchArray(SQLITE3_ASSOC)) {
            $rows[] = $row;
        }
        return $rows;
    }

    public function insert($table, $data) {
        $cols = implode(', ', array_keys($data));
        $vals = ':' . implode(', :', array_keys($data));
        $stmt = $this->db->prepare("INSERT INTO $table ($cols) VALUES ($vals)");
        foreach ($data as $k => $v) {
            $stmt->bindValue(":$k", $v);
        }
        return $stmt->execute();
    }

    public function update($table, $data, $where, $params) {
        $set = [];
        foreach ($data as $k => $v) {
            $set[] = "$k = :$k";
        }
        $sql = "UPDATE $table SET " . implode(', ', $set) . " WHERE $where";
        $stmt = $this->db->prepare($sql);

        foreach ($data as $k => $v) {
            $stmt->bindValue(":$k", $v);
        }
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        return $stmt->execute();
    }

    public function delete($table, $where, $params) {
        $stmt = $this->db->prepare("DELETE FROM $table WHERE $where");
        foreach ($params as $k => $v) {
            $stmt->bindValue($k, $v);
        }
        return $stmt->execute();
    }

    // ✔ usado pelo index.php
    public function insertIfEmpty($table, $data) {
        if ($this->isEmptyTable($table)) {
            $cols = implode(', ', array_keys($data));
            $vals = ':' . implode(', :', array_keys($data));
            $stmt = $this->db->prepare("INSERT INTO $table ($cols) VALUES ($vals)");
            foreach ($data as $k => $v) {
                $stmt->bindValue(":$k", $v);
            }
            return $stmt->execute();
        }
        return false;
    }

    private function isEmptyTable($table) {
        $res = $this->db->query("SELECT COUNT(*) AS c FROM $table");
        $row = $res->fetchArray(SQLITE3_ASSOC);
        return ((int)$row['c'] === 0);
    }

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

// ================= DB INIT =================
$db = new SQLiteWrapper($dbPath);

// ================= TABLES =================
function createTables($dbPath) {
    $db = new SQLite3($dbPath);

    $db->exec("CREATE TABLE IF NOT EXISTS user (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        username TEXT,
        password TEXT
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS dns (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        title TEXT,
        url TEXT,
        epg_url TEXT
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS note (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        note_title TEXT,
        note_content TEXT,
        createdate TEXT
    )");

    $db->exec("CREATE TABLE IF NOT EXISTS welcome (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        message_one TEXT,
        message_two TEXT,
        message_three TEXT
    )");

    $db->close();
}

createTables($dbPath);

// ================= REAL IP =================
function real_ip() {
    return htmlspecialchars(
        $_SERVER['HTTP_X_FORWARDED_FOR']
        ?? $_SERVER['HTTP_CLIENT_IP']
        ?? $_SERVER['REMOTE_ADDR']
        ?? '0.0.0.0',
        ENT_QUOTES,
        'UTF-8'
    );
}