<?php
/**
 * Common Functions
 * GHAMECC Choir Management Platform
 * 
 * This file contains common utility functions used throughout the application.
 */

// Include database connection and functions
require_once __DIR__ . '/../config/database.php';

/**
 * Format date to a readable format
 * 
 * @param string $date Date string in any format
 * @param string $format Output format (default: 'd M Y')
 * @return string Formatted date
 */
function formatDate($date, $format = 'd M Y') {
    if (empty($date)) return '';
    return date($format, strtotime($date));
}

/**
 * Format currency value
 * 
 * @param float $amount Amount to format
 * @param string $currency Currency symbol (default: '₵')
 * @return string Formatted currency
 */
function formatCurrency($amount, $currency = '₵') {
    return $currency . ' ' . number_format($amount, 2);
}

/**
 * Generate a random string
 * 
 * @param int $length Length of the string
 * @return string Random string
 */
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

/**
 * Check if a string starts with a specific substring
 * 
 * @param string $haystack The string to search in
 * @param string $needle The substring to search for
 * @return bool True if haystack starts with needle
 */
function startsWith($haystack, $needle) {
    return substr($haystack, 0, strlen($needle)) === $needle;
}

/**
 * Check if a string ends with a specific substring
 * 
 * @param string $haystack The string to search in
 * @param string $needle The substring to search for
 * @return bool True if haystack ends with needle
 */
function endsWith($haystack, $needle) {
    return substr($haystack, -strlen($needle)) === $needle;
}

/**
 * Truncate a string to a specified length and append ellipsis if needed
 * 
 * @param string $string String to truncate
 * @param int $length Maximum length
 * @param string $append String to append if truncated (default: '...')
 * @return string Truncated string
 */
function truncateString($string, $length, $append = '...') {
    if (strlen($string) <= $length) {
        return $string;
    }
    
    return substr($string, 0, $length) . $append;
}

/**
 * Alias for truncateString function for backward compatibility
 * 
 * @param string $string String to truncate
 * @param int $length Maximum length
 * @param string $append String to append if truncated (default: '...')
 * @return string Truncated string
 */
function truncateText($string, $length, $append = '...') {
    return truncateString($string, $length, $append);
}

/**
 * Convert a string to slug format (lowercase, hyphens)
 * 
 * @param string $string String to convert
 * @return string Slug
 */
function slugify($string) {
    // Replace non-alphanumeric characters with hyphens
    $string = preg_replace('/[^a-zA-Z0-9]/', '-', $string);
    // Replace multiple hyphens with a single hyphen
    $string = preg_replace('/-+/', '-', $string);
    // Trim hyphens from beginning and end
    $string = trim($string, '-');
    // Convert to lowercase
    return strtolower($string);
}

/**
 * Calculate time elapsed since a given date
 * 
 * @param string $datetime Date/time string
 * @return string Human-readable time elapsed (e.g., "2 hours ago", "3 days ago")
 */
function timeElapsed($datetime) {
    $time = time() - strtotime($datetime);
    
    if ($time < 1) return 'just now';
    
    $tokens = array (
        31536000 => 'year',
        2592000 => 'month',
        604800 => 'week',
        86400 => 'day',
        3600 => 'hour',
        60 => 'minute',
        1 => 'second'
    );
    
    foreach ($tokens as $unit => $text) {
        if ($time < $unit) continue;
        $numberOfUnits = floor($time / $unit);
        return $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '') . ' ago';
    }
    
    return 'unknown';
}

/**
 * Clean text content by removing multiple layers of escaping
 * 
 * @param string $text Text to clean
 * @param bool $preserveHtml Whether to preserve HTML tags or strip them
 * @return string Cleaned text
 */
function cleanText($text, $preserveHtml = true) {
    if (empty($text)) return '';
    
    // Remove multiple layers of slashes
    while (strpos($text, '\\') !== false) {
        $before = $text;
        $text = stripslashes($text);
        // Prevent infinite loop if stripslashes doesn't change anything
        if ($before === $text) break;
    }
    
    // Decode HTML entities
    $text = html_entity_decode($text, ENT_QUOTES | ENT_HTML5, 'UTF-8');
    
    // Strip HTML tags if not preserving HTML
    if (!$preserveHtml) {
        $text = strip_tags($text);
    }
    
    return $text;
}
?>
