<?php

namespace App\Http\Controllers\Admin;

use App\Settings;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Morilog\Jalali;
use DB;
use Auth;
use App\Orders;
use App\functions;
use SoulDoit\DataTable\SSP;

class OrdersController extends Controller
{
    public function __construct()
    {
        $this->middleware(function ($request, $next) {
            if(Auth::user()->access_orders ==1 || Auth::user()->role == 'admin')
                return $next($request);
            else
                abort(404);
        });
    }

    public function index()
    {
        return view('admin.orders');
    }

    public function list_orders(Request $request)
    {
        if(strpos($request->search['value'],"#") !== false){
            $request->id = str_replace('#','',$request->search['value']);
            $request->merge(['search' => array('value'=>$request->id,'regex'=>$request->search['regex']) ]);
        }

        $functions = new functions;
        if (isset($request->date_start)) {
            $request->date_start = $functions->toLatin($request->date_start);
            $request->date_start = Jalali\CalendarUtils::createCarbonFromFormat('Y/m/d H:i', $request->date_start);
        }

        if (isset($request->date_stop)) {
            $request->date_stop = $functions->toLatin($request->date_stop);
            $request->date_stop = Jalali\CalendarUtils::createCarbonFromFormat('Y/m/d H:i', $request->date_stop);
        }

        $dt = [
            ['label' => 'NameFamily', 'db' => 'users.family', 'dt' => 11],
            ['label' => 'Mobile', 'db' => 'users.mobile', 'dt' => 23],

            ['label' => 'ID', 'db' => 'orders.id', 'dt' => 0],
            ['label' => 'Name', 'db' => 'users.name', 'dt' => 1],
            ['label' => 'Image', 'db' => 'orders_model', 'dt' => 2, 'formatter' => function ($value, $model) {
                return '<img src="' . asset('') . 'app-assets/images/currency/' . $value . '.svg" width="30px">';
            }],
            ['label' => 'Model', 'db' => 'orders.id', 'dt' => 3, 'formatter' => function ($value, $model) {
                $functions = new functions;
                $detail = $functions->get_order_detail($value);
                return "<a href='".asset('') .env('PanelPrefix'). '/orders/' . $value."'>".$detail->type . ' ' . $detail->title.'</a>';
            }],
            ['label' => 'AmountModel', 'db' => 'orders.id', 'dt' => 4, 'formatter' => function ($value, $model) {
                $functions = new functions;
                $detail = $functions->get_order_detail($value);
                $Amount = $detail->amount_dollar ? $detail->amount_dollar : '';
                $Amount .= $detail->amount_dollar ? $detail->dollar : '-----';
                return $Amount;
            }],
            ['label' => 'Date', 'db' => 'orders.created_at', 'dt' => 5, 'formatter' => function ($value, $model) {
                return Jalali\CalendarUtils::strftime('d F Y - H:i', strtotime($value));
            }],
            ['label' => 'Status', 'db' => 'status', 'dt' => 6, 'formatter' => function ($value, $model) {
                if ($value == 'معلق')
                    return '<span class="badge badge-pill bg-dark font-weight-light">معلق</span>';
                elseif ($value == 'پرداخت شده') {
                    $functions = new functions;
                    $detail = $functions->get_order_detail($model->id);
                    if ($detail->amount_dollar)
                        return '<span class="badge badge-pill bg-success font-weight-light">' . $value . '</span>';
                    else {
                        return '<span class="badge badge-pill bg-success font-weight-light">' . $value . '</span>
                                     <span class="badge badge-pill bg-danger font-weight-light">ناموفق</span>';
                    }
                } elseif ($value == 'انجام شده')
                    return '<span class="badge badge-pill bg-success font-weight-light">انجام شده</span>';
                elseif ($value == 'منتقل شده')
                    return '<span class="badge badge-pill bg-success font-weight-light">منتقل شده</span>';
                elseif ($value == 'در دست اقدام')
                    return '<span class="badge badge-pill bg-info font-weight-light">در دست اقدام</span>';
                elseif ($value == 'در حال پردازش')
                    return '<span class="badge badge-pill bg-warning font-weight-light">در حال پردازش</span>';
                elseif ($value == 'در حال بررسی پرداخت')
                    return '<span class="badge badge-pill bg-warning font-weight-light">در حال بررسی پرداخت</span>';
                elseif ($value == 'در حال انتقال ارز')
                    return '<span class="badge badge-pill bg-success font-weight-light">پرداخت شده</span>
                            <span class="badge badge-pill bg-warning font-weight-light">در حال انتقال ارز</span>';
                elseif ($value == 'رد شده')
                    return '<span class="badge badge-pill bg-danger font-weight-light">رد شده</span>';
                elseif ($value == 'معلق,پرداخت شده')
                    return '<span class="badge badge-pill bg-dark font-weight-light">معلق</span>
                            <span class="badge badge-pill bg-success font-weight-light">پرداخت شده</span>';
                elseif ($value == 'نا موفق,پرداخت شده')
                    return '<span class="badge badge-pill bg-success font-weight-light">پرداخت شد</span>
                            <span class="badge badge-pill bg-danger font-weight-light">نا موفق</span>';
                elseif ($value == 'معلق,عودت')
                    return '<span class="badge badge-pill bg-dark font-weight-light">معلق</span>
                            <span class="badge badge-pill bg-success font-weight-light">عودت</span>';
            }],
            ['label' => 'Amount', 'db' => 'amount', 'dt' => 7, 'formatter' => function ($value, $model) {
                return number_format($value);
            }],
            ['label' => 'Detail', 'db' => 'orders.id', 'dt' => 8, 'formatter' => function ($value, $model) {
                $link =  '<a href="' . asset('') .env('PanelPrefix'). '/orders/' . $value . '"
                           class="btn btn-light btn-sm"> جزئیات</a>';
                return $link;
            }],


        ];
        $my_ssp = (new SSP('\App\Orders', $dt, 'table_name'))->where(function ($query) {

            if (isset(request()->id)) {
                $query->where('orders.id', request()->id);
            }


            if (isset(request()->currency)) {
                $query->where('orders_model', request()->currency);
            }

            if (isset(request()->admin)) {
                $query->where('id_admin', request()->admin);
            }

            if (isset(request()->model)) {
                if (request()->model == 'buy') {
                    $query->where('type', '!=', 'sell');
                } else
                    $query->where('type', 'sell');
            }

            if (isset(request()->date_start)) {
                $query->where('orders.created_at', '>', request()->date_start);
            }

            if (isset(request()->date_stop)) {
                $query->where('orders.created_at', '<', request()->date_stop);
            }

            if (isset(request()->status)) {
                $query->where('status', request()->status);
            }

            if (isset(request()->amount_start)) {
                $amount_start = str_replace(',', '', request()->amount_start);
                $query->where('amount', '>=', $amount_start);
            }

            if (isset(request()->amount_stop)) {
                $amount_stop = str_replace(',', '', request()->amount_stop);
                $query->where('amount', '<=', $amount_stop);
            }

            if (isset(request()->via)) {
                $query->where('via', request()->via);
            }

            if (isset(request()->bank_name) && request()->bank_name != '') {
                if (request()->bank_name == 'غیر ملت')
                    $query->where('users_cardbank.bank_name', '!=', 'بانک ملت');
                else
                    $query->where('users_cardbank.bank_name', request()->bank_name);
            }

        });

        if (isset(request()->bank_name) && request()->bank_name != '')
            $my_ssp->leftJoin('users_cardbank', 'orders.id_cardbank', 'users_cardbank.id');

        $my_ssp->leftJoin('users', 'orders.id_user', 'users.id');

        return response()->json($my_ssp->getDtArr());
    }

    function RemoveAllMoalagh()
    {

        $orders = Orders::where('status', 'معلق')->where('created_at', '<', date("Y-m-d H:i:s", strtotime('-15 minutes')))->delete();
        if ($orders)
            $result = array('status' => true, 'messege' => 'با موفقیت حذف شد');
        else
            $result = array('status' => false, 'messege' => 'موردی برای حذف وجود ندارد');

        return response()->json($result);
    }

    public function single(Request $request)
    {
        $order = \App\Orders::where('id', $request->id)->first();
        if ($order) {
            $result = (object)array();
            $functions = new functions;
            $order->detail = $functions->get_order_detail($order->id);
            $order->date = Jalali\CalendarUtils::strftime('d F Y ساعت H:i', strtotime($order->created_at));
            $order->update = Jalali\CalendarUtils::strftime('d F Y ساعت H:i', strtotime($order->updated_at));
            if (isset($order->id_cardbank)) {
                $order->cardbank = \App\CardBank::find($order->id_cardbank);
                $order->cardbank->card_number = app('App\Http\Controllers\User\ProfileController')->FormatCreditCard($order->cardbank->card_number);
            }
            if ($order->id_cardother){
                $order->cardother = \App\OrdersCardBank::find($order->id_cardother);
            }
            $result->order = $order;

            $user = User::find($order->id_user);
            $provinces = isset($user->id_province) ? \App\provinces::find($user->id_province)->title : '';
            $city = isset($user->id_city) ? \App\cities::find($user->id_city)->title : '';
            $user->address = isset($user->address) ? $provinces . ' - ' . $city . ' - ' . $user->address : '';
            $result->user = $user;


            $result->ticket = \App\Ticket::where('id_order', $order->id)->orderBy('updated_at', 'desc')->first();

            if($order->id_admin){
                $result->admin = \App\AdminUser::find($order->id_admin);
            }

            $cryptocurrency = \App\Cryptocurrency::all()->pluck('name')->toArray();
            $orders_model = $order->orders_model;
            if (in_array($orders_model, $cryptocurrency)){
                $result->orders_model = DB::table('orders_cryptocurrency')->where('id_order',$order->id)->first();
                $result->crypto =  DB::table('cryptocurrency')->where('name',$order->orders_model)->first();
            }
            else
                $result->orders_model = DB::table('orders_'.strtolower($order->orders_model))->where('id_order',$order->id)->first();

            $result->FinotechSendMoney = \App\FinotechSendMoney::where('id_order',$order->id)->first();

            if(isset($result->orders_model))
                if (in_array($orders_model, $cryptocurrency))
                    return view('admin.orders.single-cryptocurrency', ['result'=>$result]);
                else
                    return view('admin.orders.single-' . $order->orders_model, ['result'=>$result]);
            else{
                $result->BackStock = \App\UserFinance::where('id_user',$user->id)->where('id_order',$order->id)->where('type','واریز')->first();
                return view('admin.orders.single-error', ['result'=>$result]);
            }

        } else
            abort(404);
    }

    public function remove(Request $request)
    {
        $order = \App\Orders::where('id', $request->id)->where('status', 'معلق')->first();
        if ($order) {
            try {
                DB::table('orders_'.strtolower($order->orders_model))->where('id_order',$order->id)->delete();
                if ($order->delete())
                    $result = array('status' => true, 'messege' => 'با موفقیت حذف شد');

            } catch (\Illuminate\Database\QueryException $e) {
                $result = array('status' => false, 'messege' => 'حذف امکان پذیر نیست');
            }

        } else
            $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');
        return response()->json($result);
    }


    public function status(Request $request)
    {
        DB::beginTransaction();
        try {
            $order = \App\Orders::where('id', $request->id)->first();
            if ($order) {
                $functions = new \App\functions;

                $user = User::find($order->id_user);
                $order->status = $request->status;
                if ($request->status == 'پرداخت شده') {
                    $order->payment = str_replace(',', '', $request->payment);
                    if (!isset($order->id_cardbank) && !isset($order->id_cardother)) { // اگر درخواست به کیف پول داده بود
                        \App\User::find($user->id)->increment('wallet', $order->payment);
                        $user_finance = new \App\UserFinance;
                        $user_finance->type = 'واریز';
                        $user_finance->description = 'فروش ' . $order->orders_model;
                        $user_finance->id_user = $order->id_user;
                        $user_finance->amount = $order->payment;
                        $user_finance->stock = $user->wallet + $order->payment;
                        $user_finance->id_order = $order->id;
                        $user_finance->id_admin = Auth::user()->id;
                        $user_finance->save();
                        $result = array('status' => true, 'message' => 'با موفقیت تایید و به کیف پول کاربر اضافه شد');

                    } elseif(isset($order->id_cardbank)) { // اگر درخواست واریز به حساب خودش داده بود
                        if ($request->autoDeposit == 'true'): // اگر ادمین درخواست واریز اتوماتیک داشت
                            $sendMoney = $functions->FinotechSendMoney($order->id_cardbank,$order->payment,$user->id,$order->id);
                            if($sendMoney->status != true){
                                return response()->json($sendMoney);
                            }
                        endif;
                        $user = User::find($order->id_user);
                        $functions = new \App\functions;
                        try{\Kavenegar::VerifyLookup($user->mobile,number_format($order->amount),'وایز',null,'settle');}
                        catch (\Exception $ex){}
                        if (isset($user->firebase_token))
                            $functions->send_notification('واریز به حساب', $user->family . ' عزیز، مبلغ ' . $order->amount . ' به حساب شما واریز شد.', $user->firebase_token);
                        $result = array('status' => true, 'message' => 'با موفقیت تایید و پرداخت شد');


                    }
                    elseif(isset($order->id_cardother)) { // اگر درخواست واریز به حساب دیگران داده بود
                        if ($request->autoDeposit == 'true'): // اگر ادمین درخواست واریز اتوماتیک داشت
                            $sendMoney = $functions->FinotechSendMoney($order->id_cardother,$order->payment,$user->id,$order->id,null,'CardOther');
                            if($sendMoney->status != true){
                                return response()->json($sendMoney);
                            }
                        endif;
                        $user = User::find($order->id_user);
                        $functions = new \App\functions;
                        try{\Kavenegar::VerifyLookup($user->mobile,number_format($order->amount),'وایز',null,'settle');}
                        catch (\Exception $ex){}
                        if (isset($user->firebase_token))
                            $functions->send_notification('واریز به حساب', $user->family . ' عزیز، مبلغ ' . $order->amount . ' به حساب دیگران که معرفی کرده بودید واریز شد.', $user->firebase_token);
                        $result = array('status' => true, 'message' => 'با موفقیت تایید و پرداخت شد');

                    }

                } elseif ($request->status == 'رد شده')
                    $result = array('status' => true, 'message' => 'با موفقیت رد شد');
                elseif ($request->status == 'انجام شده' || $request->status == 'منتقل شده')
                    $result = array('status' => true, 'message' => 'با موفقیت تغییر کرد');
                $order->id_admin = Auth::user()->id;
                $order->save();

                //Save Log Admin
                if(!isset($order->id_cardbank))
                    $model = ' شارژ کیف پول ';
                elseif($request->autoDeposit == true)
                    $model = ' اتوماتیک ';
                else
                    $model = ' دستی ';
                $functions->LogAdmin('تایید سفارش '.$order->orders_model.' و واریز '.$model.' به حساب برای کاربر: '.$user->mobile,'orders');

                DB::commit();

            } else
                $result = array('status' => false, 'message' => 'خطا در ارسال پارامتر');

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

        return response()->json($result);
    }


    function insert_ticket(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'subject' => 'required',
            'unit' => 'required',
            'message' => 'required',
            'file' => 'nullable|mimes:jpg,jpeg,png,pdf,doc,,docx,,zip,rar|max:20500',
        ], [
            'subject.required' => 'موضوع را مشخص کنید',
            'unit.required' => 'واحد را انتخاب کنید',
            'message.required' => 'پیغام خود را درج کنید',
            'file.mimes' => 'فرمت فایل مناسب نیست',
            'file.max' => 'حداکثر مجاز حجم فایل 20 مگابایت است',
        ]);

        if ($validator->fails()) {
            $result = array('status' => false, 'message' => $validator->errors()->first());
            return response()->json($result);
        }

        $order = \App\Orders::where('id', $request->id)->first();
        if ($order):
            $user = User::find($order->id_user);

            DB::beginTransaction();
            try {
                $ticket = new \App\Ticket;
                $ticket->title = $request->subject;
                $ticket->unit = $request->unit;
                $ticket->id_order = $request->id;
                $ticket->id_user = $order->id_user;
                $ticket->status = 1;
                $ticket->seen_admin = 1;
                $ticket->save();

                $ticket_message = new \App\TicketMessage;
                $ticket_message->id_ticket = $ticket->id;
                $ticket_message->message = $request->message;
                $ticket_message->author = 'admin';
                $ticket_message->id_admin = Auth::user()->id;
                $ticket_message->save();

                if (isset($request->file)) {

                    //save image
                    $file = $request->file('file');
                    $extension = $file->getClientOriginalExtension();
                    $just_name = str_replace(" ", "-", pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME));
                    $just_name_hash = str_replace("/", "", bcrypt($just_name . time()));
                    $name = $just_name_hash . '.' . $extension;


                    $directory = 'uploads/Users/' . $user->created_at->year . '/' . $user->created_at->month . '/' . $user->id;
                    $file_path = $directory . '/Ticket/' . $name;
                    if (!file_exists(($file_path))) {
                        \File::makeDirectory($directory . '/Ticket/', $mode = 0777, true, true);
                        if ($request->file('file')->move($directory . '/Ticket/', $name)) {
                            $ticket_message->file_link = $directory . '/Ticket/' . $name;
                        }
                    } else {
                        if ($request->file('file')->move($directory . '/Ticket/', $just_name_hash . time() . '.' . $extension)) {
                            $ticket_message->file_link = $directory . '/Ticket/' . $just_name_hash . time() . '.' . $extension;
                        }
                    }
                    $ticket_message->save();
                }

                DB::commit();
                $result = array('status' => true, 'message' => 'تیکت شما با موفقیت ثبت شد', 'id' => $ticket->id);
                return response()->json($result);

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


    public function return_amount(Request $request)
    {
        $order = \App\Orders::where('id', $request->id)->first();
        if ($order) {

            $user = User::find($order->id_user);

            if ($request->status == 1)
                $order->status = 'معلق,عودت';

            if ($request->wallet == 1) {
                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 = $order->id_user;
                    $user_finance->amount = $order->amount;
                    $user_finance->stock = $user->wallet + $order->amount;
                    $user_finance->id_order = $order->id;
                    $user_finance->id_admin = Auth::user()->id;
                    $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, 'messege' => 'با موفقیت عودت و به کیف پول کاربر اضافه شد.');

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

            } else
                $result = array('status' => true, 'messege' => 'با موفقیت وضعیت به عودت تغییر یافت.');

            $order->save();

        } else
            $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');
        return response()->json($result);
    }


    public function hesab_format(Request $request)
    {
        $IDs = explode(',', $request->IDs);
        $orders = Orders::whereIn('id', $IDs)->whereNotNull('id_cardbank')->where('status', 'در حال پردازش')->orderBy('id', 'desc')->get();

        //echo '0000000002000000000400000'.'<br>';
        $sum = 0;
        $string = '';
        foreach ($orders as $order) {
            $user = User::select('mobile', 'name', 'family')->find($order->id_user);
            $CardBank = \App\CardBank::find($order->id_cardbank);

            $string .= str_pad($CardBank->account_number, 10, "0", STR_PAD_LEFT);
            $string .= str_pad($order->amount, 15, "0", STR_PAD_LEFT);
            $string .= str_pad($user->mobile, 17, "0", STR_PAD_LEFT);
            $string .= str_pad('', 30, " ", STR_PAD_LEFT);
            //$string .= str_pad($user->name.' '.$user->family, 30, " ", STR_PAD_LEFT);
            $string .= '<br>
';
            $sum += $order->amount;
        }

        $FristLine = str_pad(count($orders), 10, "0", STR_PAD_LEFT);
        $FristLine .= str_pad($sum, 15, "0", STR_PAD_LEFT);

        $date = Jalali\Jalalian::forge('now')->format('Ymd');

        echo "<div id='text'>" . $FristLine . '<br>
' . $string . "</div>";


        echo '
        <script>
        if (\'Blob\' in window) {
            var fileName = "ELFL' . $date . '";
            var text = document.getElementById("text").textContent;
            if (fileName) {
              var textFileAsBlob = new Blob([text], { type: \'text/plain\' });

              if (\'msSaveOrOpenBlob\' in navigator) {
                navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
              } else {
                var downloadLink = document.createElement(\'a\');
                downloadLink.download = fileName;
                downloadLink.innerHTML = \'Download File\';

                if (\'webkitURL\' in window) {
                  // Chrome allows the link to be clicked without actually adding it to the DOM.
                  downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
                } else {
                  // Firefox requires the link to be added to the DOM before it can be clicked.
                  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
                  downloadLink.click(function(){
                    document.body.removeChild(event.target);
                  });

                  downloadLink.style.display = \'none\';
                  document.body.appendChild(downloadLink);
                }
                downloadLink.click();
              }
            }
          } else {
            alert(\'Your browser does not support the HTML5 Blob Or auto create file and download.\');
          }
        </script>';

    }

    public function shba_format(Request $request)
    {
        $functions = new \App\functions;

        $IDs = explode(',', $request->IDs);
        $orders = Orders::whereIn('id', $IDs)->whereNotNull('id_cardbank')->where('status', 'در حال پردازش')->orderBy('id', 'desc')->get();

        //echo '0000000002000000000400000'.'<br>';
        $sum = 0;
        $string = '';
        foreach ($orders as $order) {
            $user = User::select('mobile', 'name', 'family', 'code_meli')->find($order->id_user);

            $CardBank = \App\CardBank::find($order->id_cardbank);

            $string .= 'IR' . $CardBank->shaba . ',';
            $string .= $user->mobile . ',';
            $string .= $order->amount . ',';
            $string .= $user->code_meli . ',';
            $string .= $user->name . ' ' . $user->family . ',';

            $detail = $functions->get_order_detail($order->id);
            $string .= $detail->type . ' ' . $detail->title;

            $string .= '<br>
';
        }

        $date = Jalali\Jalalian::forge('now')->format('Ymd');

        echo "<div id='text'>" . $string . "</div>";


        echo '
        <script>
        if (\'Blob\' in window) {
            var fileName = "ELFL' . $date . '";
            var text = document.getElementById("text").textContent;
            if (fileName) {
              var textFileAsBlob = new Blob([text], { type: \'text/plain\' });

              if (\'msSaveOrOpenBlob\' in navigator) {
                navigator.msSaveOrOpenBlob(textFileAsBlob, fileName);
              } else {
                var downloadLink = document.createElement(\'a\');
                downloadLink.download = fileName;
                downloadLink.innerHTML = \'Download File\';

                if (\'webkitURL\' in window) {
                  // Chrome allows the link to be clicked without actually adding it to the DOM.
                  downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
                } else {
                  // Firefox requires the link to be added to the DOM before it can be clicked.
                  downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
                  downloadLink.click(function(){
                    document.body.removeChild(event.target);
                  });

                  downloadLink.style.display = \'none\';
                  document.body.appendChild(downloadLink);
                }
                downloadLink.click();
              }
            }
          } else {
            alert(\'Your browser does not support the HTML5 Blob Or auto create file and download.\');
          }
        </script>';

    }

    /*
        protected function PSVouchersTransfer(Request $request)
        {
            $order = Orders::where('id', $request->id)->where('orders_model', 'PSVouchers')->where('status', 'در حال بررسی پرداخت')->first();
            $OrdersPSVouchers = \App\OrdersPSVouchers::where('id_order', $order->id)
                ->whereNull('vouchercode')->whereNull('TransactionID')->first();

            if (isset($request->amount_dollar) && isset($order) && isset($OrdersPSVouchers)) {

                $apikey = Settings::where('name', 'voucher_apikey')->first()['value'];
                $seckey = Settings::where('name', 'voucher_seckey')->first()['value'];

                $CreateVouchers = app('App\Http\Controllers\User\PSVouchersController')
                    ->CreateVouchers($apikey, $seckey, $request->amount_dollar, "USD", "1");
                $CreateVouchers = json_decode($CreateVouchers);
                //return response()->json($CreateVouchers);
                if (isset($CreateVouchers) && isset($CreateVouchers->Status) && $CreateVouchers->Status != 0) {

                    $OrdersPSVouchers->vouchercode = $CreateVouchers->Code;
                    $OrdersPSVouchers->TransactionID = $CreateVouchers->TransactionID;
                    $OrdersPSVouchers->amount_dollar = $request->amount_dollar;
                    $OrdersPSVouchers->amount_rial = str_replace(',','',$request->total_amount);
                    $OrdersPSVouchers->save();

                    $order->amount = str_replace(',','',$request->total_amount);
                    $order->status = 'پرداخت شده';
                    $order->save();
                    $this->SendSmsConfirmFish($order->id_user);
                    $result = array('status' => true, 'messege' => 'با موفقیت انجام شد');
                } else
                    $result = array('status' => false, 'messege' => 'خطا در صدا زدن api سایت ووچر');

            } else
                $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');

            return response()->json($result);
        }


        protected function PMVouchersTransfer(Request $request)
        {
            $order = Orders::where('id', $request->id)->where('status', 'در حال بررسی پرداخت')->where('orders_model', 'PMvoucher')->first();
            $OrdersPMVouchers = \App\OrdersPMVoucher::where('id_order', $order->id)
                ->whereNull('VOUCHER_NUM')->whereNull('VOUCHER_CODE')->first();

            if (isset($request->amount_dollar) && isset($order) && isset($OrdersPMVouchers)) {

                $AccountID = Settings::where('name', 'perfectmoney_AccountID')->first()['value'];
                $Password = Settings::where('name', 'perfectmoney_Password')->first()['value'];
                $Payer_Account = Settings::where('name', 'perfectmoney_Payer_Account')->first()['value'];
                $CreateVoucher = app('App\Http\Controllers\User\PMVoucherController')
                    ->CreateVoucher($AccountID, $Password, $Payer_Account, $request->amount_dollar);
                //echo response()->json($CreateVoucher);
                if ($CreateVoucher['status'] == 'success') {

                    $OrdersPMVouchers->Payer_Account = $CreateVoucher['data']['Payer_Account'];
                    $OrdersPMVouchers->VOUCHER_NUM = $CreateVoucher['data']['VOUCHER_NUM'];
                    $OrdersPMVouchers->VOUCHER_CODE = $CreateVoucher['data']['VOUCHER_CODE'];
                    $OrdersPMVouchers->amount_dollar = $request->amount_dollar;
                    $OrdersPMVouchers->amount_rial = str_replace(',','',$request->total_amount);
                    $OrdersPMVouchers->save();

                    $order->status = 'پرداخت شده';
                    $order->amount = str_replace(',','',$request->total_amount);
                    $order->save();
                    $this->SendSmsConfirmFish($order->id_user);
                    $result = array('status' => true, 'messege' => 'با موفقیت انجام شد');
                } else
                    $result = array('status' => false, 'messege' => 'خطا در صدا زدن api سایت پرفکت مانی');

            } else
                $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');

            return response()->json($result);
        }




        protected function PerfectMoneyTransfer(Request $request)
        {
            $order = Orders::where('id', $request->id)->where('status', 'در حال بررسی پرداخت')->where('type','buy-product')->where('orders_model', 'perfectmoney')->first();
            $Perfectmoney = \App\OrdersPerfectmoney::where('id_order', $order->id)->first();

            if (isset($request->amount_dollar) && isset($order) && isset($Perfectmoney)) {

                $AccountID = Settings::where('name', 'perfectmoney_AccountID')->first()['value'];
                $Password = Settings::where('name', 'perfectmoney_Password')->first()['value'];
                $Payer_Account = Settings::where('name', 'perfectmoney_Payer_Account')->first()['value'];
                $sendMoney = app('App\Http\Controllers\User\PerfectMoneyController')
                    ->sendMoney($AccountID, $Password, $Payer_Account, $Perfectmoney->Payee_Account, $request->amount_dollar, $Perfectmoney->descripion, $Perfectmoney->descripion);
                if ($sendMoney['status'] == 'success') {

                    $Perfectmoney->amount_dollar = $request->amount_dollar;
                    $Perfectmoney->amount_rial = str_replace(',','',$request->total_amount);

                    $order->status = 'پرداخت شده';
                    $order->amount = str_replace(',','',$request->total_amount);
                    $order->save();

                    $result = array('status' => true, 'messege' => 'با موفقیت انجام شد');
                    $this->SendSmsConfirmFish($order->id_user);
                } else
                    $result = array('status' => false, 'messege' => 'خطا در صدا زدن api سایت پرفکت مانی');

            } else
                $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');

            return response()->json($result);
        }




        protected function ConfirmPaymentFish(Request $request)
        {
            $order = Orders::where('id', $request->id)->where('status', 'در حال بررسی پرداخت')->where('type','buy')->first();
            $orders_model = DB::table('orders_'.strtolower($order->orders_model))->where('id_order',$order->id)->first();

            if (isset($request->amount_dollar) && isset($order) && isset($orders_model)) {

                DB::table('orders_'.strtolower($order->orders_model))->where('id_order',$order->id)
                    ->update([
                        'amount_dollar' => $request->amount_dollar,
                        'amount_rial' => str_replace(',','',$request->total_amount)
                    ]);

                $order->amount = str_replace(',','',$request->total_amount);
                $order->status = 'در دست اقدام';
                $order->save();
                $result = array('status' => true, 'messege' => 'با موفقیت انجام شد');
                $this->SendSmsConfirmFish($order->id_user);

            } else
                $result = array('status' => false, 'messege' => 'خطا در ارسال پارامتر');

            return response()->json($result);
        }


        private function SendSmsConfirmFish($id_user){
            $functions = new functions;
            $user = User::select('mobile')->find($id_user);
            $functions->KavehnegarSend($user->mobile,'.','ConfirmFish');
        }

        */

}
