<?php
/**
 * Helper functions for the project
 */

// Ensure database config is loaded to have access to BASE_URL
if (!defined('BASE_URL')) {
    require_once __DIR__ . '/../config/database.php';
}

/**
 * Get the base URL of the project
 * @return string The base URL
 */
if (!function_exists('get_base_url')) {
    function get_base_url() {
        return defined('BASE_URL') ? BASE_URL : '';
    }
}

/**
 * Generate an absolute URL from a relative path
 * @param string $path Relative path from the project root
 * @return string Absolute URL
 */
if (!function_exists('build_absolute_url')) {
    function build_absolute_url($path) {
        $base_url = get_base_url();
        // Ensure path starts with a forward slash
        if (substr($path, 0, 1) !== '/') {
            $path = '/' . $path;
        }
        return $base_url . $path;
    }
}

/**
 * Get the current page URL
 * @return string Current page URL
 */
if (!function_exists('get_current_url')) {
    function get_current_url() {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https' : 'http';
        return $protocol . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }
}

/**
 * Redirect to a page using the base URL
 * @param string $path Path to redirect to
 * @param bool $exit Whether to exit after redirect
 */
if (!function_exists('redirect_to')) {
    function redirect_to($path, $exit = true) {
        $url = build_absolute_url($path);
        header("Location: $url");
        if ($exit) {
            exit();
        }
    }
}
?>