<?php

use \Carbon\Carbon;

/**
 * Format date for display
 *
 * @param string|Carbon|null $date
 * @param bool $includeTime Optional, default true
 * @param string|null $format Optional PHP date format override
 * @return string
 */
function formatDate($date, bool $includeTime = true, ?string $format = null): string
{
    if (empty($date)) {
        return '-';
    }

    try { 
        $carbonDate = Carbon::createFromFormat('Y-m-d', substr($date, 0, 10)); 

        if ($format) {
            $fmt = $format;
        } else {
            $fmt = $includeTime ? 'M d, Y H:i' : 'M d, Y';
        }

        return $carbonDate->format($fmt);
    } catch (\Exception $e) {  
        try {
            return Carbon::parse($date)->format($format ?? 'M d, Y');
        } catch (\Exception $ee) {
            return '-';
        }
    }
}

/**
 * Extracts numeric/actual amount from dynamic currency 
 * Gives flexibility to not reformatting when you need to 
 * use the number as it is to avoid computation errors
 */
function extractNumericFromCurrency($currencyString)
{
    if (empty($currencyString)) {
        return 0;
    }

    // Remove all non-numeric characters except decimal point and minus sign
    $numeric = preg_replace('/[^0-9\.\-]/', '', $currencyString);

    return floatval($numeric);
}

/**
 * removeEmojis
 * 
 * Utility function to remove all emojis from a string.
 * Supports most common emoji ranges in Unicode, including:
 * - Emoticons
 * - Misc Symbols & Pictographs
 * - Transport & Map symbols
 * - Dingbats
 * - Variation selectors
 * - Supplemental Symbols & Pictographs
 * 
 * @param string $text The input string potentially containing emojis
 * @return string The cleaned string without emojis
 */
function removeEmojis(string $text): string {
    return preg_replace(
        '/[\x{1F600}-\x{1F64F}' . // Emoticons
        '\x{1F300}-\x{1F5FF}' .   // Misc Symbols & Pictographs
        '\x{1F680}-\x{1F6FF}' .   // Transport & Map
        '\x{2600}-\x{26FF}' .     // Misc symbols
        '\x{2700}-\x{27BF}' .     // Dingbats
        '\x{FE00}-\x{FE0F}' .     // Variation Selectors
        '\x{1F900}-\x{1F9FF}' .   // Supplemental Symbols & Pictographs
        '\x{1FA70}-\x{1FAFF}' .   // Symbols & Pictographs Extended-A
        ']+/u',
        '',
        $text
    );
}

/**
 * Removes special characters from a string.
 *
 * - Keeps letters (a–z, A–Z), numbers (0–9), and spaces by default
 * - Collapses multiple spaces into one
 * - Trims leading and trailing spaces
 *
 * @param string|null $value
 * @return string
 */
function removeSpecialCharacters(?string $value): string
{
    if ($value === null) {
        return '';
    }

    // Remove everything except letters, numbers, and spaces
    $cleaned = preg_replace('/[^a-zA-Z0-9\s]/u', '', $value);

    // Normalize whitespace
    $cleaned = preg_replace('/\s+/', ' ', $cleaned);

    return trim($cleaned);
}

/**
 * Removes all special characters and spaces from a string.
 *
 * - Keeps letters (a–z, A–Z) and numbers (0–9) only
 * - Returns an empty string for null input
 *
 * @param string|null $value
 * @return string
 */
function removeSpecialCharactersAndSpaces(?string $value): string
{
    if ($value === null) {
        return '';
    }

    return preg_replace('/[^a-zA-Z0-9]/u', '', $value);
}

/**
 * Converts HTML content to plain text for SMS or WhatsApp templates
 *
 * @param string|null $htmlContent
 * @return string
 */
function parseTemplateContent(?string $htmlContent): string
{
    if (empty($htmlContent)) return '';

    // Replace <br> and </p> with newline
    $content = preg_replace('/<br\s*\/?>/i', "\n", $htmlContent);
    $content = preg_replace('/<\/p>/i', "\n", $content);

    // Strip remaining HTML tags and decode entities
    $content = strip_tags($content);
    $content = html_entity_decode($content);

    // Normalize all newlines to \n
    $content = preg_replace("/\r\n|\r/", "\n", $content);

    // Remove trailing and leading whitespace including non-breaking spaces
    $content = preg_replace('/[\s\x{00A0}]+$/u', '', $content); // trailing
    $content = preg_replace('/^[\s\x{00A0}]+/u', '', $content); // leading

    // Also remove trailing spaces on each line
    $lines = explode("\n", $content);
    $lines = array_map(function($line) {
        return preg_replace('/[\s\x{00A0}]+$/u', '', $line);
    }, $lines);

    // Rejoin lines and trim overall content
    $content = trim(implode("\n", $lines));

    return $content;
}

/**
 * Format a datetime string for chat list display.
 * - Today     → 10:30 AM
 * - Yesterday → Yesterday
 * - This week → Monday, Tuesday...
 * - Older     → 10/03/2026
 *
 * @param  string $datetime
 * @return string
 */
function chat_time_formatter($datetime) {
    $time = Carbon::parse($datetime);
    $now  = Carbon::now();

    if ($time->isToday()) {
        return $time->format('h:i A');
    } elseif ($time->isYesterday()) {
        return 'Yesterday';
    } elseif ($time->diffInDays($now) < 7) {
        return $time->format('l');
    } else {
        return $time->format('d/m/Y');
    }
}

/**
 * Normalize phone number to digits only
 *
 * Removes:
 * - plus sign (+)
 * - whitespace
 * - all non-numeric characters
 */
function normalizePhoneNumber($phoneNumber)
{
    return preg_replace('/[^0-9]/', '', $phoneNumber);
}


/**
 * Format phone number for display
 * 
 * @param string $phoneNumber
 * @return string
 */
function formatPhoneNumber($phoneNumber)
{
    $digits = preg_replace('/\D/', '', $phoneNumber);
    
    // Format based on length
    if (strlen($digits) === 12 && substr($digits, 0, 2) === '92') {
        return '+' . substr($digits, 0, 2) . ' ' . substr($digits, 2, 3) . ' ' . substr($digits, 5, 7);
    } elseif (strlen($digits) === 10) {
        return '(' . substr($digits, 0, 3) . ') ' . substr($digits, 3, 3) . '-' . substr($digits, 6, 4);
    } elseif (strlen($digits) === 12 && substr($digits, 0, 2) === '25') {
        return '+' . substr($digits, 0, 2) . ' ' . substr($digits, 2, 3) . ' ' . substr($digits, 5, 7);
    }
    
    return $phoneNumber;
}

/**
 * Kenyan phone validation
 */
function validateKenyanPhone(string $phone): bool
{
    $phone = preg_replace('/[^0-9+]/', '', $phone);

    return preg_match('/^(\+254|254|0)[17]\d{8}$/', $phone);
}

/**
 * Password strength check
 */
function validatePasswordStrength(string $password): bool
{
    return strlen($password) >= 8
        && preg_match('/[0-9]/', $password)
        && preg_match('/[^a-zA-Z0-9]/', $password);
}
    