<?php namespace App;

use App\Settings;
use Auth;
use DB;
class functions
{
    public function toLatin($string) {
        $persian_num = array('۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹');
        $latin_num = range(0, 9);
        $string = str_replace($persian_num, $latin_num, $string);
        return $string;
    }


    public function payment_order($id_order,$api = false,$apiV = 1,$robot = null) {
        $payment_gateway = getSetting('payment_gateway');
        $order = Orders::where('id',$id_order)->where('id_user',Auth::user()->id)->whereNull('payment')->first();
        if($api == true)
            $CallbackURL = asset('api/v'.$apiV)."/order/$order->id/callback"; //Required
        elseif(isset($robot))
            $CallbackURL = asset('')."telegram/$robot/order/$order->id/callback"; //Required
        else
            $CallbackURL = asset('')."$order->orders_model/$order->type/$order->id/callback"; //Required

        if($payment_gateway=='pay'){
            $PayIrToken = getSetting('PayIrToken');
            $params = array(
                'api' => $PayIrToken,
                'amount' => $order->amount*10,
                'name' => Auth::user()->name .' '. Auth::user()->family,
                'mobile' => Auth::user()->mobile,
                'factorNumber' => $order->id,
                'description' => 'خرید '.Auth::user()->name.' '.Auth::user()->family,
                'redirect' => $CallbackURL,
            );
            $authorization = null;
            $result = $this->Curl('https://pay.ir/pg/send',$params,$authorization);
            if($result->status) {
                $go = "https://pay.ir/pg/$result->token";
                header("Location: $go");
            } else {
                echo $result->errorMessage;
            }

        }else if($payment_gateway=='idpay'){
            $IdpayToken = getSetting('IdpayToken');
            $params = array(
                'order_id' => time(),
                'amount' => $order->amount*10,
                'name' => Auth::user()->name .' '. Auth::user()->family,
                'phone' => Auth::user()->mobile,
                'mail' => Auth::user()->email,
                'desc' => 'خرید '.Auth::user()->name.' '.Auth::user()->family,
                'callback' => $CallbackURL,
            );
            $authorization = 'X-API-KEY: '.$IdpayToken;
            $result = $this->Curl('https://api.idpay.ir/v1.1/payment',$params,$authorization);
            header('Location: ' . $result->link);
            exit();
        }else if($payment_gateway=='zarinpal'){
            $Token = Settings::where('name','ZarinpalToken')->first()->value;
            $data = array(
                "merchant_id" => $Token,
                "amount" => $order->amount * 10,
                "callback_url" => $CallbackURL,
                "description" => 'شارژ کیف پول ',
                "metadata" => [ "email" => Auth::user()->email, "mobile" => Auth::user()->mobile],
            );
            $jsonData = json_encode($data);
            $ch = curl_init('https://api.zarinpal.com/pg/v4/payment/request.json');
            curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v1');
            curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
            curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($jsonData)
            ));

            $result = curl_exec($ch);
            $err = curl_error($ch);
            $result = json_decode($result, true, JSON_PRETTY_PRINT);
            curl_close($ch);
            //dd($result);
            header("Location: https://www.zarinpal.com/pg/StartPay/" . $result['data']["authority"]);
            exit();

        }
        elseif($payment_gateway=='zibal'){
            $ZibalToken = Settings::where('name','ZibalToken')->first()->value;
            $parameters = array(
                "merchant"=> $ZibalToken,//required
                "callbackUrl"=> $CallbackURL,//required
                "amount"=> $order->amount*10,

                "orderId"=> time(),//optional
                "mobile"=> Auth::user()->mobile
            );


            $url = 'https://gateway.zibal.ir/v1/request';
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $response  = curl_exec($ch);
            curl_close($ch);
            $response = json_decode($response);


            if ($response->result == 100)
            {
                $startGateWayUrl = "https://gateway.zibal.ir/start/" . $response->trackId;
                header('location: '.$startGateWayUrl);
            }
            else{
                echo "errorCode: ".$response->result."<br>";
                echo "message: ".$response->message;
            }

        }
    }

    public function payment_order_callback($id_order,$request = null) {
        $payment_gateway = getSetting('payment_gateway');
        $order = Orders::where('id',$id_order)->where('id_user',Auth::user()->id)->whereNull('payment')->first();
        if($payment_gateway=='pay') {
            if($request->status != 0 ){
                $PayIrToken = getSetting('PayIrToken');
                $params = array(
                    'api' => $PayIrToken,
                    'token' => $request->token,
                );
                $result = $this->Curl('https://pay.ir/pg/verify',$params,null);
                if(isset($result->status)){
                    if($result->status == 1){
                        $result = self::payment_success($order->id,$result->refNumber,'پی آی آر');
                    } else {
                        $result = array('status' => false, 'message' => $result->errorMessage);
                    }
                } else {
                    if($_GET['status'] == 0){
                        $result = array('status' => false, 'message' => "خطا در پرداخت!");
                    }
                }
            }else
                $result = array('status' => false, 'message' => "پرداخت لغو شد!");

        }else if($payment_gateway=='idpay'){
            $IdpayToken = getSetting('IdpayToken');
            if($request->status == 10) {
                $CheckCardBank = self::CheckCardBank($order->amount, $order->id, $request->card_no, $request->hashed_card_no, 'hash');
                if ($CheckCardBank == true) {
                    $params = array(
                        'id' => $request->id,
                        'order_id' => $request->order_id,
                    );
                    $authorization = 'X-API-KEY: ' . $IdpayToken;
                    $res = $this->Curl('https://api.idpay.ir/v1.1/payment/verify', $params, $authorization);
                    if (isset($res->status) && $res->status == 100) {
                        $result = self::payment_success($order->id, $res->track_id, 'آی دی پی');
                    } else
                        $result = array('status' => false, 'message' => "پرداخت با شکست مواجه شد!");
                } else {
                    $order->status = 'معلق,عودت';
                    $order->payment_gateway = 'درگاه زیبال';
                    $order->save();
                    $result = array('status' => false, 'message' => "کارتی که پرداخت کرده اید در پنل کاربری ثبت نشده است و مبلغ پرداخت شده حداکثر تا یک ساعت آینده به کارت پرداخت کننده به صورت اتوماتیک عودت میشود و تیکتی در این خصوص برای شما ثبت شده است که آن را بررسی و پیگیری نمایید.");
                }
            }else
                $result = array('status' => false, 'message' => "پرداخت کنسل شد!");
        }else if($payment_gateway=='zarinpal'){
            $Token = Settings::where('name','ZarinpalToken')->first()->value;
            if($request->Status == 'OK'){
                $data = array("merchant_id" => $Token, "authority" => $request->Authority, "amount" => $order->amount * 10);
                $jsonData = json_encode($data);
                $ch = curl_init('https://api.zarinpal.com/pg/v4/payment/verify.json');
                curl_setopt($ch, CURLOPT_USERAGENT, 'ZarinPal Rest Api v4');
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                    'Content-Type: application/json',
                    'Content-Length: ' . strlen($jsonData)
                ));

                $result = curl_exec($ch);
                curl_close($ch);
                $result = json_decode($result, true);
                if(isset($result['data']['code']) && $result['data']['code'] == 100){
                    $result = self::payment_success($order->id, $result['data']['ref_id'], 'زرین‌پال');
                }else
                    $result = array('status' => false, 'message' => "پرداخت با شکست مواجه شد!");
            }else{
                $result = array('status' => false, 'message' => "پرداخت کنسل شد!");
            }
        }
        elseif($payment_gateway=='zibal'){
            $ZibalToken = Settings::where('name','ZibalToken')->first()->value;

            if($request->success == 1){
                $parameters = array(
                    "merchant"=> $ZibalToken,//required
                    "trackId"=> $request->trackId
                );

                $url = 'https://gateway.zibal.ir/v1/verify';
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, $url);
                curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($parameters));
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                $response  = curl_exec($ch);
                curl_close($ch);
                $response = json_decode($response);
                if(isset($response->result) && $response->result == 100){
                    $result = self::payment_success($order->id, $response->refNumber,'زیبال');
                }else
                    $result = array('status' => false, 'message' => "پرداخت با شکست مواجه شد!");
            }else{
                $result = array('status' => false, 'message' => "پرداخت کنسل شد!");
            }

        }

        return (object)$result;
    }

    private function payment_success($id_order,$trans_id,$nameGatway){
        $order = Orders::where('id',$id_order)->where('id_user',Auth::user()->id)->whereNull('payment')->first();
        $order->payment = $order->amount;
        $default_exchanger = getSetting('default_exchanger');
        if(in_array($default_exchanger, ['binance', 'coinex'])) {
            $order->status = 'پرداخت شده';
        }else{
            $order->status = 'در دست اقدام';
        }
        $order->payment_gateway = $nameGatway;
        $order->payment_tracking = $trans_id;
        $order->save();
        $result = array('status' => true, 'message' => "پرداخت با موفقیت انجام شد!",'RefID'=>$trans_id);
        //}
        return $result;
    }


    public function payment_wallet_order($id_order) {
        if(isset(Auth::user()->id))
            $user = \App\User::find(Auth::user()->id);
        else
            $user =  \App\User::find(Orders::where('id',$id_order)->whereNull('payment')->first()->id_user);

        $order = Orders::where('id',$id_order)->where('id_user',$user->id)->whereNull('payment')->first();
        if($order->amount <= $user->wallet){
            DB::beginTransaction();
            try {
                \App\User::find($user->id)->decrement('wallet',$order->amount);

                $user_finance = new \App\UserFinance;
                $user_finance->type = 'برداشت';
                $user_finance->description = 'خرید '.$order->orders_model;
                $user_finance->id_user = $user->id;
                $user_finance->amount = $order->amount;
                $user_finance->stock = $user->wallet - $order->amount;
                $user_finance->id_order = $id_order;
                $user_finance->save();

                $order->payment = $order->amount;
                $default_exchanger = getSetting('default_exchanger');
                if(in_array($default_exchanger, ['binance', 'coinex'])) {
                    $order->status = 'پرداخت شده';
                }else{
                    $order->status = 'در دست اقدام';
                }
                $order->payment_gateway = 'کیف پول';
                $order->save();
                //self::CheckInvitation($order->id);
                DB::commit();
                $result = array('status' => true, 'message' => 'پرداخت با موفقیت انجام شد!');


            } catch (\Exception $e) {
                DB::rollback();
                $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد'.$e);
            }
        }else
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد');

        return (object)$result;
    }

    public function sell_wallet_order($id_order,$id_user = null) {
        $id_user = isset(Auth::user()->id) ? Auth::user()->id : $id_user;
        $user = \App\User::find($id_user);

        $order = Orders::where('id',$id_order)->where('id_user',$user->id)->
        where('type','sell')->whereNull('payment')->first();

        DB::beginTransaction();
        try {
            \App\User::find($user->id)->increment('wallet',$order->amount);

            $user_finance = new \App\UserFinance;
            $user_finance->type = 'واریز';
            $user_finance->description = 'فروش '.$order->orders_model;
            $user_finance->id_user = $user->id;
            $user_finance->amount = $order->amount;
            $user_finance->stock = $user->wallet + $order->amount;
            $user_finance->id_order = $id_order;
            $user_finance->save();

            $order->payment = $order->amount;
            $order->wallet = $order->amount;
            $default_exchanger = getSetting('default_exchanger');
            if(in_array($default_exchanger, ['binance', 'coinex'])) {
                $order->status = 'پرداخت شده';
            }else{
                $order->status = 'در دست اقدام';
            }
            $order->save();

            DB::commit();
            $result = array('status' => true, 'message' => 'پرداخت با موفقیت انجام شد!');


        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد');
        }


        return (object)$result;
    }

    public function payment_order_BackStock($id_order) {
        if(isset(Auth::user()->id))
            $user = \App\User::find(Auth::user()->id);
        else
            $user = \App\User::find(Orders::where('id',$id_order)->first()->id_user);

        $order = Orders::where('id',$id_order)->where('id_user',$user->id)->
        where('type','!=','sell')->whereNotNull('payment')->first();

        DB::beginTransaction();
        try {
            \App\User::find($user->id)->increment('wallet',$order->amount);

            $user_finance = new \App\UserFinance;
            $user_finance->type = 'واریز';
            $user_finance->description = 'برگشت خرید '.$order->orders_model;
            $user_finance->id_user = $user->id;
            $user_finance->amount = $order->amount;
            $user_finance->stock = ($user->wallet+$order->amount);
            $user_finance->id_order = $id_order;
            $user_finance->save();

            $invitation = \App\UserInvitation::where('id_order',$order->id)->first();
            if(isset($invitation)){
                \App\User::find($invitation->id_user)->decrement('wallet',$invitation->amount);
                $UserFinance = \App\UserFinance::where('description','پورسانت سفارش')->where('amount',$invitation->amount)->orderBy('id','desc')->first();
                $UserFinance->delete();
                $invitation->delete();
            }

            DB::commit();
            $result = array('status' => true, 'message' => 'پرداخت با موفقیت انجام شد!');
        } catch (\Exception $e) {
            DB::rollback();
            $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد');
        }
        return (object)$result;
    }

    public function CheckCardBank($amount, $id_order, $maskCard, $HashCardNumber = null, $model = null, $id_user = null)
    {
        $id_user = isset(Auth::user()->id) ? Auth::user()->id : $id_user;

        $UserCardBank = \App\CardBank::select('card_number')->where('confirm','1')->where('id_user',Auth::user()->id)->get();
        if(isset($HashCardNumber)){
            foreach($UserCardBank as $card){
                $hash = strtoupper(hash('sha256', $card->card_number));
                if($hash == $HashCardNumber)
                    return true;
            }
        }else{
            foreach($UserCardBank as $card){
                $CardNumberFrist = substr($maskCard,0,6);
                $CardFrist = substr($card->card_number,0,6);
                $CardNumberLast = substr($maskCard,-4);
                $CardLast = substr($card->card_number,-4);
                if($CardNumberFrist == $CardFrist && $CardNumberLast == $CardLast)
                    return true;
            }
        }

        $ticket = new \App\Ticket;
        $ticket->title = 'عدم انجام سفارش';
        $ticket->unit = 'مالی';
        $ticket->seen_admin = 1;
        $ticket->status = 1;
        $ticket->id_order = $id_order;
        $ticket->id_user = $id_user;
        $ticket->save();

        $ticket_message = new \App\TicketMessage;
        $ticket_message->id_ticket = $ticket->id;
        $ticket_message->author = 'admin';
        $ticket_message->message = '        شما سفارشی به مبلغ '. number_format($amount) .'تومان را توسط کارت '.'<span dir="ltr">' .$maskCard .'</span>' .' انجام داده اید که هنوز این کارت در پنل کاربری ثبت یا تایید نشده است. مبلغ کسر شده حداکثر تا یک ساعت آینده به صورت اتوماتیک به کارت عودت میشود.

<a href="'.asset('profile/financial').'" class="typo_link text-warning">جهت افزودن کارت کلیک کنید</a>
        ';
        $ticket_message->save();
        return false;
    }

    public function CheckInvitation($id_order){
        if(isset(Auth::user()->id))
            $user = \App\User::find(Auth::user()->id);
        else
            $user = \App\User::find(Orders::where('id',$id_order)->first()->id_user);

        $order = Orders::where('id',$id_order)->where('type','!=','sell')->whereNotNull('payment')->where('id_user',$user->id)->first();
        if($user->invitationID != '' && isset($user->invitationID)){
            $invitation_percent = getSetting('invitation_percent_'.$order->orders_model, false);
            if(isset($invitation_percent)):
                $invitation_percent = $invitation_percent->value;
                DB::beginTransaction();
                try {
                    if($invitation_percent < 100)
                        $amount_percent = ($order->amount / 100)* $invitation_percent;
                    else
                        $amount_percent = $invitation_percent;

                    \App\User::find($user->invitationID)->increment('wallet',$amount_percent);

                    $invitationID =  \App\User::find($user->invitationID);

                    $user_finance = new \App\UserFinance;
                    $user_finance->type = 'واریز';
                    $user_finance->description = 'پورسانت سفارش';
                    $user_finance->id_user = $user->invitationID;
                    $user_finance->amount = $amount_percent;
                    $user_finance->stock = $invitationID->wallet + $amount_percent;
                    $user_finance->save();

                    $user_invitation = new \App\UserInvitation;
                    $user_invitation->id_user = $user->invitationID;
                    $user_invitation->id_invitation_user = $user->id;
                    $user_invitation->amount = $amount_percent;
                    $user_invitation->id_order = $order->id;
                    $user_invitation->save();

                    DB::commit();
                } catch (\Exception $e) {
                    DB::rollback();
                    $result = array('status' => false, 'message' => 'عملیات دچار مشکل شد');
                }
            endif;
        }
    }


    public function get_order_detail($id_order)
    {
        $order = Orders::select('id', 'orders_model', 'type')->where('id', $id_order)->first();
        $result = (object)array();
        if ($order->orders_model == 'PSVouchers') {
            $result->title = 'پی اس ووچرز';
            $result->dollar = ' دلار ووچرز';
        } elseif ($order->orders_model == 'perfectmoney'){
            $result->title = 'پرفکت مانی';
            $result->dollar = ' دلار پرفکت مانی';
        }
        elseif ($order->orders_model == 'PMvoucher'){
            $result->title = 'ووچر پرفکت مانی';
            $result->dollar = ' دلار پرفکت مانی';
        }elseif($order->orders_model == 'paypal'){
            $result->title = 'پی پل';
            $result->dollar = ' دلار پی پل';
        }elseif($order->orders_model == 'skrill'){
            $result->title = 'اسکریل';
            $result->dollar = ' دلار اسکریل';
        }elseif($order->orders_model == 'webmoney'){
            $result->title = 'وب مانی';
            $result->dollar = ' دلار وب مانی';
        }

        if($order->type == 'sell')
            $result->type = 'فروش';
        elseif($order->type == 'buy')
            $result->type = 'خرید';
        elseif($order->type == 'buy-product')
            $result->type = 'خرید با ';

        if (!isset($result->title))
            $Cryptocurrency = \App\Cryptocurrency::where('name',$order->orders_model)->first();

        if(isset($Cryptocurrency)){
            $result->title = $Cryptocurrency->name_fa;
            $result->dollar = $Cryptocurrency->symbol;

            $orders_model = DB::table('orders_cryptocurrency')->where('id_order',$order->id)->first();
            $amount_dollar = isset($orders_model->amount_coin) ? $orders_model->amount_coin : '';
            $result->amount_dollar =  $amount_dollar;
        }else{
            $orders_model = DB::table('orders_'.strtolower($order->orders_model))->where('id_order',$order->id)->first();
            $amount_dollar = isset($orders_model->amount_dollar) ? $orders_model->amount_dollar : '';
            $result->amount_dollar =  $amount_dollar;
        }


        if ($result->type=='خرید' && ($result->title=='پرفکت مانی' | $result->title=='وب مانی' | $result->title=='اسکریل' | $result->title=='پی پل'))
            $result->type = 'شارژ حساب';
        if($order->orders_model == 'webmoney' && isset($orders_model->paymer_code))
            $result->title = 'پیمر وب مانی';

        return $result;
    }


    public function send_notification($title, $message, $singleID , $data = array() ) {

        if(count($data)==0)
            $data = array('id_user' => 1);

        if (!defined('API_ACCESS_KEY'))
            define('API_ACCESS_KEY', env('FirebaseToken'));

        $fcmFields = array(
            //'registration_ids' => $registrationIDs,
            'to' => $singleID,
            //'priority' => 'high',
            "data" => $data,
            "notification" => array('click_action' => asset(''),
                'title' => $title,
                'body' => $message,
                'icon' => asset('')."app-assets/images/icon.png",
            )
        );

        $headers = array(
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fcmFields));
        $res = curl_exec($ch);
        curl_close( $ch );
        return json_decode($res);
    }


    public function KavehnegarSendTokens($mobile , $token = [] , $template = null ) {

        if(count($token) == 1)
            $url='https://api.kavenegar.com/v1/'.getSetting('KavehnegarKey').'/verify/lookup.json?receptor='.$mobile.'&token='.$token[0].'&template='.$template;
        elseif(count($token) == 2)
            $url='https://api.kavenegar.com/v1/'.getSetting('KavehnegarKey').'/verify/lookup.json?receptor='.$mobile.'&token='.$token[0].'&token2='.$token[1].'&template='.$template;
        elseif(count($token) == 3)
            $url='https://api.kavenegar.com/v1/'.getSetting('KavehnegarKey').'/verify/lookup.json?receptor='.$mobile.'&token='.$token[0].'&token2='.$token[1].'&token3='.$token[2].'&template='.$template;

        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
        //curl_setopt($ch,CURLOPT_POSTFIELDS);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $res = curl_exec($ch);
        $res = json_decode($res);
        $res = $res->return;
        return $res;
    }


    public function CheckBeforeBuy($amount,$buy_method = 0,$id_user = null,$model = null , $dollar = null){
        $id_user = isset(Auth::user()->id) ? Auth::user()->id : $id_user;
        $user = \App\User::find($id_user);

        if($buy_method == 0 && ($user->auth_img_confirm != 1 || $user->selfie_img_confirm != 1) ){
            $result = (object)array('status' => false, 'message' => 'برای خرید لازم است اطلاعات شما تکمیل گردد');
            return $result;
        }

        $disable_buy = getSetting($model.'_buy_status');
        if ($disable_buy=='false') {
            $result = (object)array('status' => false, 'message' => 'خرید این ارز موقتا غیر فعال است.');
            return $result;
        }

        if($buy_method==0 && \App\CardBank::where('id_user',$id_user)->where('confirm',1)->count() <= 0){
            $result = (object)array('status' => false, 'message' => 'هنوز کارت بانکی تایید شده ای جهت پرداخت ندارید!');
            return $result;
        }

        $disable_buy_message = getSetting('disable_buy_message');
        if ($disable_buy_message!='') {
            $result = (object)array('status' => false, 'message' => $disable_buy_message);
            return $result;
        }

        if ($amount > 50000000 && $buy_method == 0) {
            $result = (object)array('status' => false, 'message' => "با توجه به محدودیت درگاه بانکی حداکثر مبلغ قابل پرداخت 50,000,000 تومان است.");
            return $result;
        }


        $sum_order_buy = Orders::where('id_user', $user->id)->where('created_at', '>', date('Y-m-d'))
            ->where('created_at', '<', date('Y-m-d',strtotime("+1 days")))
            ->whereIn('type', ['buy','buy-product'])->whereIn('status',['پرداخت شده','در دست اقدام','در حال پردازش','در حال بررسی پرداخت','در حال انتقال ارز'])->sum('amount');
        $orderDay = \App\Orders::where('id_user', Auth::user()->id)->where('created_at', '>', date('Y-m-d'))
            ->where('created_at', '<', date('Y-m-d',strtotime("+1 days")))
            ->whereIn('type', ['buy','buy-product'])->whereIn('status',['پرداخت شده','در حال بررسی پرداخت','در دست اقدام','در حال پردازش'])->get();

        $functions = new functions;
        foreach ($orderDay as $order){
            $detail = $functions->get_order_detail($order->id);
            if (!$detail->amount_dollar){
                $sum_order_buy = $sum_order_buy - $order->amount;
            }
        }
        if ($sum_order_buy+$amount > $user->daily_buy) {
            $result = (object)array('status' => false, 'message' => "مبلغ مورد نیاز از جمع خرید های امروز شما بیشتر است!");
            return $result;
        }

        $min_buy = getSetting('min_buy');
        if ($amount < $min_buy) {
            $result = (object)array('status' => false, 'message' => "حداقل مجاز مبلغ خرید " . number_format($min_buy) . " تومان میباشد");
            return $result;
        }

        if ($buy_method == 1 && $amount > $user->wallet) {
            $result = (object)array('status' => false, 'message' => 'مبلغ قابل پرداخت از موجودی شما بیشتر است');
            return $result;
        }


        $cryptocurrency = \App\Cryptocurrency::all()->pluck('name')->toArray();
        if(in_array($model,$cryptocurrency)){
            $crypto = \App\Cryptocurrency::where('name',$model)->first();
            $Controller = 'App\Http\Controllers\User\CryptoController';
            $balances =  app($Controller)->balances();
            foreach ($balances as $balance){
                if($balance->symbol == $crypto->symbol){
                    $stock = $balance->stock;
                    break;
                }
            }

            if($stock < $dollar){
                $result = (object)array('status' => false, 'message' => 'موجودی '.$crypto->name.' '. env('APP_NAME_FARSI') .' کمتر از درخواست شما میباشد.<br> موجودی: '.$stock.$crypto->symbol);
                return $result;
            }

        }else{
            $Controller = str_replace(' ','','App\Http\Controllers\User\ '. ucfirst($model) .'Controller');
            $stock =  (int)app($Controller)->balances();
            if($stock < $dollar){
                $result = (object)array('status' => false, 'message' => 'موجودی این ارز در '. env('APP_NAME_FARSI') .' کمتر از درخواست شما میباشد.<br> موجودی: '.$stock);
                return $result;
            }
        }

        $result = (object)array('status' => true, 'message' => "");
        return $result;

    }


//    function postToZibal($path, $parameters)
//    {
//        $url = 'https://gateway.zibal.ir/'.$path;
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//        curl_setopt($ch, CURLOPT_POST, 1);
//        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($parameters));
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        $response  = curl_exec($ch);
//        curl_close($ch);
//        return json_decode($response);
//    }


    function Curl($url,$params =[], $authorization = null,$method = 'POST'){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);

        $headers = array(
            'Accept: application/json',
            'charset: utf-8',
            'Content-Type: application/json',
            $authorization
        );

        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, 4);
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($params));
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        $response = (object) json_decode( curl_exec($ch) );
        $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $response->statusCodeHttp = $httpcode??404;
        //array_push($response,$httpcode);
        curl_close($ch);

        //dd($response);
        return $response;
    }


    function SaveOrder($request,$OrderModel,$Type){
        if ((!isset($request->amount) && $Type=='buy') ||  (!isset($request->price) && $Type=='buy-product')) {
            $result = array('status' => false, 'message' => "مقادیر نا معتبر است!");
            return $result;
        }

        $Controller = str_replace(' ','','App\Http\Controllers\User\ '. ucfirst($OrderModel) .'Controller');
        $fee =  app($Controller)->price()->buy;

        if($Type=='buy'){
            $amount = str_replace(',', '', $request->amount);
            $dollar = $amount / $fee;
        }
        else{
            $dollar = (float)$request->price;
            $amount = $dollar * $fee;
        }


        $CheckBeforeBuy = $this->CheckBeforeBuy($amount,$request->buy_method,null,$OrderModel,$dollar);
        if($CheckBeforeBuy->status == false)
            return $CheckBeforeBuy;

        $order = new Orders;
        $order->id_user = Auth::user()->id;
        $order->amount = $amount;
        $order->description = $request->description;
        $order->type = $Type;
        $order->orders_model = $OrderModel;
        if ($request->buy_method == 1)
            $order->wallet = $amount;
        $order->ip = $request->ip();
        $order->via = $request->via ?? 'website';
        $order->save();

        $result = (object)array('status' => true, 'message' => "", 'id' => $order->id);
        return $result;
    }


    public function infoCoin($coin,$type){
        $result = (object)array();
        $cryptocurrency = \App\Cryptocurrency::all()->pluck('name')->toArray();
        if(in_array($coin,$cryptocurrency)){
            $crypto = \App\Cryptocurrency::where('name',$coin)->first();
            $Controller = 'App\Http\Controllers\User\CryptoController';
            $balances =  app($Controller)->balances();
            foreach ($balances as $balance){
                if($balance->symbol == $crypto->symbol){
                    $stock = $balance->stock;
                    break;
                }
            }
            $result->balances = $stock;

            $fees = app($Controller)->price([$crypto->symbol]);
            foreach ($fees->coins as $fee){
                if($crypto->symbol == $fee->symbol){
                    $result->fee = $fee->{$type};
                    break;
                }
            }

            $result->buy_order_fee = getSetting('buy_order_fee', 0)->value;
            $result->sell_order_fee = getSetting('sell_order_fee', 0)->value;

            $result->transfer_fee_amount = app($Controller)->withdrawFee($crypto->symbol,$coin);

        }else{
            $Controller = str_replace(' ','','App\Http\Controllers\User\ '. ucfirst($coin) .'Controller');
            $result->fee = app($Controller)->price()->{$type};
            $result->balances = (int)app($Controller)->balances();
        }
        $result->message =  '';

        return $result;
    }


    public function SetSession($name,$value){
        $SessionApi = \App\SessionApi::where(['name'=>$name,'id_user'=>Auth::user()->id])->orderBy('id','desc')->first();
        if($SessionApi){
            $SessionApi->delete();
        }
        $SessionApi = new \App\SessionApi;
        $SessionApi->name = $name;
        $SessionApi->value =  $value;
        $SessionApi->id_user = Auth::user()->id;
        $SessionApi->save();
        return true;
    }
    public function GetSession($name){
        $SessionApi = \App\SessionApi::where(['name'=>$name,'id_user'=>Auth::user()->id])->orderBy('id','desc')->first();
        return isset($SessionApi) ? $SessionApi->value : null;
    }


    public function LogAdmin($text,$model,$id_user = null){
        $log = new \App\AdminLog;
        $log->id_admin = $id_user ?? Auth::user()->id;
        $log->text = $text;
        $log->model = $model;
        $log->save();
    }



    public function FinotechSendMoney($id_card,$amount,$id_user,$id_order = null,$id_finance= null, $CardModel = null){
        $result = array('status' => false, 'message' => 'واریز اتوماتیک از تنظیمات غیر فعال است');
        return (object)$result;
    }


    function GetTokenFinotech(){
        return false;

        $authorization = "Authorization: Basic ".env('FinotechKey');
        $url = 'https://apibeta.finnotech.ir/dev/v2/oauth2/token';
        $param = array(
            "grant_type"=> "client_credentials",
            "nid"=> env('FinotechCodemeli'),
            "scopes"=> "card:information:get,facility:card-to-iban:get,oak:iban-inquiry:get"
        );
        $path = '../../heydari.co/storage/Finotcech.json';
        //$path = 'storage/Finotcech.json';
        if (file_exists($path)){
            $responce = json_decode( file_get_contents($path) );
            if($responce->date > date('Y-m-d H:i:s',strtotime('- 9 day'))){
                return $responce->result->value;
            }else{
                $responce = self::Curl($url,$param,$authorization,'POST');
                if ($responce->statusCodeHttp == 200 && $responce->status =='DONE') {
                    $responce->date = date('Y-m-d H:i:s');
                    file_put_contents($path, json_encode($responce) );
                    return $responce->result->value;
                }
            }
        }else{

            $responce = self::Curl($url,$param,$authorization,'POST');
            if ($responce->statusCodeHttp == 200 && $responce->status =='DONE') {
                $responce->date = date('Y-m-d H:i:s');
                file_put_contents($path, json_encode($responce) );
                return $responce->result->value;
            }
        }

        //$token = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbklkIjoiMzgyY2E4ZTQtOTgyZC00NzlkLThhYTQtZWJjNzdjMDIzMTA3IiwicmVmcmVzaFRva2VuIjoiWlRNalM0Y0I0THhlc3NEeWxzaWFNNVJVUzh6NVl5Wm9jWFE4Tm5xQU9kblhyVFdHSXRvMkFmcklPcXFPd1JLUnY3MndqcW5QOFp4eFNodVRPSlJadmhwRVZOVWlQNjVPb3E0ajlya1J5TTFiUWg2aXU4TThMd0hUSVN5RWkzdFZXZjl0SUVKQlJJU3dVbWJGM0hvY0hRbGxIbkdJamNMR1NWbk1DbFhnYm9mZjJRZ2NXOUIyYkViNXlrenFBOEpBbFBtdnBrV2hBYzZUV2dDMVAwaUQ0a2ZaN0FMNWtwWTc2VTI2cGpnQXJFaHVTZDE5b1dtQ3lvTnUyQnB5TFpRRCIsImNyZWF0aW9uRGF0ZSI6IjEzOTgxMTIwMTM0MzQzIiwibGlmZVRpbWUiOjg2NDAwMDAwMCwiY2xpZW50SWQiOiJleG9ueXgiLCJ1c2VySWQiOiIyOTAwMzQzNTc3IiwiYWN0aXZlIjp0cnVlLCJzY29wZXMiOlsiY2FyZDppbmZvcm1hdGlvbjpnZXQiLCJmYWNpbGl0eTpjYXJkLXRvLWliYW46Z2V0Il0sInR5cGUiOiJDTElFTlQtQ1JFREVOVElBTCIsImJhbmsiOiIwNjIiLCJpYXQiOjE1ODEyNDMyMjMsImV4cCI6MTU4MjEwNzIyM30.dkyfDRKUZ_cRKnDtXSe_RswlZVMHPs8b8VO1RboW8mrCt057v_Gnfy6qGSOLNfDBf0gDr66ErI82I2MfyFtOVCJOaNLdbk0_9JJ-oAga06rhfxnsV_C8IEhu3MOklyBmIEB_e5jYiDAXA1T2b0u0cgiTDLR3IfHBHv23V48-U2F6HxrJrWQLeVQgKmCjSbjU_ZZe2LB3EZE85QLuJg5SyBbx0oWj4Pa0cq7c_K7VvIDCZqRkxUmtiT9cjl1o6N8omMk4xNEs4bix-jLdUs94t6zOqTxe1kMz-5JgUT2PUrClFPA0RDnOs03WP7BcYEp4MufeMSOhpevUJOvPjc6o-w";
        //return $token;
    }


    function SaveCardOther($request, $id_order){
        $OtherBank = new \App\OrdersCardBank;
        $OtherBank->id_order = $id_order;
        $OtherBank->account_owner = $request->other_cardnameFamily;
        $OtherBank->bank_name = $request->other_cardnameBank;
        $OtherBank->card_number = $request->other_cardnumber;
        $OtherBank->account_number = $request->other_accuntNumber;
        $OtherBank->shaba = $request->other_iban;
        if(!$OtherBank->save()){
            $result = array('status' => false, 'message' => "ذخیره حساب دیگران انجام نشد!");
        }else{
            $result = array('status' => true, 'message' => "ok",'id'=>$OtherBank->id);
        }
        return (object)$result;
    }

    function CheckBeforeSell($model){
        $disable_buy = getSetting($model.'_sell_status');
        if ($disable_buy=='false') {
            $result = (object)array('status' => false, 'message' => 'فروش این ارز به ما موقتا غیر فعال است.');
            return $result;
        }

        $result = (object)array('status' => true, 'message' => "");
        return $result;
    }

}
