<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * This function is used to print the content of any data
 */
function pre($data)
{
    echo '<pre>';
    print_r($data);
    echo '</pre>';
}

/** This function used to get the CI instance */
if (!function_exists('get_instance')) {
    function get_instance()
    {
        $CI = &get_instance();
    }
}

/**
 * This function used to generate the hashed password
 * @param {string} $plainPassword : This is plain text password
 */
if (!function_exists('getHashedPassword')) {
    function getHashedPassword($plainPassword)
    {
        return password_hash($plainPassword, PASSWORD_DEFAULT);
    }
}

/**
 * This function used to generate the hashed password
 * @param {string} $plainPassword : This is plain text password
 * @param {string} $hashedPassword : This is hashed password
 */
if (!function_exists('verifyHashedPassword')) {
    function verifyHashedPassword($plainPassword, $hashedPassword)
    {
        return password_verify($plainPassword, $hashedPassword) ? true : false;
    }
}

/** This method used to get current browser agent */
if (!function_exists('getBrowserAgent')) {
    function getBrowserAgent()
    {
        $CI = get_instance();
        $CI->load->library('user_agent');

        $agent = '';

        if ($CI->agent->is_browser()) {
            $agent = $CI->agent->browser() . ' ' . $CI->agent->version();
        } else if ($CI->agent->is_robot()) {
            $agent = $CI->agent->robot();
        } else if ($CI->agent->is_mobile()) {
            $agent = $CI->agent->mobile();
        } else {
            $agent = 'Unidentified User Agent';
        }

        return $agent;
    }
}

if (!function_exists('setProtocol')) {
    function setProtocol()
    {
        $CI = &get_instance();

        $CI->load->library('email');

        $config['protocol'] = PROTOCOL;
        $config['mailpath'] = MAIL_PATH;
        $config['smtp_host'] = SMTP_HOST;
        $config['smtp_port'] = SMTP_PORT;
        $config['smtp_user'] = SMTP_USER;
        $config['smtp_pass'] = SMTP_PASS;
        $config['charset'] = 'utf-8';
        $config['mailtype'] = 'html';
        $config['newline'] = "\r\n";

        $CI->email->initialize($config);

        return $CI;
    }
}

if (!function_exists('emailConfig')) {
    function emailConfig()
    {
        $CI->load->library('email');
        $config['protocol'] = PROTOCOL;
        $config['smtp_host'] = SMTP_HOST;
        $config['smtp_port'] = SMTP_PORT;
        $config['mailpath'] = MAIL_PATH;
        $config['charset'] = 'UTF-8';
        $config['mailtype'] = 'html';
        $config['newline'] = "\r\n";
        $config['wordwrap'] = TRUE;
    }
}

if (!function_exists('resetPasswordEmail')) {
    function resetPasswordEmail($detail)
    {
        $data['data'] = $detail;
        // pre($detail);
        // die;

        $CI = setProtocol();

        $CI->email->from(EMAIL_FROM, FROM_NAME);
        $CI->email->subject('Reset Password');
        $CI->email->message($CI->load->view('email/resetPassword', $data, TRUE));
        $CI->email->to($detail['email']);
        $status = $CI->email->send();

        return $status;
    }
}

if (!function_exists('setFlashData')) {
    function setFlashData($status, $flashMsg)
    {
        $CI = get_instance();
        $CI->session->set_flashdata($status, $flashMsg);
    }
}
if (!function_exists('timeAgo')) {
    function timeAgo($time_ago = '')
    {
        $new_time = date('Y-m-d H:i:s', strtotime($time_ago));
        // echo   "===".date("Y-m-d H:i:s");
        $time_ago = strtotime($new_time);
        $cur_time = time();
        $time_elapsed = $cur_time - $time_ago;
        $seconds = $time_elapsed;
        $minutes = round($time_elapsed / 60);
        $hours = round($time_elapsed / 3600);
        $days = round($time_elapsed / 86400);
        $weeks = round($time_elapsed / 604800);
        $months = round($time_elapsed / 2600640);
        $years = round($time_elapsed / 31207680);
        if ($seconds <= 60) {
            return $seconds . 's';
        }
        // Minutes
        else if ($minutes <= 60) {
            if ($minutes == 1) {
                return '1m';
            } else {
                return "$minutes m";
            }
        }
        // Hours
        else if ($hours <= 24) {
            if ($hours == 1) {
                return '1h';
            } else {
                return $hours . 'h';
            }
        } else if ($days <= 7 && $months <= 12) {
            // if ($days == 1){

            //   return "yesterday";

            // } else {

            //   return "$days days ago";

            // }

            return date('M d', $time_ago);
        } else {
            if ($years == 1) {
                return date('M d', $time_ago);
            } else {
                return date('M d Y', $time_ago);
            }
        }
    }
}

if (!function_exists('timeAgonew')) {
    function timeAgonew($time_ago = '')
    {
        //$new_time = date('Y-m-d H:i:s', strtotime($time_ago));
        // echo   "===".date("Y-m-d H:i:s");
        $time_ago =$time_ago; 
        //strtotime($new_time);
        $cur_time = time();
        $time_elapsed = $cur_time - $time_ago;
        
        $seconds = $time_elapsed;
        $minutes = round($time_elapsed / 60);
        $hours = round($time_elapsed / 3600);
        $days = round($time_elapsed / 86400);
        $weeks = round($time_elapsed / 604800);
        $months = round($time_elapsed / 2600640);
        $years = round($time_elapsed / 31207680);
        if ($seconds <= 60) {
            return $seconds . 's';
        }
        // Minutes
        else if ($minutes <= 60) {
            if ($minutes == 1) {
                return '1m';
            } else {
                return "$minutes m";
            }
        }
        // Hours
        else if ($hours <= 24) {
            if ($hours == 1) {
                return '1h';
            } else {
                return $hours . 'h';
            }
        } else if ($days <= 7 && $months <= 12) {
            // if ($days == 1){

            //   return "yesterday";

            // } else {

            //   return "$days days ago";

            // }

            return date('M d', $time_ago);
        } else {
            if ($years == 1) {
                return date('M d', $time_ago);
            } else {
                return date('M d Y', $time_ago);
            }
        }
    }
}

if (!function_exists('getDateDifference')) {
    function getDateDifference($startDate, $endDate)
    {
        $start = DateTime::createFromFormat('Y-m-d H:i:s', $startDate);
        $end = DateTime::createFromFormat('Y-m-d H:i:s', $endDate);

        $interval = $end->diff($start);

        $output = '';

        if ($interval->y > 0) {
            if ($interval->y > 1) {
                $output .= $interval->y . ' Years';
            } else {
                $output .= $interval->y . ' Year';
            }
        }

        if ($interval->m > 0) {
            if ($interval->m > 1) {
                $output .= $interval->m . ' Months';
            } else {
                $output .= $interval->m . ' Month';
            }
        }

        if ($interval->d > 0) {
            if ($interval->d > 1) {
                $output .= $interval->d . ' Days';
            } else {
                $output .= $interval->d . ' Day';
            }
        } else {
            if ($interval->h > 0) {
                if ($interval->h > 1) {
                    $output .= $interval->h . ' Hours';
                } else {
                    $output .= $interval->h . ' Hour';
                }
            } else {
                if ($interval->i > 0) {
                    if ($interval->i > 1) {
                        $output .= $interval->i . ' minutes';
                    } else {
                        $output .= $interval->i . ' minute';
                    }
                } else {
                    if ($interval->s > 0) {
                        $output .= $interval->s . ' seconds';
                    }
                }
            }
        }

        if (empty(trim($output))) {
            $output .= 'Just Now';
        } else {
            $output .= ' ago';
        }

        return $output;
    }

    // ????for lack to  M and thousands to k

    if (!function_exists('format_number')) {
        /**
         * Format numbers to 'K' for thousands and 'M' for millions.
         *
         * @param int $number The number to format.
         * @return string The formatted number.
         */
        function format_number($number)
        {
            if ($number >= 1000000) {
                return number_format($number / 1000000, 1) . ' M';
            } elseif ($number >= 1000) {
                return number_format($number / 1000, 1) . ' K';
            } else {
                return $number;
            }
        }
    }

    // ???for read more function
    if (!function_exists('truncate_caption')) {
        function truncate_caption($caption, $limit = 100)
        {
            if (strlen($caption) > $limit) {
                $truncated = substr($caption, 0, $limit) . '...';
                return '<span class="caption-text" data-full-caption="' . htmlspecialchars($caption) . '">' . htmlspecialchars($truncated) . '</span> 
                        <a href="#" class="toggle-caption">Read More</a>';
            }
            return htmlspecialchars($caption);
        }
    }
    if (!function_exists('get_user_image')) {
        // function get_user_image($imageSrc)
        // {
        //     // Get the file name from the image source
        //     $imageFileName = basename($imageSrc);

        //     // Define the correct paths to check
        //     $path1 = $_SERVER['DOCUMENT_ROOT'] . '/dentifyd/uploads/user_profiles/' . $imageFileName;
        //     $path2 = $_SERVER['DOCUMENT_ROOT'] . '/dentifiyclient/uploads/user_profiles/' . $imageFileName;

        //     // Check if the image source contains a full URL (http or https)
        //     if (!preg_match('/^(http|https):\/\//', $imageSrc)) {
        //         // Check if the image exists in the first path
        //         if (file_exists($path1)) {
        //             return 'https://buzzwaretech.com/dentifyd/uploads/user_profiles/' . $imageFileName;
        //         }
        //         // Check if the image exists in the second path
        //         else if (file_exists($path2)) {
        //             return 'https://buzzwaretech.com/dentifiyclient/uploads/user_profiles/' . $imageFileName;
        //         }
        //         // If the image does not exist in either path, use the default image
        //         else {
        //             return "https://buzzwaretech.com/dentifyd/uploads/user_profiles/defaultimage.jpg";
        //         }
        //     }

        //     // If the image source is already a full URL, return it as is
        //     return $imageSrc;
        // }
        //         function get_user_image($imageSrc)
        // {
        //     // If the image is empty, return the default image immediately
        //     if (empty($imageSrc)) {
        //         return "https://buzzwaretech.com/dentifyd/uploads/user_profiles/defaultimage.jpg";
        //     }

        //     // Extract filename safely
        //     $imageFileName = basename(parse_url($imageSrc, PHP_URL_PATH));

        //     // Define possible paths
        //     $path1 = $_SERVER['DOCUMENT_ROOT'] . '/dentifyd/uploads/user_profiles/' . $imageFileName;
        //     $path2 = $_SERVER['DOCUMENT_ROOT'] . '/dentifiyclient/uploads/user_profiles/' . $imageFileName;

        //     // If image is already a full URL, return it as is
        //     if (filter_var($imageSrc, FILTER_VALIDATE_URL)) {
        //         return $imageSrc;
        //     }

        //     // Check if the file exists in either location
        //     if (file_exists($path1)) {
        //         return 'https://buzzwaretech.com/dentifyd/uploads/user_profiles/' . $imageFileName;
        //     } elseif (file_exists($path2)) {
        //         return 'https://buzzwaretech.com/dentifiyclient/uploads/user_profiles/' . $imageFileName;
        //     }

        //     // If not found, return the default image
        //     return "https://buzzwaretech.com/dentifyd/uploads/user_profiles/defaultimage.jpg";
        // }
        function get_user_image($imageSrc)
        {
            // Default image path (should use base_url() for consistency)
            $defaultImage = base_url('uploads/user_profiles/defaultimage.jpg');

            // Return default if empty
            if (empty($imageSrc)) {
                return $defaultImage;
            }

            // If already a full URL, return as-is
            if (filter_var($imageSrc, FILTER_VALIDATE_URL)) {
                return $imageSrc;
            }

            // Remove any existing base URL if present
            $baseToRemove = base_url('uploads/user_profiles/');
            $cleanPath = str_replace($baseToRemove, '', $imageSrc);
            $imageFileName = basename($cleanPath);

            // Build correct local path
            $localPath = FCPATH . 'uploads/user_profiles/' . $imageFileName;

            // Check file existence
            if (file_exists($localPath)) {
                return base_url('uploads/user_profiles/' . $imageFileName);
            }

            return $defaultImage;
        }
    }
}

?>