<?php

use App\Lib\GoogleAuthenticator;
use App\Lib\SendSms;
use App\Models\Deposit;
use App\Models\EmailLog;
use App\Models\EmailTemplate;
use App\Models\Extension;
use App\Models\Frontend;
use App\Models\Gateway;
use App\Models\GeneralSetting;
use App\Models\SmsTemplate;
use App\Models\Transaction;
use App\Models\User;
use App\Models\Withdrawal;
use App\Models\Investment;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Str;
use Intervention\Image\Facades\Image;
use Mailjet\Resources;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use App\Models\Admin;






function sidebarVariation(){

    /// for sidebar
    $variation['sidebar'] = 'bg_img';

    //for selector
    $variation['selector'] = 'capsule--rounded';

    //for overlay
    $variation['overlay'] = 'overlay--indigo';

    //Opacity
    $variation['opacity'] = 'overlay--opacity-8'; // 1-10

    return $variation;

}

function systemDetails()
{
    $system['name'] = 'Fine-Gold';
    $system['version'] = '1.2';
    return $system;
}

function getLatestVersion()
{
    return '';
    $param['purchasecode'] = env("PURCHASECODE");
    $param['website'] = @$_SERVER['HTTP_HOST'] . @$_SERVER['REQUEST_URI'] . ' - ' . env("APP_URL");
    $url = 'https://license.viserlab.com/updates/version/' . systemDetails()['name'];
    $result = curlPostContent($url, $param);
    if ($result) {
        return $result;
    } else {
        return null;
    }
}


function slug($string)
{
    return Illuminate\Support\Str::slug($string);
}


function shortDescription($string, $length = 120)
{
    return Illuminate\Support\Str::limit($string, $length);
}


function shortCodeReplacer($shortCode, $replace_with, $template_string)
{
    return str_replace($shortCode, $replace_with, $template_string);
}


function verificationCode($length)
{
    if ($length == 0) return 0;
    $min = pow(10, $length - 1);
    $max = 0;
    while ($length > 0 && $length--) {
        $max = ($max * 10) + 9;
    }
    return random_int($min, $max);
}

function getNumber($length = 8)
{
    $characters = '1234567890';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}



//moveable
function uploadImage($file, $location, $size = null, $old = null, $thumb = null)
{
    $path = makeDirectory($location);
    if (!$path) throw new Exception('File could not been created.');

    if ($old) {
        removeFile($location . '/' . $old);
        removeFile($location . '/thumb_' . $old);
    }
    $filename = uniqid() . time() . '.' . $file->getClientOriginalExtension();
    $image = Image::make($file);
    if ($size) {
        $size = explode('x', strtolower($size));
        $image->resize($size[0], $size[1]);
    }
    $image->save($location . '/' . $filename);

    if ($thumb) {
        $thumb = explode('x', $thumb);
        Image::make($file)->resize($thumb[0], $thumb[1])->save($location . '/thumb_' . $filename);
    }

    return $filename;
}

function uploadFile($file, $location, $size = null, $old = null){
    $path = makeDirectory($location);
    if (!$path) throw new Exception('File could not been created.');

    if ($old) {
        removeFile($location . '/' . $old);
    }

    $filename = uniqid() . time() . '.' . $file->getClientOriginalExtension();
    $file->move($location,$filename);
    return $filename;
}

function makeDirectory($path)
{
    if (file_exists($path)) return true;
    return mkdir($path, 0755, true);
}


function removeFile($path)
{
    return file_exists($path) && is_file($path) ? @unlink($path) : false;
}


function activeTemplate($asset = false)
{
    $general = GeneralSetting::first(['active_template']);
    $template = $general->active_template;
    $sess = session()->get('template');
    if (trim($sess)) {
        $template = $sess;
    }
    if ($asset) return 'assets/templates/' . $template . '/';
    return 'templates.' . $template . '.';
}

function activeTemplateName()
{
    $general = GeneralSetting::first(['active_template']);
    $template = $general->active_template;
    $sess = session()->get('template');
    if (trim($sess)) {
        $template = $sess;
    }
    return $template;
}


function loadReCaptcha()
{
    $reCaptcha = Extension::where('act', 'google-recaptcha2')->where('status', 1)->first();
    return $reCaptcha ? $reCaptcha->generateScript() : '';
}


function loadAnalytics()
{
    $analytics = Extension::where('act', 'google-analytics')->where('status', 1)->first();
    return $analytics ? $analytics->generateScript() : '';
}

function loadTawkto()
{
    $tawkto = Extension::where('act', 'tawk-chat')->where('status', 1)->first();
    return $tawkto ? $tawkto->generateScript() : '';
}


function loadFbComment()
{
    $comment = Extension::where('act', 'fb-comment')->where('status',1)->first();
    return  $comment ? $comment->generateScript() : '';
}

function loadCustomCaptcha($height = 46, $width = '300px', $bgcolor = '#003', $textcolor = '#abc')
{
    $textcolor = '#'.GeneralSetting::first()->base_color;
    $captcha = Extension::where('act', 'custom-captcha')->where('status', 1)->first();
    if (!$captcha) {
        return 0;
    }
    $code = rand(100000, 999999);
    $char = str_split($code);
    $ret = '<link href="https://fonts.googleapis.com/css?family=Henny+Penny&display=swap" rel="stylesheet">';
    $ret .= '<div style="height: ' . $height . 'px; line-height: ' . $height . 'px; width:' . $width . '; text-align: center; background-color: ' . $bgcolor . '; color: ' . $textcolor . '; font-size: ' . ($height - 20) . 'px; font-weight: bold; letter-spacing: 20px; font-family: \'Henny Penny\', cursive;  -webkit-user-select: none; -moz-user-select: none;-ms-user-select: none;user-select: none;  display: flex; justify-content: center;">';
    foreach ($char as $value) {
        $ret .= '<span style="    float:left;     -webkit-transform: rotate(' . rand(-60, 60) . 'deg);">' . $value . '</span>';
    }
    $ret .= '</div>';
    $captchaSecret = hash_hmac('sha256', $code, $captcha->shortcode->random_key->value);
    $ret .= '<input type="hidden" name="captcha_secret" value="' . $captchaSecret . '">';
    return $ret;
}


function captchaVerify($code, $secret)
{
    $captcha = Extension::where('act', 'custom-captcha')->where('status', 1)->first();
    $captchaSecret = hash_hmac('sha256', $code, $captcha->shortcode->random_key->value);
    if ($captchaSecret == $secret) {
        return true;
    }
    return false;
}

function getTrx($length = 12)
{
    $characters = 'ABCDEFGHJKMNOPQRSTUVWXYZ123456789';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}


function getAmount($amount, $length = 2)
{
    $amount = round($amount, $length);
    return $amount + 0;
}

function showAmount($amount, $decimal = 2, $separate = true, $exceptZeros = false){
    $separator = '';
    if($separate){
        $separator = ',';
    }
    $printAmount = number_format($amount, $decimal, '.', $separator);
    if($exceptZeros){
    $exp = explode('.', $printAmount);
        if($exp[1]*1 == 0){
            $printAmount = $exp[0];
        }
    }
    return $printAmount;
}

function amount_format($amount){
    return number_format($amount);
}


function removeElement($array, $value)
{
    return array_diff($array, (is_array($value) ? $value : array($value)));
}

function cryptoQR($wallet)
{

    //return "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=$wallet&choe=UTF-8";
    //return "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=%22&$wallet";
    
    return "https://quickchart.io/qr?chs=300x300&text=$wallet";
}

function getUSDTtoETB($amount)
{
    // Initialize the Guzzle client
    $client = new Client();

    try {
        $response = $client->get('https://api.exchangerate-api.com/v4/latest/USDT');
        $data = json_decode($response->getBody(), true);
        
        $ethiopiaRate = $data['rates']['ETB'];
        
        return $amount / $ethiopiaRate;

    } catch (\Exception $e) {
        // Handle any errors
        return response()->json([
            'status' => 'error',
            'message' => 'Failed to fetch exchange rate. Please try again later.',
        ], 500);
    }
}

//moveable
function curlContent($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

//moveable
function curlPostContent($url, $arr = null)
{
    if ($arr) {
        $params = http_build_query($arr);
    } else {
        $params = '';
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


function inputTitle($text)
{
    return ucfirst(preg_replace("/[^A-Za-z0-9 ]/", ' ', $text));
}

function keyToTitle($text)
{
    return ucfirst(preg_replace("/[^A-Za-z0-9 ]/", ' ', $text));
}

function titleToKey($text)
{
    return strtolower(str_replace(' ', '_', $text));
}


function str_limit($title = null, $length = 10)
{
    return \Illuminate\Support\Str::limit($title, $length);
}

//moveable
function getIpInfo()
{
    $ip = $_SERVER["REMOTE_ADDR"];

    //Deep detect ip
    if (filter_var(@$_SERVER['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP)){
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    }
    if (filter_var(@$_SERVER['HTTP_CLIENT_IP'], FILTER_VALIDATE_IP)){
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    }


    $xml = @simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=" . $ip);


    $country = @$xml->geoplugin_countryName;
    $city = @$xml->geoplugin_city;
    $area = @$xml->geoplugin_areaCode;
    $code = @$xml->geoplugin_countryCode;
    $long = @$xml->geoplugin_longitude;
    $lat = @$xml->geoplugin_latitude;

    $data['country'] = $country;
    $data['city'] = $city;
    $data['area'] = $area;
    $data['code'] = $code;
    $data['long'] = $long;
    $data['lat'] = $lat;
    $data['ip'] = request()->ip();
    $data['time'] = date('d-m-Y h:i:s A');


    return $data;
}

//moveable
function osBrowser(){
    $userAgent = $_SERVER['HTTP_USER_AGENT'];
    $osPlatform = "Unknown OS Platform";
    $osArray = array(
        '/windows nt 10/i' => 'Windows 10',
        '/windows nt 6.3/i' => 'Windows 8.1',
        '/windows nt 6.2/i' => 'Windows 8',
        '/windows nt 6.1/i' => 'Windows 7',
        '/windows nt 6.0/i' => 'Windows Vista',
        '/windows nt 5.2/i' => 'Windows Server 2003/XP x64',
        '/windows nt 5.1/i' => 'Windows XP',
        '/windows xp/i' => 'Windows XP',
        '/windows nt 5.0/i' => 'Windows 2000',
        '/windows me/i' => 'Windows ME',
        '/win98/i' => 'Windows 98',
        '/win95/i' => 'Windows 95',
        '/win16/i' => 'Windows 3.11',
        '/macintosh|mac os x/i' => 'Mac OS X',
        '/mac_powerpc/i' => 'Mac OS 9',
        '/linux/i' => 'Linux',
        '/ubuntu/i' => 'Ubuntu',
        '/iphone/i' => 'iPhone',
        '/ipod/i' => 'iPod',
        '/ipad/i' => 'iPad',
        '/android/i' => 'Android',
        '/blackberry/i' => 'BlackBerry',
        '/webos/i' => 'Mobile'
    );
    foreach ($osArray as $regex => $value) {
        if (preg_match($regex, $userAgent)) {
            $osPlatform = $value;
        }
    }
    $browser = "Unknown Browser";
    $browserArray = array(
        '/msie/i' => 'Internet Explorer',
        '/firefox/i' => 'Firefox',
        '/safari/i' => 'Safari',
        '/chrome/i' => 'Chrome',
        '/edge/i' => 'Edge',
        '/opera/i' => 'Opera',
        '/netscape/i' => 'Netscape',
        '/maxthon/i' => 'Maxthon',
        '/konqueror/i' => 'Konqueror',
        '/mobile/i' => 'Handheld Browser'
    );
    foreach ($browserArray as $regex => $value) {
        if (preg_match($regex, $userAgent)) {
            $browser = $value;
        }
    }

    $data['os_platform'] = $osPlatform;
    $data['browser'] = $browser;

    return $data;
}

function siteName()
{
    $general = GeneralSetting::first();
    $sitname = str_word_count($general->sitename);
    $sitnameArr = explode(' ', $general->sitename);
    if ($sitname > 1) {
        $title = "<span>$sitnameArr[0] </span> " . str_replace($sitnameArr[0], '', $general->sitename);
    } else {
        $title = "<span>$general->sitename</span>";
    }

    return $title;
}


//moveable
function getTemplates()
{
    $param['purchasecode'] = env("PURCHASECODE");
    $param['website'] = @$_SERVER['HTTP_HOST'] . @$_SERVER['REQUEST_URI'] . ' - ' . env("APP_URL");
    $url = 'https://license.viserlab.com/updates/templates/' . systemDetails()['name'];
    $result = curlPostContent($url, $param);
    if ($result) {
        return $result;
    } else {
        return null;
    }
}


function getPageSections($arr = false)
{

    $jsonUrl = resource_path('views/') . str_replace('.', '/', activeTemplate()) . 'sections.json';
    $sections = json_decode(file_get_contents($jsonUrl));
    if ($arr) {
        $sections = json_decode(file_get_contents($jsonUrl), true);
        ksort($sections);
    }
    return $sections;
}


function getImage($image,$size = null)
{
    $clean = '';
    if (file_exists($image) && is_file($image)) {
        return asset($image) . $clean;
    }
    if ($size) {
        return route('placeholder.image',$size);
    }
    return asset('assets/images/default.png');
}

function notify($user, $type, $shortCodes = null)
{

    sendEmail($user, $type, $shortCodes);
    sendSms($user, $type, $shortCodes);
}



function sendSms($user, $type, $shortCodes = [])
{
    $general = GeneralSetting::first();
    $smsTemplate = SmsTemplate::where('act', $type)->where('sms_status', 1)->first();
    $gateway = $general->sms_config->name;
    $sendSms = new SendSms;
    if ($general->sn == 1 && $smsTemplate) {
        $template = $smsTemplate->sms_body;
        foreach ($shortCodes as $code => $value) {
            $template = shortCodeReplacer('{{' . $code . '}}', $value, $template);
        }
        $message = shortCodeReplacer("{{message}}", $template, $general->sms_api);
        $message = shortCodeReplacer("{{name}}", $user->username, $message);
        $sendSms->$gateway($user->mobile,$general->sitename,$message,$general->sms_config);
    }
}

function sendEmail($user, $type = null, $shortCodes = [])
{
    $general = GeneralSetting::first();

    $emailTemplate = EmailTemplate::where('act', $type)->where('email_status', 1)->first();
    if ($general->en != 1 || !$emailTemplate) {
        return;
    }


    $message = shortCodeReplacer("{{fullname}}", $user->fullname, $general->email_template);
    $message = shortCodeReplacer("{{username}}", $user->username, $message);
    $message = shortCodeReplacer("{{message}}", $emailTemplate->email_body, $message);

    if (empty($message)) {
        $message = $emailTemplate->email_body;
    }

    foreach ($shortCodes as $code => $value) {
        $message = shortCodeReplacer('{{' . $code . '}}', $value, $message);
    }

    $config = $general->mail_config;

    $emailLog = new EmailLog();
    $emailLog->user_id = $user->id;
    $emailLog->mail_sender = $config->name;
    $emailLog->email_from = $general->sitename.' '.$general->email_from;
    $emailLog->email_to = $user->email;
    $emailLog->subject = $emailTemplate->subj;
    $emailLog->message = $message;
    $emailLog->save();


    if ($config->name == 'php') {
        sendPhpMail($user->email, $user->username,$emailTemplate->subj, $message, $general);
    } else if ($config->name == 'smtp') {
        sendSmtpMail($config, $user->email, $user->username, $emailTemplate->subj, $message,$general);
    } else if ($config->name == 'sendgrid') {
        sendSendGridMail($config, $user->email, $user->username, $emailTemplate->subj, $message,$general);
    } else if ($config->name == 'mailjet') {
        sendMailjetMail($config, $user->email, $user->username, $emailTemplate->subj, $message,$general);
    }
}


function sendPhpMail($email, $name, $subject, $message,$general,$contact = false)
{
    if ($contact) {
        $headers = "From: $name <$email> \r\n";
        $headers .= "Reply-To: $name <$email> \r\n";
        $email = $general->email_from;
    }else{
        $headers = "From: $general->sitename <$general->email_from> \r\n";
        $headers .= "Reply-To: $general->sitename <$general->email_from> \r\n";
    }
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";
    @mail($email, $subject, $message, $headers);
}


function sendSmtpMail($config, $receiver_email, $receiver_name, $subject, $message,$general,$contact = false)
{
    $mail = new PHPMailer(true);

    try {
        //Server settings
        $mail->isSMTP();
        $mail->Host       = $config->host;
        $mail->SMTPAuth   = true;
        $mail->Username   = $config->username;
        $mail->Password   = $config->password;
        if ($config->enc == 'ssl') {
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
        }else{
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        }
        $mail->Port       = $config->port;
        $mail->CharSet = 'UTF-8';
        //Recipients
        if ($contact) {
            $mail->setFrom($receiver_email, $receiver_name);
            $mail->addAddress($general->email_from, $general->sitename);
            $mail->addReplyTo($receiver_email, $receiver_name);
        }else{
            $mail->setFrom($general->email_from, $general->sitename);
            $mail->addAddress($receiver_email, $receiver_name);
            $mail->addReplyTo($general->email_from, $general->sitename);
        }
        // Content
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $message;
        $mail->send();
    } catch (Exception $e) {
        throw new Exception($e);
    }
}


function sendSendGridMail($config, $receiver_email, $receiver_name, $subject, $message,$general,$contact = false)
{
    $sendgridMail = new \SendGrid\Mail\Mail();
    if ($contact) {
        $sendgridMail->setFrom($receiver_email, $receiver_name);
        $sendgridMail->setSubject($subject);
        $sendgridMail->addTo($general->email_from, $general->sitename);
    }else{
        $sendgridMail->setFrom($general->email_from, $general->sitename);
        $sendgridMail->setSubject($subject);
        $sendgridMail->addTo($receiver_email, $receiver_name);
    }

    $sendgridMail->addContent("text/html", $message);
    $sendgrid = new \SendGrid($config->appkey);
    try {
        $response = $sendgrid->send($sendgridMail);
    } catch (Exception $e) {
        throw new Exception($e);
    }
}


function sendMailjetMail($config, $receiver_email, $receiver_name, $subject, $message,$general,$contact = false)
{
    $mj = new \Mailjet\Client($config->public_key, $config->secret_key, true, ['version' => 'v3.1']);
    if ($contact) {
        $fromMail = $receiver_email;
        $fromName = $receiver_name;
        $toMail = $general->email_from;
        $toName = $general->sitename;
    }else{
        $toMail = $receiver_email;
        $toName = $receiver_name;
        $fromMail = $general->email_from;
        $fromName = $general->sitename;
    }
    $body = [
        'Messages' => [
            [
                'From' => [
                    'Email' => $fromMail,
                    'Name' => $fromName,
                ],
                'To' => [
                    [
                        'Email' => $toMail,
                        'Name' => $toName,
                    ]
                ],
                'Subject' => $subject,
                'TextPart' => "",
                'HTMLPart' => $message,
            ]
        ]
    ];
    $response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]);
}


function getPaginate($paginate = 100)
{
    return $paginate;
}

function paginateLinks($data, $design = 'admin.partials.paginate'){
    return $data->appends(request()->all())->links($design);
}


function menuActive($routeName, $type = null)
{
    if ($type == 3) {
        $class = 'side-menu--open';
    } elseif ($type == 2) {
        $class = 'sidebar-submenu__open';
    } else {
        $class = 'active';
    }
    if (is_array($routeName)) {
        foreach ($routeName as $key => $value) {
            if (request()->routeIs($value)) {
                return $class;
            }
        }
    } elseif (request()->routeIs($routeName)) {
        return $class;
    }
}


function imagePath()
{
    $data['gateway'] = [
        'path' => 'assets/images/gateway',
        'size' => '800x800',
    ];
    $data['verify'] = [
        'withdraw'=>[
            'path'=>'assets/images/verify/withdraw'
        ],
        'deposit'=>[
            'path'=>'assets/images/verify/deposit'
        ]
    ];
    $data['image'] = [
        'default' => 'assets/images/default.png',
    ];
    $data['withdraw'] = [
        'method' => [
            'path' => 'assets/images/withdraw/method',
            'size' => '800x800',
        ]
    ];
    $data['ticket'] = [
        'path' => 'assets/support',
    ];
    $data['language'] = [
        'path' => 'assets/images/lang',
        'size' => '64x64'
    ];
    $data['logoIcon'] = [
        'path' => 'assets/images/logoIcon',
    ];
    $data['favicon'] = [
        'size' => '128x128',
    ];
    $data['extensions'] = [
        'path' => 'assets/images/extensions',
        'size' => '36x36',
    ];
    $data['seo'] = [
        'path' => 'assets/images/seo',
        'size' => '600x315'
    ];
    $data['profile'] = [
        'user'=> [
            'path'=>'assets/images/user/profile',
            'size'=>'350x300'
        ],
        'admin'=> [
            'path'=>'assets/admin/images/profile',
            'size'=>'400x400'
        ]
    ];
    return $data;
}

function diffForHumans($date)
{
    $lang = session()->get('lang');
    Carbon::setlocale($lang);
    return Carbon::parse($date)->diffForHumans();
}

function showDateTime($date, $format = 'Y-m-d h:i A')
{
    $lang = session()->get('lang');
    Carbon::setlocale($lang);
    return Carbon::parse($date)->translatedFormat($format);
}

//moveable
function sendGeneralEmail($email, $subject, $message, $receiver_name = '')
{

    $general = GeneralSetting::first();


    if ($general->en != 1 || !$general->email_from) {
        return;
    }

    $message = shortCodeReplacer("{{message}}", $message, $general->email_template);
    $message = shortCodeReplacer("{{fullname}}", $receiver_name, $message);
    $message = shortCodeReplacer("{{username}}", $email, $message);

    $config = $general->mail_config;

    if ($config->name == 'php') {
        sendPhpMail($email, $receiver_name, $subject, $message, $general);
    } else if ($config->name == 'smtp') {
        sendSmtpMail($config, $email, $receiver_name, $subject, $message, $general);
    } else if ($config->name == 'sendgrid') {
        sendSendGridMail($config, $email, $receiver_name,$subject, $message,$general);
    } else if ($config->name == 'mailjet') {
        sendMailjetMail($config, $email, $receiver_name,$subject, $message, $general);
    }
}
function sendContactEmail($email, $subject, $message, $receiver_name = '')
{

    $general = GeneralSetting::first();


    if ($general->en != 1 || !$general->email_from) {
        return;
    }
    $admin = App\Models\Admin::first();
    $message = shortCodeReplacer("{{message}}", $message, $general->email_template);
    $message = shortCodeReplacer("{{fullname}}", '', $message);
    $message = shortCodeReplacer("{{username}}", $admin->name, $message);

    $config = $general->mail_config;

    if ($config->name == 'php') {
        sendPhpMail($email, $receiver_name, $subject, $message, $general,true);
    } else if ($config->name == 'smtp') {
        sendSmtpMail($config, $email, $receiver_name, $subject, $message, $general,true);
    } else if ($config->name == 'sendgrid') {
        sendSendGridMail($config, $email, $receiver_name,$subject, $message,$general,true);
    } else if ($config->name == 'mailjet') {
        sendMailjetMail($config, $email, $receiver_name,$subject, $message, $general,true);
    }
}

function getContent($data_keys, $singleQuery = false, $limit = null,$orderById = false)
{
    if ($singleQuery) {
        $content = Frontend::where('data_keys', $data_keys)->orderBy('id','desc')->first();
    } else {
        $article = Frontend::query();
        $article->when($limit != null, function ($q) use ($limit) {
            return $q->limit($limit);
        });
        if($orderById){
            $content = $article->where('data_keys', $data_keys)->orderBy('id')->get();
        }else{
            $content = $article->where('data_keys', $data_keys)->orderBy('id','desc')->get();
        }
    }
    return $content;
}


function gatewayRedirectUrl($type = false){
    if ($type) {
        return 'user.deposit.history';
    }else{
        return 'user.deposit';
    }
}

function verifyG2fa($user,$code,$secret = null)
{
    $ga = new GoogleAuthenticator();
    if (!$secret) {
        $secret = $user->tsc;
    }
    $oneCode = $ga->getCode($secret);
    $userCode = $code;
    if ($oneCode == $userCode) {
        $user->tv = 1;
        $user->save();
        return true;
    } else {
        return false;
    }
}


function urlPath($routeName,$routeParam=null){
    if($routeParam == null){
        $url = route($routeName);
    } else {
        $url = route($routeName,$routeParam);
    }
    $basePath = route('home');
    $path = str_replace($basePath,'',$url);
    return $path;
}


function referralComission($user_id, $base_amount)
{

    $user = User::find($user_id);
    $refer = User::find($user->ref_by);
    $general = GeneralSetting::first();

    $expected_bonus = 6;
    $total_bonus = 0;

    if ($refer) {

        //level 1

        $descr = "Level 1 bonus from ".$user->username;
        $amount = ($general->lv1/100) * $base_amount;
        $total_bonus += 3;
        give_bonus($refer->id, $amount, $descr);


        $refer2 = User::find($refer->ref_by);
        if($refer2){

            //level 2
            $descr = "Level 2 bonus from ".$user->username;
            $amount = ($general->lv2/100) * $base_amount;
            $total_bonus +=5;
            give_bonus($refer2->id, $amount, $descr);

            $refer3 = User::find($refer2->ref_by);
            if($refer3){

                //level 3
                $descr = "Level 3 bonus from ".$user->username;
                $amount = ($general->lv3/100) * $base_amount;
                $total_bonus += 2;
                give_bonus($refer3->id, $amount, $descr);


            }

        }

    }


}




function give_bonus($user_id, $amount, $descr, $to_main = 0){


    $refer = User::find($user_id);

    if($refer) {

        if($to_main){
            $refer->balance += $amount;
        }else {
            $refer->bonus_balance += $amount;
        }
        //$refer->balance += $amount;
        $refer->save();





        $transaction = new Transaction();
        $transaction->user_id = $user_id;
        $transaction->amount = $amount;
        if($to_main) {
            $transaction->post_balance = $refer->balance;
        }else{
            $transaction->post_balance = $refer->bonus_balance;
        }
        $transaction->charge = 0;
        $transaction->trx_type = '+';
        $transaction->details = $descr;
        $transaction->trx = getTrx();
        $transaction->save();


    }

}


function send_to_telegram($message){

    //return;
    $gnl = GeneralSetting::first();
    if(!$gnl->enable_telegram){
        return;
    }

    $apiToken = $gnl->telegram_api_token;// "5595553724:AAEuxr1MMjZgJJh-ymZ62pTCbaXIHwm9bXY";//telegram_chat_id

    $chat_ids = explode(",",$gnl->telegram_chat_id);
    $response = [];

    foreach ($chat_ids as $chat_id) {
        $data = [
            'chat_id' => $chat_id,
            'text' => $message
        ];

        $response[] = url_get_contents("https://api.telegram.org/bot$apiToken/sendMessage?" . http_build_query($data));
    }


    return $response;
}



function url_get_contents ($Url) {
    if (!function_exists('curl_init')){
        die('CURL is not installed!');
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $Url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}


function get_bank_name($code){
    $bank = \App\Models\Bank::where('bank_code', $code)->first();
    if($bank){
        return $bank->name;
    }else{
        return '';
    }
}


function getshpaybank() {
    // Define the URL for fetching banks list
    $gateway = Gateway::where('alias','Shpay')->first();

    $url = 'https://transapi.shpays.com/v1/trans/payBanks';
    $date = date("Y-m-d H:i:s");
    $mchid = json_decode($gateway->gateway_parameters)->mchtId->value;
    $appid = json_decode($gateway->gateway_parameters)->appId->value;
    $key = json_decode($gateway->gateway_parameters)->key->value;


        $p = array(
        'countryCode' => 'NG',
        'requestTime' => $date,
        'signType' => 'MD5',
        'mchtId' => $mchid,
        'appId' => $appid,
        );

        ksort($p);
        $string = '';
        foreach($p as $oneKey=>$oneValue)
        $string .= $oneKey ."=". $oneValue."&";
        $string_without_last_and = substr($string, 0, -1);
        $digest = $string_without_last_and .$key;
        $sign = strtoupper(md5($digest));


        // Define query parameters
        $params = [
            'appId' => $appid,
            'countryCode' => 'NG',
            'mchtId' => $mchid,
            'requestTime' => $date,
            'sign' => $sign,
            'signType' => 'MD5',

        ];

        // Sending GET request with the parameters
        $response = Http::get($url, $params);

        // Checking if the request was successful
        if ($response->successful()) {
            // Parsing the response JSON
            $banks = $response->json();

            // Returning the list of banks
            return $banks;
        } else {
            // Returning an error message if the request failed
            return response()->json(['error' => 'Failed to retrieve banks'], $response->status());
        }
}

function getAllBanks(){


    $curl = curl_init();

    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.flutterwave.com/v3/banks/NG",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_HTTPHEADER => array(
            "Authorization: Bearer "
        ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
//echo $response;

    $response_array = json_decode($response,1);

    return $response_array;

}


if(!function_exists('get_account_info')){

    function get_account_info($account_no, $bank_code, $verify = false){
        //curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        $gnl = GeneralSetting::first();
        $params = http_build_query([
            "account_number" => $account_no,
            'account_bank' => $bank_code,
            "country" => "NG"
        ]);
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://api.flutterwave.com/v3/accounts/resolve",
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => $params,
            CURLOPT_HTTPHEADER => array(
                'Authorization: Bearer '.$gnl->flutterwave_key.''
            ),
        ));

        $response = curl_exec($curl);
        $err = curl_error($curl);

        if ($err) {
            // there was an error contacting the Paystack API
            return;
        }

        $response_array = json_decode($response,true);

        if($verify == true){
            return $response_array['status'];
        }

        return $response_array;


    }

}


function Split_Hide_Name($name) {
    return substr($name,0,3)."****".substr($name,8,3);
    //return preg_replace("/(?!^).(?!$)/", "*", $name);
}


function plan_color($id){
    if($id == 1){
        return "orange";
    }elseif ($id == 2){
        return "teal";
    }else{
        return "#161445";
    }
}function showUserLevel($id, $level)
{
    $general = GeneralSetting::first();
    $myref  = showBelow($id);
    $nxt    = $myref;

    for ($i = 1; $i < $level; $i++) {
        $nxt = array();
        foreach ($myref as $uu) {
            $n = showBelow($uu);
            $nxt = array_merge($nxt, $n);
        }
        $myref = $nxt;
    }

    if (!$nxt) {
        echo '
            <div class="card glass-bg">
                <div class="card-body">
                    <h6 class="mb-0 small-font-lg text-secondary text-center">No Data!</h6>
                </div>
            </div>
        ';
    }

    foreach ($nxt as $key => $uu) {
        $key += 1;
        $data = User::where('id', $uu)->first();
        $balance  = $data->balance;


        $fd = 0;
        $fdata = Deposit::where('user_id', $uu)->where('status', 1)->orderBy('created_at', 'asc')->first();
        if ( !blank($fdata) ){
            $fd = getAmount($fdata->amount).' '.$fdata->method_currency;
        }
        $sp = '';
        $ref_balance = '';
        if ( !blank($data->referrer) ){
        $sp = $data->referrer->username;
        }
        if($data->image!=null){
            $userImg = $data->image;
        }else{
            $userImg = 'dummy-profile.png';
        }
        echo '
            <div class="card my-2" style="border-radius: 15px">
                <div class="card-body">
                    <div class="row">
                        <div class="col-12">
                            Account: '.$data->username.'
                        </div>
                        <div class="col-12">
                            Recharge Amount: '.showAmount(refTotalDeposit($data->id)).'
                        </div>
                        <div class="col-12">
                            Join Time: '.$data->created_at.'
                        </div>
                    </div>
                </div>
            </div>
        ';
        // echo '
        // <div class="col-md-6 col-xl-4">
        //     <div class="card glass-bg mb-2">
        //         <div class="card-body px-2">
        //             <div class="row align-items-center">
        //                 <div class="col-auto">
        //                     <img class="rounded-circle" style="width: 60px; height: 60px;" src="' . route("home") . '/assets/images/avatar/man-2.png' .'" alt="Image">
        //                 </div>
        //                 <div class="col">
        //                     <p class="mb-0 small-font text-light text-start" style="margin-bottom: 2px !important;">
        //                         <b class="small-font text-light">ID:</b> '.$data->username.'
        //                     </p>
        //                     <p class="mb-0 small-font text-secondary text-start" style="margin-bottom: 2px !important;">
        //                         <b class="small-font text-secondary">Joined:</b> '.showDateTime($data->created_at).'
        //                     </p>
        //                 </div>
        //             </div>
        //         </div>
        //     </div>
        // </div>
        // ';
    }

}



function teamSize($id, $level)
{
    $myref  = showBelow($id);
    $nxt    = $myref;

    for ($i = 1; $i < $level; $i++) {
        $nxt = array();
        foreach ($myref as $uu) {
            $n = showBelow($uu);
            $nxt = array_merge($nxt, $n);
        }
        $myref = $nxt;
    }
    $key = 0;

    foreach ($nxt as $key => $uu) {
        $key += 1;
    }

    return $key;
}

function teamDeposit($id, $level)
{
    $myref  = showBelow($id);
    $nxt    = $myref;

    for ($i = 1; $i < $level; $i++) {
        $nxt = array();
        foreach ($myref as $uu) {
            $n = showBelow($uu);
            $nxt = array_merge($nxt, $n);
        }
        $myref = $nxt;
    }

    $deposit = 0;
    foreach ($nxt as $uu) {
        $data = User::where('id', $uu)->first();
        $deposit += Deposit::where('user_id', $data->id)->where('status', 1)->sum('amount');
    }

    return $deposit;
}

function check_user_level($id, $level)
{
    $myref  = showBelow($id);
    $nxt    = $myref;
    for ($i = 1; $i < $level; $i++) {
        $nxt = array();
        foreach ($myref as $uu) {
            $n = showBelow($uu);
            $nxt = array_merge($nxt, $n);
        }
        $myref = $nxt;
    }
    return count($nxt);
}

function get_user_level_count($id)
{
    $t = 0;
    $max = 100;
    for ($i = 1; $i < $max; $i++) {
        $count = check_user_level($id, $i);
        if ( $count < 1 ){
            break;
        }
        $t++;
    }

    return $t;
}


function showBelow($id)
{
    $arr = array();
    $under_ref = User::select('id')->where('ref_by', $id)->get();

    foreach ($under_ref as $u) {
        array_push($arr, $u->id);
    }

    return $arr;
}

// new reffer system
function refTotalCount($user_id){
    $user = User::findOrFail($user_id);
    $count = 0;
    foreach ($user->referrals as $user) {
        $count += 1;
        foreach ($user->referrals as $user) {
            $count += 1;
            foreach ($user->referrals as $user) {
                $count += 1;
            }
        }
    }
    return $count;
}

function refTotalDeposit($user_id){
    $user = User::findOrFail($user_id);
    $deposit = 0;
    foreach ($user->referrals as $user) {
        $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->sum('amount');
        foreach ($user->referrals as $user) {
            $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->sum('amount');
            foreach ($user->referrals as $user) {
                $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->sum('amount');
            }
        }
    }
    return getAmount($deposit);
}

function refTotalInvestment($user_id){
    $user = User::findOrFail($user_id);
    $deposit = 0;
    foreach ($user->referrals as $user) {
        $deposit += Investment::where('user_id', $user->id)->where('status', 0)->sum('amount');
        foreach ($user->referrals as $user) {
            $deposit += Investment::where('user_id', $user->id)->where('status', 0)->sum('amount');
            foreach ($user->referrals as $user) {
                $deposit += Investment::where('user_id', $user->id)->where('status', 0)->sum('amount');
            }
        }
    }
    return getAmount($deposit);
}

function refTotalWithdraw($user_id){
    $user = User::findOrFail($user_id);
    $withdraw = null;
    foreach ($user->referrals as $user) {
        $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->sum('amount');
        foreach ($user->referrals as $user) {
            $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->sum('amount');
            foreach ($user->referrals as $user) {
                $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->sum('amount');
            }
        }
    }
    return getAmount($withdraw);
}

// today
function refTodayCount($user_id){
    $user = User::findOrFail($user_id);
    $count = 0;
    foreach ($user->referrals as $user) {
        if (date_format($user->created_at, 'Ymd') == date('Ymd')) {
            $count += 1;
        }
        foreach ($user->referrals as $user) {
            if (date_format($user->created_at, 'Ymd') == date('Ymd')) {
                $count += 1;
            }
            foreach ($user->referrals as $user) {
                if (date_format($user->created_at, 'Ymd') == date('Ymd')) {
                    $count += 1;
                }
            }
        }
    }
    return $count;
}

function refTodayDeposit($user_id){
    $user = User::findOrFail($user_id);
    $deposit = 0;
    foreach ($user->referrals as $user) {
        $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
        foreach ($user->referrals as $user) {
            $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
            foreach ($user->referrals as $user) {
                $deposit += Deposit::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
            }
        }
    }
    return getAmount($deposit);
}

function refTodayWithdraw($user_id){
    $user = User::findOrFail($user_id);
    $withdraw = null;
    foreach ($user->referrals as $user) {
        $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
        foreach ($user->referrals as $user) {
            $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
            foreach ($user->referrals as $user) {
                $withdraw += Withdrawal::where('user_id', $user->id)->where('status', 1)->whereDate('created_at', Carbon::today())->sum('amount');
            }
        }
    }
    return getAmount($withdraw);
}