<?php
require_once 'inc/config.php';

// Function to return absolute integer value
function fl($m) {
    return abs(intval($m));
}

class DB {
    protected static $instance = null;

    private function __construct() {}
    private function __clone() {}

    // Method to initialize database connection with custom parameters
    public static function init($host, $dbname, $user, $pass, $opt = []) {
        if (self::$instance === null) {
            $dsn = 'mysql:host=' . $host . ';dbname=' . $dbname . ';charset=utf8mb4';
            $defaultOptions = [
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
                PDO::ATTR_EMULATE_PREPARES => false,
            ];
            $options = array_replace_recursive($defaultOptions, $opt);

            self::$instance = new PDO($dsn, $user, $pass, $options);
        }
    }

    // Singleton pattern to get database instance
    public static function instance() {
        if (self::$instance === null) {
            throw new Exception("Database connection is not initialized. Call DB::init method first.");
        }
        return self::$instance;
    }

    // Magic method to call instance methods statically
    public static function __callStatic($method, $args) {
        return call_user_func_array([self::instance(), $method], $args);
    }

    // Method to run SQL query
    public static function run($sql, $args = []) {
        $stmt = $args ? self::instance()->prepare($sql) : self::instance()->query($sql);
        $stmt->execute($args);
        return $stmt;
    }
}

// Function to get current page
function page($k_page = 1) {
    $page = 1;
    if (isset($_GET['page'])) {
        if ($_GET['page'] == 'end') {
            $page = intval($k_page);
        } elseif (is_numeric($_GET['page'])) {
            $page = intval($_GET['page']);
        }
    }
    if ($page < 1) {
        $page = 1;
    }
    if ($page > $k_page) {
        $page = $k_page;
    }
    return $page;
}

// Function to calculate number of pages
function k_page($k_post = 0, $k_p_str = 10) {
    if ($k_post != 0) {
        return ceil($k_post / $k_p_str);
    } else {
        return 1;
    }
}
?>
