<?php
/**
 * ============================================================================
 * includes/media-helpers.php - Media URL Helper Functions
 * ============================================================================
 */

if (!function_exists('getMediaUrl')) {
    /**
     * Get media URL (for stories, posts, etc.)
     * Handles both relative paths and full URLs
     */
    function getMediaUrl($mediaPath = null) {
        if (empty($mediaPath)) {
            return null;
        }
        
        // If it's already a full URL, return as is
        if (strpos($mediaPath, 'http') === 0) {
            return $mediaPath;
        }
        
        // If it's a relative path, construct full URL
        return APP_URL . '/' . ltrim($mediaPath, '/');
    }
}

if (!function_exists('getAvatarUrlEnhanced')) {
    /**
     * Enhanced get avatar URL function
     * Handles both relative paths and full URLs
     */
    function getAvatarUrlEnhanced($profilePicture = null) {
        if (!empty($profilePicture)) {
            // If it's already a full URL, return as is
            if (strpos($profilePicture, 'http') === 0) {
                return $profilePicture;
            }
            
            // If file exists, return the URL
            $fullPath = __DIR__ . '/../' . ltrim($profilePicture, '/');
            if (file_exists($fullPath)) {
                return APP_URL . '/' . ltrim($profilePicture, '/');
            }
        }
        return APP_URL . '/assets/images/default-avatar.png';
    }
}

if (!function_exists('cleanMediaPath')) {
    /**
     * Clean media path - remove APP_URL if present
     * Use this when storing paths in database
     */
    function cleanMediaPath($url) {
        if (empty($url)) {
            return null;
        }
        
        // Remove APP_URL if present
        $url = str_replace(APP_URL . '/', '', $url);
        $url = str_replace(APP_URL, '', $url);
        
        // Remove leading slash
        $url = ltrim($url, '/');
        
        return $url;
    }
}
?>