<?php

use App\GeneralSetting;
use App\User;
use App\UserExtra;

function get_image($image, $clean = '')
{
    return file_exists($image) && is_file($image) ? asset($image) . $clean : asset(config('constants.image.default'));
}


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


function description_shortener($string, $length = null)
{
    if (empty($length)) $length = config('constants.stringLimit.default');
    return Illuminate\Support\Str::limit($string, $length);
}


function sidenav_active($routename, $class = 'active open')
{
    if (is_array($routename)) {
        foreach ($routename as $key => $value) {
            if (request()->routeIs($value)) {
                return $class;
            }
        }
    } elseif (request()->routeIs($routename)) {
        return $class;
    }
}


function show_datetime($date, $format = 'd M, Y h:ia')
{

    return \Carbon\Carbon::parse($date)->format($format);
}


function shortcode_replacer($shortcode, $replace_with, $template_string)
{

    return str_replace($shortcode, $replace_with, $template_string);
}


function verification_code($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 site_precision()
{
    return config('constants.currency.precision.' . strtolower(config('constants.currency.base')));
}

function formatter_money($money, $currency = null)
{
    if (!$currency) $currency = config('constants.currency.base');
    $money = round($money, config('constants.currency.precision.' . strtolower($currency)));
    return $money;
}


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

    if (!empty($old)) {
        remove_file($location . '/' . $old);
        remove_file($location . '/thumb_' . $old);
    }

    $filename = uniqid() . time() . '.' . $file->getClientOriginalExtension();

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

    if (!empty($thumb)) {

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

    return $filename;
}


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


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

function send_general_email($email, $subject, $message, $receiver_name = '')
{
    $general = GeneralSetting::first();

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

    $message = shortcode_replacer("{{message}}", $message, $general->etemp);
    $message = shortcode_replacer("{{name}}", $receiver_name, $message);
    $config = $general->mail_config;

    if ($config->name == 'php') {
        send_php_mail($email, $receiver_name, $general->efrom, $subject, $message);
    } else if ($config->name == 'smtp') {
        send_smtp_mail($config, $email, $receiver_name, $general->efrom, $general->sitetitle, $subject, $message);
    } else if ($config->name == 'sendgrid') {
        send_sendgrid_mail($config, $email, $receiver_name, $general->efrom, $general->sitetitle, $subject, $message);
    } else if ($config->name == 'mailjet') {
        send_mailjet_mail($config, $email, $receiver_name, $general->efrom, $general->sitetitle, $subject, $message);
    }
}

function send_email($user, $type, $shortcodes = [])
{
    $general = GeneralSetting::first();
    $email_template = \App\EmailTemplate::where('act', $type)->where('email_status', 1)->first();
    if ($general->en != 1 || !$email_template) {
        return;
    }

    $message = shortcode_replacer("{{name}}", $user->username, $general->etemp);
    $message = shortcode_replacer("{{message}}", $email_template->email_body, $message);

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

    foreach ($shortcodes as $code => $value) {
        $message = shortcode_replacer('{{' . $code . '}}', $value, $message);
    }
    $config = $general->mail_config;

    if ($config->name == 'php') {
        send_php_mail($user->email, $user->username, $general->efrom, $email_template->subj, $message);
    } else if ($config->name == 'smtp') {
        send_smtp_mail($config, $user->email, $user->username, $general->efrom, $general->sitetitle, $email_template->subj, $message);
    } else if ($config->name == 'sendgrid') {
        send_sendgrid_mail($config, $user->email, $user->username, $general->efrom, $general->sitetitle, $email_template->subj, $message);
    } else if ($config->name == 'mailjet') {
        send_mailjet_mail($config, $user->email, $user->username, $general->efrom, $general->sitetitle, $email_template->subj, $message);
    }
}

function send_php_mail($receiver_email, $receiver_name, $sender_email, $subject, $message)
{
    $general = GeneralSetting::first();
    $headers = "From: $general->sitename <$sender_email> \r\n";
    $headers .= "Reply-To: $receiver_name <$receiver_email> \r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=utf-8\r\n";
    @mail($receiver_email, $subject, $message, $headers);
}

function send_smtp_mail($config, $receiver_email, $receiver_name, $sender_email, $sender_name, $subject, $message)
{
    $f = fsockopen($config->host, $config->port);
    if ($f !== false) {
        $res = fread($f, 1024);
        if (strlen($res) > 0 && strpos($res, '220') === 0) {
            $mail_val = [
                'send_to_name' => $receiver_name,
                'send_to' => $receiver_email,
                'email_from' => $sender_email,
                'email_from_name' => $sender_name,
                'subject' => $subject,
            ];
            Config::set('mail.driver', $config->driver);
            Config::set('mail.from', $config->username);
            Config::set('mail.name', $sender_name);
            Config::set('mail.host', $config->host);
            Config::set('mail.port', $config->port);
            Config::set('mail.username', $config->username);
            Config::set('mail.password', $config->password);
            Config::set('mail.encryption', $config->enc);
            $xx = Mail::send('partials.email', ['body' => $message], function ($send) use ($mail_val) {
                $send->from($mail_val['email_from'], $mail_val['email_from_name']);
                $send->replyto($mail_val['email_from'], $mail_val['email_from_name']);
                $send->to($mail_val['send_to'], $mail_val['send_to_name'])->subject($mail_val['subject']);
            });
        }
    }
}

function send_sendgrid_mail($config, $receiver_email, $receiver_name, $sender_email, $sender_name, $subject, $message)
{
    require 'core/app/Http/Helpers/Lib/Sendgrid/vendor/autoload.php';

    $sendgridMail = new \SendGrid\Mail\Mail();
    $sendgridMail->setFrom($sender_email, $sender_name);
    $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) {
        // echo 'Caught exception: '. $e->getMessage() ."\n";
    }
}

function send_mailjet_mail($config, $receiver_email, $receiver_name, $sender_email, $sender_name, $subject, $message)
{
    require 'core/app/Http/Helpers/Lib/Mailjet/vendor/autoload.php';
    $mj = new \Mailjet\Client($config->public_key, $config->secret_key, true, ['version' => 'v3.1']);
    $body = [
        'Messages' => [
            [
                'From' => [
                    'Email' => $sender_email,
                    'Name' => $sender_name,
                ],
                'To' => [
                    [
                        'Email' => $receiver_email,
                        'Name' => $receiver_name,
                    ]
                ],
                'Subject' => $subject,
                'TextPart' => "",
                'HTMLPart' => $message,
            ]
        ]
    ];
    $response = $mj->post(\Mailjet\Resources::$Email, ['body' => $body]);
}


function send_sms($user, $type, $shortcodes = [])
{
    $general = GeneralSetting::first(['sn', 'smsapi']);
    $sms_template = \App\SmsTemplate::where('act', $type)->where('sms_status', 1)->first();
    if ($general->sn == 1 && $sms_template) {
        $template = $sms_template->sms_body;
        foreach ($shortcodes as $code => $value) {
            $template = shortcode_replacer('{{' . $code . '}}', $value, $template);
        }
        $template = urlencode($template);
        $message = shortcode_replacer("{{number}}", $user->mobile, $general->smsapi);
        $message = shortcode_replacer("{{message}}", $template, $message);
        $result = @file_get_contents($message);
    }
}

function activeTemplate($asset = false)
{
    $template = '';
    if (session()->has('active_template')) {
        $template = session('active_template');
    } else {
        $gs = GeneralSetting::first(['active_template']);
        $template = $gs->active_template;
        session()->put(['active_template' => $template]);
    }
    if ($asset) return 'assets/templates/' . $template . '/';
    return 'templates.' . $template . '.';
}

function recaptcha()
{
    $recaptcha = \App\Plugin::where('act', 'google-recaptcha3')->where('status', 1)->first();
    return $recaptcha ? $recaptcha->generateScript() : '';
}

function recaptcha_validate($response)
{
    $recaptcha = \App\Plugin::where('act', 'google-recaptcha3')->where('status', 1)->first();
    if (!$recaptcha) return true;
    $verify_url = 'https://www.google.com/recaptcha/api/siteverify';
    $secret_key = $recaptcha->shortcode->secretkey->value;
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $verify_url);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=$secret_key&response=$response");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $capthca_response = curl_exec($curl);
    curl_close($curl);
    return json_decode($capthca_response);
}


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


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

function cryptoQR($wallet, $amount, $crypto = null)
{

    $varb = $wallet . "?amount=" . $amount;
    return "https://chart.googleapis.com/chart?chs=300x300&cht=qr&chl=$varb&choe=UTF-8";
}


function curlContent($url)
{

    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data

    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);


    //execute post
    $result = curl_exec($ch);

    //close connection
    curl_close($ch);

    return $result;
}


function printEmail($email)
{
    $beforeAt = strstr($email, '@', true);
    $withStar = substr($beforeAt, 0, 2) . str_repeat("**", 5) . substr($beforeAt, -2) . strstr($email, '@');
    return $withStar;
}


function getUserById($id)
{
    return User::find($id);
}


///////////////////////////////////////// MLM FUNCTION //





function createBVLog($user_id, $lr, $amount, $details){
    $bvlog = new App\BvLog();
    $bvlog->user_id = $user_id;
    $bvlog->position = $lr;
    $bvlog->amount = $amount;
    $bvlog->details = $details;
    $bvlog->save();
}




function mlmWidth()
{
    return config('constants.mlm.width');
}

function khaliPosition($user_id)
{
    for ($i = 1; $i <= mlmWidth(); $i++) {
        $check = User::where('pos_id', $user_id)->where('position', $i)->count();
        if ($check == 0) {
            return $i;
        }
    }
}

function khaliAcheNaki($user_id)
{
    $count = User::where('pos_id', $user_id)->count();
    if ($count < mlmWidth()) {
        return khaliPosition($user_id);
    } else {
        return 0;
    }
}

function showPositionBelow($id)
{
    $arr = array();
    $under_ref = User::where('pos_id', $id)->get();
    foreach ($under_ref as $u) {
        array_push($arr, $u->id);
    }
    return $arr;
}

function getPosition($refer_id, $position)
{
    $stststs = 0;
    $firstCheck = User::where('pos_id', $refer_id)->where('position', $position)->count();
    if ($firstCheck == 0) {
        $res['pos_id'] = $refer_id;
        $res['position'] = $position;
        return $res;
    } else {
        $refer = User::where('pos_id', $refer_id)->where('position', $position)->first();
        if (khaliAcheNaki($refer->id) != 0) {
            $res['pos_id'] = $refer->id;
            $res['position'] = khaliAcheNaki($refer->id);
            return $res;
        } else {
            $level = 0;
            while (empty($res)) {
                $level++;
                $myref = showPositionBelow($refer->id);
                $nxt = $myref;
                for ($i = 1; $i < $level; $i++) {
                    $nxt = array();
                    foreach ($myref as $uu) {
                        $n = showPositionBelow($uu);
                        $nxt = array_merge($nxt, $n);
                    }
                    $myref = $nxt;
                }
                foreach ($nxt as $uu) {
//                    echo $uu . '-----';
                    if (khaliAcheNaki($uu) != 0) {
                        $res['pos_id'] = $uu;
                        $res['position'] = khaliAcheNaki($uu);
                        $stststs = 1;
                    }
                    if ($stststs == 1) {
                        break;
                    }
                }
                if ($stststs == 1) {
                    break;
                }
            }
            return $res;
        }
    }
}


////-------------->>>>>>>> UPTO ROOT

function isUserExists($id)
{
    $user = User::find($id);
    if ($user) {
        return true;
    } else {
        return false;
    }
}

function getPositionId($id)
{
    $user = User::find($id);
    if ($user) {
        return $user->pos_id;
    } else {
        return 0;
    }
}

function getPositionLocation($id)
{
    $user = User::find($id);
    if ($user) {
        return $user->position;
    } else {
        return 0;
    }
}


function updateFreeCount($id)
{
    while ($id != "" || $id != "0") {
        if (isUserExists($id)) {
            $posid = getPositionId($id);
            if ($posid == "0") {
                break;
            }
            $position = getPositionLocation($id);

            $extra = UserExtra::where('user_id', $posid)->first();

            if ($position == 1) {
                $extra->free_left += 1;
            } else {
                $extra->free_right += 1;
            }
            $extra->save();


            $id = $posid;
        } else {
            break;
        }
    }//while

}

function updatePaidCount($id)
{
    while ($id != "" || $id != "0") {
        if (isUserExists($id)) {
            $posid = getPositionId($id);
            if ($posid == "0") {
                break;
            }
            $position = getPositionLocation($id);

            $extra = UserExtra::where('user_id', $posid)->first();

            if ($position == 1) {
                $extra->free_left -= 1;
                $extra->paid_left += 1;
            } else {
                $extra->free_right -= 1;
                $extra->paid_right += 1;
            }
            $extra->save();


            $id = $posid;
        } else {
            break;
        }
    }//while

}


function updateBV($id, $bv, $details)
{
    while ($id != "" || $id != "0") {
        if (isUserExists($id)) {
            $posid = getPositionId($id);
            if ($posid == "0") {
                break;
            }

            $posUser = User::find($posid);
            if ($posUser->plan_id != 0) {

                $position = getPositionLocation($id);
                $extra = UserExtra::where('user_id', $posid)->first();

                $bvlog = new App\BvLog();
                $bvlog->user_id = $posid;

                if ($position == 1) {
                    $extra->bv_left += $bv;
                    $bvlog->position = '1';
                } else {
                    $extra->bv_right += $bv;
                    $bvlog->position = '2';
                }
                $extra->save();

                $bvlog->amount = $bv;
                $bvlog->details = $details;
                $bvlog->save();
            }


            $id = $posid;
        } else {
            break;
        }
    }//while

}


function treeComission($id, $amount, $details)
{
    while ($id != "" || $id != "0") {
        if (isUserExists($id)) {
            $posid = getPositionId($id);
            if ($posid == "0") {
                break;
            }


            $posUser = User::find($posid);
            if ($posUser->plan_id != 0) {

                $posUser->balance = $posUser->balance + $amount;
                $posUser->save();


///////// CREATE TRANSACTION TYPE => binary_comission


                $posUser->transactions()->create([
                    'trx' => getTrx(),
                    'user_id' => $posUser->id,
                    'amount' => $amount,
                    'main_amo' => $amount,
                    'balance' => $posUser->balance,
                    'title' => $details,
                    'charge' => 0,
                    'type' => 'binary_comission',
                ]);

                $user = User::find($id);

                $gnl = GeneralSetting::first();
                send_email($posUser, 'binary_comission', [
                    'amount' => formatter_money($amount) . ' ' . $gnl->cur_text,
                    'username' => $user->username,
                ]);

                send_sms($posUser, 'binary_comission', [
                    'amount' => formatter_money($amount) . ' ' . $gnl->cur_text,
                    'username' => $user->username,
                ]);

            }

            $id = $posid;
        } else {
            break;
        }
    }//while

}


function referralComission($user_id, $details)
{

    $user = User::find($user_id);
    $refer = User::find($user->ref_id);
    if ($refer) {
        $plan = App\Plan::find($refer->plan_id);
        if ($plan) {
            $amount = $plan->ref_com;
            $refer->balance = $refer->balance + $amount;
            $refer->save();

//////// CREATE TRANSACTION TYPE => referral_commision


            $refer->transactions()->create([
                'trx' => getTrx(),
                'user_id' => $refer->id,
                'amount' => $amount,
                'main_amo' => $amount,
                'balance' => $refer->balance,
                'title' => $details,
                'charge' => 0,
                'type' => 'referral_commision',
            ]);

            $gnl = GeneralSetting::first();
            send_email($refer, 'referral_commission', [
                'amount' => formatter_money($amount) . ' ' . $gnl->cur_text,
                'username' => $user->username,
            ]);

            send_sms($refer, 'referral_commission', [
                'amount' => formatter_money($amount) . ' ' . $gnl->cur_text,
                'username' => $user->username,
            ]);

        }


    }


}


///////-------------------->>>>>>>>>>>>>> TREE /////---------------------------->>>>>>>>>>>>>



function getPositionUser($id, $position)
{
    return User::where('pos_id', $id)->where('position', $position)->first();
}

function showTreePage($id)
{
    $res = array_fill_keys(array('b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o'), null);
    $res['a'] = User::find($id);

    $res['b'] = getPositionUser($id, 1);
    if ($res['b']) {
        $res['d'] = getPositionUser($res['b']->id, 1);
        $res['e'] = getPositionUser($res['b']->id, 2);
    }
    if ($res['d']) {
        $res['h'] = getPositionUser($res['d']->id, 1);
        $res['i'] = getPositionUser($res['d']->id, 2);
    }
    if ($res['e']) {
        $res['j'] = getPositionUser($res['e']->id, 1);
        $res['k'] = getPositionUser($res['e']->id, 2);
    }
    $res['c'] = getPositionUser($id, 2);
    if ($res['c']) {
        $res['f'] = getPositionUser($res['c']->id, 1);
        $res['g'] = getPositionUser($res['c']->id, 2);
    }
    if ($res['f']) {
        $res['l'] = getPositionUser($res['f']->id, 1);
        $res['m'] = getPositionUser($res['f']->id, 2);
    }
    if ($res['g']) {
        $res['n'] = getPositionUser($res['g']->id, 1);
        $res['o'] = getPositionUser($res['g']->id, 2);
    }
    return $res;
}


function showSingleUserinTree($user)
{
    $res = '';
    if ($user) {
        if ($user->plan_id == 0) {
            $userType = "free-user";
            $stShow = "Free";
            $planName = '';
        } else {
            $userType = "paid-user";
            $stShow = "Paid";
            $planName = $user->plan->name;
        }

        $img = get_image(config('constants.user.profile.path') . '/' . $user->image);
        $refby = getUserById($user->ref_id)->fullname ?? '';
        $hisTree = route('user.other.tree',$user->username);

        $extraData = " data-name=\"$user->fullname\"";
        $extraData .= " data-treeurl=\"$hisTree\"";
        $extraData .= " data-status=\"$stShow\"";
        $extraData .= " data-plan=\"$planName\"";
        $extraData .= " data-image=\"$img\"";
        $extraData .= " data-refby=\"$refby\"";
        $extraData .= " data-lpaid=\"" . @$user->user_extra->paid_left . "\"";
        $extraData .= " data-rpaid=\"" . @$user->user_extra->paid_right . "\"";
        $extraData .= " data-lfree=\"" . @$user->user_extra->free_left . "\"";
        $extraData .= " data-rfree=\"" . @$user->user_extra->free_right . "\"";
        $extraData .= " data-lbv=\"" . formatter_money(@$user->user_extra->bv_left) . "\"";
        $extraData .= " data-rbv=\"" . formatter_money(@$user->user_extra->bv_right) . "\"";


        $res .= "<div class=\"user showDetails\" type=\"button\" $extraData>";
        $res .= "<img src=\"$img\" alt=\"*\"  class=\"$userType\">";
        $res .= "<p class=\"user-name\">$user->username</p>";

    } else {
        $img = get_image('assets/images/nouser.png');

        $res .= "<div class=\"user\" type=\"button\">";
        $res .= "<img src=\"$img\" alt=\"*\"  class=\"no-user\">";
        $res .= "<p class=\"user-name\">No User</p>";
    }

    $res .= " </div>";
    $res .= " <span class=\"line\"></span>";

    return $res;

}




//////////////////////// TREE AUTH
function treeAuth($whichID, $whoID){

        if($whichID==$whoID){
            return true;
        }

   $formid = $whichID;

   while($whichID!=""||$whichID!="0"){
    if(isUserExists($whichID)){
        $posid = getPositionId($whichID);
        if($posid=="0"){
            break;
        }
        $position=getPositionLocation($whichID);
        if($posid==$whoID){
            return true;
        }
        $whichID =$posid;
    } else {
        break;
    }
        }//while
        return 0;
}


