<?php

/*=============================================  
GET REAL CLIENT IP
=============================================*/
function getRealIP(): string
{
    $ipHeaders = [
        'HTTP_CLIENT_IP',
        'HTTP_X_FORWARDED_FOR',
        'HTTP_X_FORWARDED',
        'HTTP_FORWARDED_FOR',
        'HTTP_FORWARDED',
        'REMOTE_ADDR'
    ];

    foreach ($ipHeaders as $header) {
        if (!empty($_SERVER[$header])) {

            // X-Forwarded-For may contain multiple IPs
            $ips = explode(',', $_SERVER[$header]);

            foreach ($ips as $ip) {
                $ip = trim($ip);

                if (filter_var(
                    $ip,
                    FILTER_VALIDATE_IP,
                    FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE
                )) {
                    return $ip;
                }
            }
        }
    }

    return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
}

// FORMAT DATE TO MYSQL DATE YYYY-MM-DD
function mysqlDate($date)
{
    $date = explode("/", $date);
    $date = $date[2] . '-' . $date[0] . '-' . $date[1];
    return $date;
}

// FORMAT DATE TO MYSQL DATE YYYY-MM-DD
function mysqlDateBetween($dateBetween)
{
    $dateFromTo = explode(" - ", $dateBetween);
    $from = explode("/", $dateFromTo[0]);
    $from = $from[2] . '-' . $from[0] . '-' . $from[1];
    $to = explode("/", $dateFromTo[1]);
    $to = $to[2] . '-' . $to[0] . '-' . $to[1];
    return $from . '-' . $to;
}

// FORMAT DATE TO US DATE MM-DD-YYYY
function usDateFormat($date)
{
    $date = explode("-", $date);
    $date = $date[0] . '/' . $date[1] . '/' . $date[2];
    return $date;
}


function get_timeago($datetime, $full = false)
{
    $now = new DateTimeImmutable();
    $ago = new DateTimeImmutable($datetime);
    $diff = $now->diff($ago);

    $weeks = floor($diff->days / 7);
    $days = $diff->days % 7;

    $string = [
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    ];

    $parts = [];

    foreach ($string as $k => $v) {
        $value = 0;
        if ($k === 'w') {
            $value = $weeks;
        } elseif ($k === 'd') {
            $value = $days;
        } else {
            $value = $diff->$k;
        }

        if ($value) {
            $parts[] = $value . ' ' . $v . ($value > 1 ? 's' : '');
        }
    }

    if (!$full) {
        $parts = array_slice($parts, 0, 1);
    }

    return $parts ? implode(', ', $parts) . ' ago' : 'Just now';
}


function getDateTime($posTimeZone = "America/New_York")
{
    $tz_object = new DateTimeZone($posTimeZone);
    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('Y\-m\-d\ H:i:s');
}


function getDateTimeUserIP($userTimeZone)
{
    $tz_object = new DateTimeZone($userTimeZone);
    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('Y\-m\-d\ H:i:s');
}


function getTime($posTimeZone = "America/New_York")
{
    $tz_object = new DateTimeZone($posTimeZone);
    $datetime = new DateTime();
    $datetime->setTimezone($tz_object);
    return $datetime->format('H:i:s');
}


function repDomDecimalFormat($val, $currency)
{

    if (empty(trim((string) $val))) {

        return number_format(0, 2, ".", ",");
    }

    return number_format($val, 2, ".", ",");
}


function mysqlDecimalFormat($val)
{

    if (empty(trim((string) $val))) {

        return number_format(0, 2, ".", ",");
    }

    $val = str_replace(',', '.', str_replace('.', '', $val));

    return number_format($val, 2, ".", ",");
}

function funSetToUpper($value)
{

    if (empty(trim((string) $value))) {

        return null;
    }

    return mb_strtoupper($value, 'UTF-8');
}


function funSetToLower($value)
{

    if (empty(trim((string) $value))) {

        return null;
    }

    return mb_strtolower($value, 'UTF-8');
}

function funSetToUcwords($value)
{

    if (empty(trim((string) $value))) {

        return null;
    }

    return ucwords(funSetToLower($value), 'UTF-8');
}


function checkDias($fecha)
{
    $datetime1 = new DateTime($fecha);
    $datetime2 = new DateTime(date("Y-m-d"));
    $interval = $datetime1->diff($datetime2);
    return $interval->format('%R%a días');
}


function randomDate($format = "Y-m-d", $minLimit = "1970-01-01", $maxLimnit = "2038-01-01")
{
    $millisecondsMinLimit = strtotime($minLimit);
    $millisecondsMaxLimit = strtotime($maxLimnit);
    $randomMilliseconds = mt_rand($millisecondsMinLimit, $millisecondsMaxLimit);
    return date($format, $randomMilliseconds);
}


function funGetValStrlen($string, $maxLenght)
{

    return (strlen($string) > $maxLenght) ? substr($string, 0, $maxLenght) . '...' : $string;
}


function getDiffenceBetweenTwoDates($startDate, $endDate)
{

    $start_date = strtotime($startDate);
    $end_date = strtotime($endDate);

    // $diff = ($start_date - $end_date);
    $diff = ($end_date - $start_date);

    $years = floor($diff / (365 * 60 * 60 * 24));
    $months = floor(($diff - $years * 365 * 60 * 60 * 24) / (30 * 60 * 60 * 24));
    $days = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24) / (60 * 60 * 24));
    $hours = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24) / (60 * 60));
    $minutes = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60) / 60);
    $seconds = floor(($diff - $years * 365 * 60 * 60 * 24 - $months * 30 * 60 * 60 * 24 - $days * 60 * 60 * 24 - $hours * 60 * 60 - $minutes * 60));

    return $response = array("diff" => $diff, "years" => $years, "months" => $months, "days" => $days, "hours" => $hours, "minutes" => $minutes, "seconds" => $seconds);
}

function generateEnterpriseFolderName(string $ent_name = "global"): string
{
    // 1. Convert to lowercase
    $entName = mb_strtolower($ent_name, 'UTF-8');

    // 2. Transliterate accented characters to ASCII
    // e.g., "HÔTEL" → "HOTEL"
    $entName = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $entName);

    // 3. Replace any non-alphanumeric character with underscore
    $entName = preg_replace('/[^a-z0-9]+/', '_', $entName);

    // 4. Remove duplicated underscores
    $entName = preg_replace('/_+/', '_', $entName);

    // 5. Trim leading/trailing underscores
    $entName = trim($entName, '_');

    return $entName ?: 'global';
}


function reduceImageQualityAndUpload($sourcePath, $sourceFile, $uploadDirectory)
{
    // Get the source image dimensions
    list($sourceWidth, $sourceHeight) = getimagesize($sourcePath);
    $imageInfo = getimagesize($sourcePath);
    $mimeType = $imageInfo['mime'];

    // $targetWidth = $imageInfo[0] / 2;
    // $targetHeight = $imageInfo[1] / 2;

    $newWidth = 400;
    $newHeight = 400;

    // Create a new blank image with the desired dimensions
    $targetImage = imagecreatetruecolor($newWidth, $newHeight);

    // Generate a unique file name for the uploaded image
    $newImage = uniqid() . '.' . pathinfo($sourceFile, PATHINFO_EXTENSION);

    // Set the target path for the uploaded image
    $targetPath = $uploadDirectory . '/' . $newImage;


    $sourceImage = null;
    // Reduce the image quality and save to the target path
    switch ($mimeType) {
        case 'image/jpeg':
            $sourceImage = @imagecreatefromjpeg($sourcePath);
            break;
        case 'image/png':
            $sourceImage = @imagecreatefrompng($sourcePath);
            break;
        case 'image/gif':
            $sourceImage = @imagecreatefromgif($sourcePath);
            break;
        default:
            return false; // or throw an error for unsupported formats
    }

    // Resize the source image to the desired dimensions
    imagecopyresampled($targetImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $sourceWidth, $sourceHeight);

    // Save the resized image to the target path
    imagejpeg($targetImage, $targetPath, 90); // Adjust the output format and quality as needed

    // Free up memory
    unset($targetImage);
    unset($sourceImage);

    return $newImage; // Return the uploaded file name or the file path if needed
}


function reduceImageQuality($sourcePath)
{
    $imageInfo = getimagesize($sourcePath);
    $mimeType = $imageInfo['mime'];

    // Set a maximum height and width
    $new_width = 400;
    $new_height = 400;

    // Get the source image dimensions
    list($origWidth, $origHeight) = getimagesize($sourcePath);

    // Create a new blank image with the desired dimensions
    $image = imagecreatetruecolor($new_width, $new_height);

    $source = null;
    // Reduce the image quality and save to the target path
    switch ($mimeType) {
        case 'image/jpeg':
            $source = @imagecreatefromjpeg($sourcePath);
            break;
        case 'image/png':
            $source = @imagecreatefrompng($sourcePath);
            break;
        case 'image/gif':
            $source = @imagecreatefromgif($sourcePath);
            break;
        default:
            return false; // or throw an error for unsupported formats
    }

    // Resize image
    imagecopyresampled($image, $source, 0, 0, 0, 0, $new_width, $new_height, $origWidth, $origHeight);

    // Output resized image to output buffer
    ob_start();
    imagejpeg($image, null, 90);
    $resizedImageContents = ob_get_clean();

    // Free up memory
    unset($image);
    unset($source);

    return $resizedImageContents;
}

function reduceImageQualityDefault($sourcePath)
{
    $imageInfo = getimagesize($sourcePath);
    $mimeType = $imageInfo['mime'];

    $percent = 0.5;

    // Get the source image dimensions
    list($width, $height) = getimagesize($sourcePath);

    // Get new dimensions
    $new_width = $width * $percent;
    $new_height = $height * $percent;

    // Create a new blank image with the desired dimensions
    $image = imagecreatetruecolor($new_width, $new_height);

    $source = null;
    // Reduce the image quality and save to the target path
    switch ($mimeType) {
        case 'image/jpeg':
            $source = @imagecreatefromjpeg($sourcePath);
            break;
        case 'image/png':
            $source = @imagecreatefrompng($sourcePath);
            break;
        case 'image/gif':
            $source = @imagecreatefromgif($sourcePath);
            break;
        default:
            return false; // or throw an error for unsupported formats
    }

    // Resize image
    imagecopyresampled($image, $source, 0, 0, 0, 0, $new_width, $new_height, $width, $height);

    // Output resized image to output buffer
    ob_start();
    imagejpeg($image, null, 90);
    $resizedImageContents = ob_get_clean();

    // Free up memory
    unset($image);
    unset($source);

    return $resizedImageContents;
}
