<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Mail\AccountDetailsMail;
use App\Models\Leverage;
use App\Models\Mtaccount;
use App\Models\Product;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Concerns\FromArray;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Facades\Excel;

class MtaccountController extends Controller
{
    public function messages()
    {
        return [
            'newpassword.required' => 'password required',
        ];
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $checkadmin = Gate::allows('permission_create');
        $mt4ids = array();
        $getuserdata = array();
        $accounts = DB::table('users')
            ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
            ->select('users.name', 'users.email', 'mtaccount.*')
            ->where('userid', Auth::user()->id)
            ->get();
        $allacc = array();
        foreach ($accounts as $key => $mta) {
            $allacc[$key]['index'] = $key;
            $allacc[$key]['accountID'] = $mta->loginid;
        }
        $getuserdata = array();
        if (count($accounts) > 0) {
            $postfields = array(
                'method' => 'GetUserByLogin',
                'key' => '0001',
                'array' => $allacc
            );
            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => "http://jenya.securedns.us:3001/capitalmanageinv",
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => "POST",
                CURLOPT_POSTFIELDS => json_encode($postfields),
                CURLOPT_HTTPHEADER => array(
                    "Content-Type: text/plain"
                ),
            ));
            $response = curl_exec($curl);
            curl_close($curl);
            $getresult = json_decode($response);
            $getuserdata = $getresult->array;
        }
        //	dd($getuserdata);
        return view('admin.mtaccount.index', compact('accounts', 'checkadmin', 'getuserdata'));
    }

    public function adminindex(Request $request)
    {
        $mt5id = '';
        $email  = '';
        $parts = parse_url($_SERVER['REQUEST_URI']);
        if (!empty($parts['query'])) {
            parse_str($parts['query'], $query);
            if (isset($query['mt5id'])) {
                $mt5id = $query['mt5id'];
            }
            if (isset($query['email'])) {
                $email = $query['email'];
            }
        } else {
            $mt5id = '';
            $email = '';
        }

        $checkadmin = Gate::allows('permission_create');
        $mt4ids = array();
        $getuserdata = array();
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            if (!empty($mt5id)) {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->where('mtaccount.loginid', 'like', '%' . $mt5id . '%')
                    ->orderBy('id', 'DESC')->paginate(10);
            } elseif (!empty($email)) {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->where('users.email', 'like', '%' . $email . '%')
                    ->orderBy('id', 'DESC')->paginate(10);
            } else {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->orderBy('id', 'DESC')->paginate(10);
            // echo '<pre>';print_r($accounts);exit;
            }
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            if (!empty($mt5id)) {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->where('users.afid', Auth::user()->id)
                    ->where('mtaccount.loginid', 'like', '%' . $mt5id . '%')
                    ->orderBy('id', 'DESC')->paginate(10);
            } else {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->where('users.afid', Auth::user()->id)
                    ->orderBy('id', 'DESC')->paginate(10);
            }
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1' && Auth::user()->issubadmin == '1') {
            $getafids = User::select('id')->where('afid', Auth::user()->id)->pluck('id')->toArray();
            $getallids = User::select('id')->whereIn('afid', $getafids)->pluck('id')->toArray();
            $finalids = array_merge($getafids, $getallids);
            if (!empty($mt5id)) {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->whereIn('users.id', $finalids)
                    ->where('mtaccount.loginid', 'like', '%' . $mt5id . '%')
                    ->orderBy('id', 'DESC')->paginate(10);
            } else {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->whereIn('users.id', $finalids)
                    ->orderBy('id', 'DESC')->paginate(10);
            }
        } elseif ($checkadmin == false && Auth::user()->issubadmin == '1') {
            $getafids = User::select('id')->where('afid', Auth::user()->id)->pluck('id')->toArray();
            $getallids = User::select('id')->whereIn('afid', $getafids)->pluck('id')->toArray();
            $finalids = array_merge($getafids, $getallids);
            if (!empty($mt5id)) {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->whereIn('users.id', $finalids)
                    ->where('mtaccount.loginid', 'like', '%' . $mt5id . '%')
                    ->orderBy('id', 'DESC')->paginate(10);
            } else {
                $accounts = DB::table('users')
                    ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                    ->select('users.name', 'users.email', 'mtaccount.*')
                    ->whereIn('users.id', $finalids)
                    ->orderBy('id', 'DESC')->paginate(10);
            }
        } else {
            abort(403);
        }

        //dd($getuserdata);
        return view('admin.mtaccount.index', compact('accounts', 'checkadmin', 'getuserdata', 'mt5id', 'email'));
    }

    public function infomt4account(Request $request)
    {
        //dd("We will back soon");
        //$this->makeconnection();

        $checkadmin = Gate::allows('permission_create');
        $mt4ids = array();
        $getuserdata = array();
        $allacc = array();

        $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
        $postdata = array();
        $postdata['LOGIN'] = $request->id;
        $option = array(
            'Content-Type:application/json'
        );

        $ch = curl_init(str_replace(' ', '', $url));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
        $getallw = curl_exec($ch);
        $getuserdata = json_decode($getallw);
        //  dd($getuserdata->response->Balance);
        // echo '<pre>';print_r($getuserdata);exit;

        $getuserdata2 = $getuserdata->response->Balance;
        return $getuserdata2;

        //return view('admin.mtaccount.index', compact('accounts','checkadmin','getuserdata'));
    }

    public function demoaccounts()
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            $accounts = DB::table('users')
                ->join('demoaccount', 'users.id', '=', 'demoaccount.userid')
                ->select('users.name', 'users.email', 'demoaccount.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = DB::table('users')
                ->join('demoaccount', 'users.id', '=', 'demoaccount.userid')
                ->select('users.name', 'users.email', 'demoaccount.*')
                ->where('users.afid', Auth::user()->id)
                ->get();
        } else {
            $accounts = DB::table('users')
                ->join('demoaccount', 'users.id', '=', 'demoaccount.userid')
                ->select('users.name', 'users.email', 'demoaccount.*')
                ->where('userid', Auth::user()->id)
                ->get();
        }
        return view('admin.mtaccount.demoindex', compact('accounts', 'checkadmin'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        abort_unless(Gate::allows('user_client'), 403);

        return view('admin.mtaccount.create');
    }

    public function leverage()
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {

            $accounts = DB::table('leverage')
                ->join('users', 'leverage.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'leverage.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = DB::table('leverage')
                ->join('users', 'leverage.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'leverage.*')
                ->where('users.afid', Auth::user()->id)
                ->get();
        } else {
            $accounts = DB::table('leverage')
                ->join('users', 'leverage.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'leverage.*')
                ->where('leverage.userid', Auth::user()->id)
                ->get();
        }

        return view('admin.mtaccount.leverageindex', compact('accounts', 'checkadmin'));
    }

    public function leveragerequest()
    {
        abort_unless(Gate::allows('user_client'), 403);
        $accounts = Mtaccount::where('userid', Auth::user()->id)->get();
        return view('admin.mtaccount.leveragecreate', compact('accounts'));
    }
    public function leverageapprove($id)
    {
        abort_unless(Gate::allows('permission_create'), 403);
        $accounts = Mtaccount::where('userid', Auth::user()->id)->get();
        return view('admin.mtaccount.leverageapprove', compact('accounts', 'id'));
    }
    public function leverageapprovestore(Request $request)
    {
        abort_unless(Gate::allows('permission_create'), 403);

        // $this->makeconnection();

        $docdata = Leverage::where('id', $request->id)->first();
        if ($request->status == '1') {
            $url = $this->apicall . 'CHANGE_LEVERAGE?MT4Account=' . $docdata->mtaccount . '&Leverage=' . $docdata->leverage . '&ManagerIndex=' . $this->manager;

            $userdetail['LOGIN'] = $docdata->mtaccount;
            $userdetail['LEVERAGE'] = $docdata->leverage;
            $userdetail['AGENT'] = '';
            $apiurl = 'http://api.tradeactive.com/mt5api3/api/api.php?MODE=UpdateUser';

            //  dd($url);
            $option = array(
                'Content-Type:application/json'
            );

            $ch = curl_init($apiurl);
            curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userdetail));
            $result = curl_exec($ch);
            $getresult = json_decode($result);
            curl_close($ch);
        }
        Leverage::where('id', $request->id)->update(array(
            'status'     => $request->status,
        ));
        return redirect('admin/leverage');
    }
    public function storeleverage(Request $request)
    {
        abort_unless(Gate::allows('user_client'), 403);
        $data = $request->all();
        $adduser = array();


        $adduser['mtaccount'] = $request->mtaccount;
        $adduser['leverage'] = $request->leverage;
        $adduser['userid'] = Auth::user()->id;

        $product = Leverage::create($adduser);

        return redirect()->route('admin.leverage');
    }

    public function opendemoaccount()
    {
        abort_unless(Gate::allows('user_client'), 403);

        return view('admin.mtaccount.createdemo');
    }

    public function admincreate()
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            $accounts = User::where('affiliate', '0')->where('id', '!=', Auth::user()->id)->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = User::where('affiliate', '0')->where('afid', Auth::user()->id)->get();
        } else {
            abort(403);
        }
        return view('admin.mtaccount.createadmin', compact('accounts'));
    }

    public function changemt4password()
    {
        //abort_unless(\Gate::allows('user_client'), 403);
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            // $myaccounts = Mtaccount::get();
            $myaccounts = DB::table('users')
                ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                ->select('users.name', 'users.email', 'mtaccount.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $myaccounts = DB::table('users')
                ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                ->select('users.name', 'users.email', 'mtaccount.*')
                ->where('users.afid', Auth::user()->id)
                ->get();
        } elseif ($checkadmin == false && Auth::user()->issubadmin == '1') {
            $getafids = User::select('id')->where('afid', Auth::user()->id)->pluck('id')->toArray();
            $getallids = User::select('id')->whereIn('afid', $getafids)->pluck('id')->toArray();
            $finalids = array_merge($getafids, $getallids);
            $myaccounts = DB::table('users')
                ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
                ->select('users.name', 'users.email', 'mtaccount.*')
                ->whereIn('users.id', $finalids)
                ->get();
        } else {
            $myaccounts = Mtaccount::where('userid', Auth::user()->id)->get();
        }

        return view('admin.mtaccount.changepass', compact('myaccounts'));
    }

    public function storemt4pass(Request $request)
    {
        //	$this->makeconnection();
        $validator = Validator::make($request->all(), [
            'newpassword' => 'required|string|min:8|regex:/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{6,}$/'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        $data = $request->all();

        //  $url = $this->apicall.'CHANGE_MASTER_PASSWORD?MT4Account='.$request->mt4account.'&password='.$request->newpassword.'&ManagerIndex='.$this->manager;
        //dd($url);
        $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=ChangePassword';
        $postdata = array();
        $postdata['LOGIN'] = $request->mt4account;
        $postdata['TYPE'] = 'MAIN';
        $postdata['Password'] = $request->newpassword;
        $option = array(
            'Content-Type:application/json'
        );

        $ch = curl_init(str_replace(' ', '', $url));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true); // Specify the request method as POST
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
        $getallw = curl_exec($ch);
        $getuserdata = json_decode($getallw);
        // echo '<pre>';print_r($getallw);exit;
        if ($getuserdata->status == 'success') {
            $adduser = array();
            Mtaccount::where('loginid', $request->mt4account)->update(array(
                'mainpass'     => $request->newpassword,
            ));
            return redirect()->route('admin.mt4accounts')->with('success', 'Your mt5 account password changed successfully.');
        } else {
            return redirect()->back();
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        abort_unless(Gate::allows('user_client'), 403);
        $data = $request->all();
        $adduser = array();
        $fourRandomDigit = mt_rand(1000, 9999);
        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $uniqpass = substr(str_shuffle($str_result), 0, 8);

        //$url = $this->apicall.'ADD_USER';

        $userval = User::find(Auth::user()->id);


        $ibcode = 0;
        //  dd($ibcode);
        $userdetail = array();

        $userdetail['First'] = Auth::user()->name;
        $userdetail['Last'] = '';
        $userdetail['ProfilePic'] = Auth::user()->name;
        $userdetail['Comment'] = 'New Account';
        $userdetail['EmailID'] = Auth::user()->email;
        $userdetail['Phone'] = Auth::user()->mobile;
        $userdetail['Website_URL'] = '';
        $userdetail['Email_Verify'] = 0;
        $userdetail['Phone_Verify'] = 0;
        $userdetail['Address1'] = "";
        $userdetail['Address2'] = "";
        $userdetail['City'] = "";
        $userdetail['State'] = "";
        $userdetail['Country'] = Auth::user()->country;
        $userdetail['ZipCode'] = "";
        $userdetail['GroupName'] = $request->groupname;
        $userdetail['Leverage'] = $request->leverage;
        $userdetail['Agent_Code'] = $ibcode;
        //  $userdetail['ManagerIndex'] = $this->manager;

        $datap1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcefghijklmnopqrstuvwxyz';
        $datap2 = '1234567890abcefghijklmnopqrstuvwxyz';
        $mainpass = substr(str_shuffle($datap1), 0, 8);
        $invepass = substr(str_shuffle($datap2), 0, 8);

        $postfields = array(
            'method' => 'AddUser',
            'key' => '0001',
            'array' =>
            array(
                0 =>
                array(
                    'index' => 0,
                    'agentAccount' => 0,
                    'canTrade' => true,
                    'comment' => 'new user',
                    'group' =>
                    array(
                        'name' => $data['groupname']
                    ),
                    'hasSendReportEnabled' => true,
                    'isEnabled' => true,
                    'leverage' => $data['leverage'],
                    'password' => $mainpass,
                    'investorPassword' => $invepass,
                    'enable_change_password' => true,

                    'user' =>
                    array(
                        'address' =>
                        array(
                            "address" => "",
                            "city" => "",
                            "state" => "",
                            "zipcode" => "",
                            "country" => Auth::user()->country,
                        ),
                        "name" => Auth::user()->name,
                        "email" => Auth::user()->email,
                        "phone" => Auth::user()->mobile
                    ),

                ),

            ),
        );
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://jenya.securedns.us:3001/capitalmanageinv",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($postfields),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: text/plain"
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $getresult = json_decode($response);
        // echo '<pre>';print_r($getresult);exit;

        if ($getresult->systemErrorStatus == '') {

            $adduser['userid'] = Auth::user()->id;
            $adduser['loginid'] = $getresult->array[0]->accountID;
            $adduser['mainpass'] = $mainpass;
            $adduser['leverage'] = $data['leverage'];
            $adduser['groupname'] = $data['groupname'];

            $product = Mtaccount::create($adduser);
        }
        return redirect()->route('admin.mtaccount.index');
    }

    public function random_password($lower, $upper, $digits, $special_characters)
    {
        $lower_case = "abcdefghijklmnopqrstuvwxyz";
        $upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $numbers = "1234567890";
        $symbols = "!@#$%^&*";

        $lower_case = str_shuffle($lower_case);
        $upper_case = str_shuffle($upper_case);
        $numbers = str_shuffle($numbers);
        $symbols = str_shuffle($symbols);

        $random_password = substr($lower_case, 0, $lower);
        $random_password .= substr($upper_case, 0, $upper);
        $random_password .= substr($numbers, 0, $digits);
        $random_password .= substr($symbols, 0, $special_characters);

        return  str_shuffle($random_password);
    }

    public function storedmin(Request $request)
    {
        //$this->makeconnection();

        //abort_unless(\Gate::allows('user_client'), 403);
        $data = $request->all();
        $adduser = array();
        $fourRandomDigit = mt_rand(1000, 9999);
        $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        $uniqpass = substr(str_shuffle($str_result), 0, 8);

        $userval = User::find($request->userid);

        $ibcode = 0;
        //  dd($ibcode);

        $datap1 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcefghijklmnopqrstuvwxyz';
        $datap2 = '1234567890abcefghijklmnopqrstuvwxyz';
        $mainpass = $this->random_password(2, 2, 3, 2);
        $invepass = $this->random_password(2, 2, 3, 2);
        //dd($userval->country);
        if (empty($userval->country)) {
            $country = 'IT';
        } else {
            $country = $userval->country;
        }
        $url = 'https://api.qubixtrader.com/api-v2/api.php?mode=mt4_create&name=AFF005&pass=pXzp8047yZzo&uname=' . trim($userval->name) . '&lname=lname&group=' . $request->groupname . '&pwd=' . rand() . '&email=' . $userval->email . '&country=' . $country . '&phone=' . $userval->mobile;

        $userdetail = array();
        $userdetail['LOGIN'] = '';
        $userdetail['PASS_MAIN'] = $mainpass;
        $userdetail['PASS_INVESTOR'] = $invepass;
        $userdetail['RIGHTS'] = 3;
        $userdetail['GROUP'] = 'real\\real';
        $userdetail['NAME'] = $userval->name;
        $userdetail['COMPANY'] = '';
        $userdetail['LANGUAGE'] = '';
        $userdetail['COUNTRY'] = $country;
        $userdetail['CITY'] = '';
        $userdetail['STATE'] = '';
        $userdetail['ZIPCODE'] = '';
        $userdetail['ADDRESS'] = '';
        $userdetail['PHONE'] = $userval->mobile;
        $userdetail['EMAIL'] = $userval->email;
        $userdetail['COMMENT'] = '';
        $userdetail['PASS_PHONE'] = '';
        $userdetail['LEVERAGE'] = $request->leverage;
        $userdetail['AGENT'] = '';
        $apiurl = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=AddUser';

        $option = array(
            'Content-Type: application/json'
        );

        $ch = curl_init($apiurl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userdetail));
        $result = curl_exec($ch);
        $getresult = json_decode($result);
        curl_close($ch);
        // echo '<pre>';print_r($result);exit;
        if ($getresult->status !== '') {
            $adduser['userid'] = $userval->id;
            $adduser['loginid'] = $getresult->login;
            $adduser['mainpass'] = $mainpass;
            $adduser['leverage'] = $data['leverage'];
            $adduser['groupname'] = 'real\\real';

            $product = Mtaccount::create($adduser);

            Mail::to($userval->email)->send(new AccountDetailsMail($userval, $mainpass, $getresult->login));
        }
        return redirect()->route('admin.mt4accounts',compact('product'));
    }

    public function clientopen(Request $request)
    {
        abort_unless(Gate::allows('user_management_access'), 403);

        $accounts = Mtaccount::all();
        $loginIds = $accounts->pluck('loginid')->toArray();

        $mtaccount = $request->account && in_array($request->account, $loginIds) ? $request->account : null;

        $userdetail = [
            'LOGIN' => $mtaccount ? [$mtaccount] : $loginIds,
        ];

        $apiurl = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=GetPosition';

        $option = [
            'Content-Type: application/json'
        ];

        // Initialize CURL request
        $ch = curl_init($apiurl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userdetail));
        $result = curl_exec($ch);
        curl_close($ch);

        $getresult = json_decode($result);

        $positions = $getresult && $getresult->status == 'success' ? $getresult->response : [];

        if ($request->ajax()) {
            return response()->json(['positions' => $positions]);
        }

        return view('admin.mtaccount.clientopen', compact('accounts', 'positions', 'mtaccount'));
    }

    public function closetrades(Request $request)
    {
        //$this->makeconnection();
        abort_unless(Gate::allows('user_management_access'), 403);
        $accounts = Mtaccount::all();
        $allid = array();
        if (count($accounts) > 0) {
            foreach ($accounts as $mtid) {
                $allid[] = $mtid->loginid;
            }
        }
        if ($request->account != null && in_array($request->account, $allid)) {
            $mtaccount = $request->account;
        } else {
            $accountdata = Mtaccount::all();
            $mtaccount = $accountdata;
        }
        $from = '2020-06-01 00:00:00';
        $to = date('Y-m-d 23:59:59');

        $ch = curl_init();
        $fromdate1 = strtotime($from);
        $fromdate2 = strtotime($to);

        // echo "<pre>";print_r($fromdate2);exit;

        $userdetail = array();
        $userdetail['LOGIN'] = $mtaccount;
        $userdetail['FROM'] = $fromdate1;
        $userdetail['TO'] = $fromdate2;

        $apiurl = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=GetClosedOrders';
        $option = array(
            'Content-Type:application/json'
        );

        $ch = curl_init($apiurl);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($userdetail));
        $result = curl_exec($ch);
        $getresult = json_decode($result);
        // echo "<pre>";print_r($result);exit;

        if ($getresult->status == 'success') {
            $positions = $getresult->response;
        } else {
            $positions = array();
        }

        return view('admin.mtaccount.clientclose', compact('accounts', 'positions', 'mtaccount'));
    }

    public function crmopen(Request $request)
    {
        //$this->makeconnection();
        abort_unless(Gate::allows('user_management_access'), 403);
        $accounts = Mtaccount::get();
        $allmt = array();
        foreach ($accounts as $mt4) {
            $allmt[] = $mt4->loginid;
        }
        $parts = parse_url($_SERVER['REQUEST_URI']);
        if (!empty($parts['query'])) {
            parse_str($parts['query'], $query);
            $getaccpara = $query['account'];
        } else {
            $getaccpara = null;
        }
        if ($getaccpara != null && in_array($getaccpara, $allmt)) {
            $mtaccount = $getaccpara;
        } else {
            $accountdata = Mtaccount::first();
            $mtaccount = $accountdata->loginid;
        }
        //$url = $this->apicall.'GET_OPENED_BY_USER?Account='.$mtaccount.'&ManagerIndex='.$this->manager;
        // dd($mtaccount);
        $postfields = array(
            'method' => 'GetUserOpenTrades',
            'key' => '0001',
            'accountID' => $mtaccount
        );
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://jenya.securedns.us:3001/capitalmanageinv",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => json_encode($postfields),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: text/plain"
            ),
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $getresult = json_decode($response);
        if ($getresult->systemErrorStatus == '' && $getresult->arraySize > 0) {
            $positions = $getresult->array;
        } else {
            $positions = array();
        }

        return view('admin.mtaccount.crmopen', compact('accounts', 'positions', 'mtaccount'));
    }

    /**
     * Display the specified resource.
     */
    public function show(Product $product)
    {
        abort_unless(Gate::allows('product_show'), 403);

        return view('admin.products.show', compact('product'));
    }

    /**
     * Show the form for editing the specified resource.
     */

     public function edit(Product $product)
     {
         //  abort_unless(\Gate::allows('product_edit'), 403);

         return view('admin.products.edit', compact('product'));
     }

     public function update(UpdateProductRequest $request, Product $product)
     {
         // abort_unless(\Gate::allows('product_edit'), 403);

         $product->update($request->all());

         return redirect()->route('admin.products.index');
     }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Product $product)
    {
        abort_unless(Gate::allows('product_delete'), 403);

        $product->delete();

        return back();
    }

    public function massDestroy(MassDestroyProductRequest $request)
    {
        Product::whereIn('id', request('ids'))->delete();

        return response(null, 204);
    }

    public function updatemtbl(Request $request)
    {
        $accounts = Mtaccount::get();
        foreach ($accounts as $account) {
                /* $url = 'https://api.qubixtrader.com/api-v2/api.php?mode=mt4_details&name=AFF005&pass=pXzp8047yZzo&s='.$account->loginid;
        		$ch = curl_init(trim($url));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$getallw = curl_exec($ch);
			    curl_close($ch);
				$getresult = json_decode($getallw); */
            $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
            $postdata = array();
            $postdata['LOGIN'] = $account->loginid;
            $option = array(
                'Content-Type:application/json'
            );

            $ch = curl_init(str_replace(' ', '', $url));
            curl_setopt($ch, CURLOPT_HTTPHEADER, $option);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true); // Specify the request method as POST
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postdata));
            $getallw = curl_exec($ch);
            $getuserdata = json_decode($getallw);
            //  dd($getuserdata->response->Balance);


            // $getuserdata2 = $getuserdata->response->Balance;
            if (isset($getuserdata->response->Balance)) {
                Mtaccount::where('loginid', $account->loginid)->update(array(
                    'balance'     => $getuserdata->response->Balance,
                ));
            }
        }
        dd("done");
    }

    public function exportMt5account()
    {
        $mtaccountData = Mtaccount::join('users', 'mtaccount.userid', '=', 'users.id')
        ->select('users.name as client_name', 'users.email', 'mtaccount.*')
        ->get();

        return Excel::download(new class($mtaccountData) implements FromArray, WithHeadings {
            private $mtaccountData;

            public function __construct($mtaccountData)
            {
                $this->mtaccountData = $mtaccountData;
            }

            public function array(): array
            {
                return $this->mtaccountData->map(function ($mtaccount) {
                    return [
                        $mtaccount->loginid,
                        $mtaccount->client_name,
                        $mtaccount->email,
                        $mtaccount->mainpass,
                        $mtaccount->groupname,
                        $mtaccount->leverage,
                    ];
                })->toArray();
            }

            public function headings(): array
            {
                return [
                    'Login ID', 'Client Name', 'Email', 'Password', 'Group Name', 'Leverage',
                ];
            }
        }, 'Mt5accounts.xlsx');
    }
}
