<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Models\Internaltransfer;
use App\Models\Mtaccount;
use App\Models\Product;
use App\Models\User;
use App\Models\Withdraw;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;

class WithdrawController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $accounts = Withdraw::where('userid', Auth::user()->id)->get();

        return view('admin.withdraw.index', compact('accounts'));
    }

    public function adminindex()
    {
        // abort_unless(\Gate::allows('product_access'), 403);
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            $accounts = DB::table('withdraw')
                ->join('users', 'withdraw.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'withdraw.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = DB::table('withdraw')
                ->join('users', 'withdraw.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'withdraw.*')
                ->where('users.afid', Auth::user()->id)
                ->get();
        } 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);
            $accounts = DB::table('withdraw')
                ->join('users', 'withdraw.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'withdraw.*')
                ->whereIn('users.id', $finalids)
                ->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);
            $accounts = DB::table('withdraw')
                ->join('users', 'withdraw.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'withdraw.*')
                ->whereIn('users.id', $finalids)
                ->get();
        } else {
            abort(403);
        }


        return view('admin.withdraw.adminindex', compact('accounts'));
    }

    public function editwithdraw($id)
    {
        // abort_unless(\Gate::allows('product_access'), 403);
        $cid = $id;

        return view('admin.withdraw.approve', compact('cid'));
    }

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

        $docdata = Withdraw::where('id', $request->id)->first();
        $comment = 'withdraw';
        //$url = $this->apicall.'MAKE_WITHDRAW_BALANCE?MT4Account='.$docdata->mt4account.'&Amount='.$docdata->amount.'&Comment='.$comment.'&ManagerIndex='.$this->manager;

        //   dd($docdata);
        $amountw = '-' . $docdata->amount;
        //   $url = 'https://api.qubixtrader.com/api-v2/api.php?mode=deposit_operation&name=AFF005&pass=pXzp8047yZzo&login='.$docdata->mt4account.'&amount='.$amountw.'&comment=withdraw';

        $urlw = 'http://api.tradeactive.com/mt5api3/api/api.php?MODE=Withdraw';
        $postdata1 = array();
        $postdata1['LOGIN'] = $docdata->mt4account;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $amountw;
        $postdata1['COMMENT'] = 'withdraw';
        $postdata1['CHECK_MARGIN'] = '1';
        $option = array(
            'Content-Type:application/json'
        );
        $ch1 = curl_init(str_replace(' ', '', $urlw));
        curl_setopt($ch1, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch1, CURLOPT_POST, true); // Specify the request method as POST
        curl_setopt($ch1, CURLOPT_POSTFIELDS, json_encode($postdata1));
        $getallw1 = curl_exec($ch1);
        curl_close($ch1);
        $getuserdata1 = json_decode($getallw1);
        if ($getuserdata1->status == 'success') {

            //	if($getresult->status == true){
            Withdraw::where('id', $request->id)->update(array(
                'description'     => $request->description,
                'status'     => $request->status,
            ));
        }
        return redirect('admin/withdrawlist');
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $accounts = Mtaccount::where('userid', Auth::user()->id)->get();
        $countries = DB::table('countries')->get();
        return view('admin.withdraw.create', compact('accounts', 'countries'));
    }

    public function internaltransfer()
    {
        // abort_unless(\Gate::allows('product_create'), 403);
        $accounts = Internaltransfer::where('userid', Auth::user()->id)->get();
        return view('admin.withdraw.transferlist', compact('accounts'));
    }

    public function createtransfer()
    {
        // abort_unless(\Gate::allows('product_create'), 403);
        $accounts = Mtaccount::where('userid', Auth::user()->id)->get();
        return view('admin.withdraw.transfer', compact('accounts'));
    }

    public function storetransfer(Request $request)
    {
        //	$this->makeconnection();
        $validator = Validator::make($request->all(), [
            'fromaccount' => 'required',
            'toaccount' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }

        if ($request->fromaccount == $request->toaccount) {
            return redirect()->back()->withErrors(['transfer not allowed in same account.']);
        }
        //$url = $this->apicall.'GET_ACCOUNT_INFO?Account='.$request->fromaccount.'&ManagerIndex='.$this->manager;
        $postfields3 = array(
            'method' => 'GetUserByLogin',
            'key' => '0001',
            'array' =>
            array(
                0 =>
                array(
                    'index' => 0,
                    'accountID' => $request->fromaccount
                ),
            ),
        );
        $curl3 = curl_init();
        curl_setopt_array($curl3, 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($postfields3),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: text/plain"
            ),
        ));
        $response3 = curl_exec($curl3);
        curl_close($curl3);
        $getresult3 = json_decode($response3);
        $ubalnc = $getresult3->array[0]->pltAccount->balance;
        if ($request->amount > $ubalnc) {
            return redirect()->back()->withErrors(['not enough balance.']);
            return redirect()->back();
        } else {

            $commentw = 'transfer to ' . $request->toaccount;
            $commentd = 'transfer from ' . $request->fromaccount;
            $comntd = str_replace(' ', '-', $commentd);

            // $urlw = $this->apicall.'MAKE_WITHDRAW_BALANCE?MT4Account='.$request->fromaccount.'&Amount='.$request->amount.'&Comment='.$comntd.'&ManagerIndex='.$this->manager;

            $amountw = '-' . $request->amount;
            $postfields = array(
                'method' => 'Deposit',
                'key' => '0001',
                'array' =>
                array(
                    0 =>
                    array(
                        'index' => 0,
                        'accountID' => $request->fromaccount,
                        'comment' => $commentw,
                        'amount' => $amountw,
                    ),
                ),
            );
            $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 == '') {

                // $urld = $this->apicall.'MAKE_DEPOIST_BALANCE?MT4Account='.$request->toaccount.'&Amount='.$request->amount.'&Comment='.$comntd.'&ManagerIndex='.$this->manager;
                $postfields2 = array(
                    'method' => 'Deposit',
                    'key' => '0001',
                    'array' =>
                    array(
                        0 =>
                        array(
                            'index' => 0,
                            'accountID' => $request->toaccount,
                            'comment' => $comntd,
                            'amount' => $request->amount,
                        ),
                    ),
                );
                $curl2 = curl_init();
                curl_setopt_array($curl2, 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($postfields2),
                    CURLOPT_HTTPHEADER => array(
                        "Content-Type: text/plain"
                    ),
                ));
                $response2 = curl_exec($curl2);
                curl_close($curl2);
                $getresult2 = json_decode($response2);

                if ($getresult2->systemErrorStatus == '') {
                    $adduser = array();
                    $adduser['fromaccount'] = $request->fromaccount;
                    $adduser['toaccount'] = $request->toaccount;
                    $adduser['userid'] = Auth::user()->id;
                    $adduser['amount'] = $request->amount;
                    $adduser['notes'] = $request->description;

                    Internaltransfer::create($adduser);

                    return redirect()->back()->with('success', 'Your transfer done successfully');
                }
            }
        }
    }

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $postfields3 = array(
            'method' => 'GetUserByLogin',
            'key' => '0001',
            'array' =>
            array(
                0 =>
                array(
                    'index' => 0,
                    'accountID' => $request->mt4account
                ),
            ),
        );
        $curl3 = curl_init();
        curl_setopt_array($curl3, 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($postfields3),
            CURLOPT_HTTPHEADER => array(
                "Content-Type: text/plain"
            ),
        ));
        $response3 = curl_exec($curl3);
        curl_close($curl3);
        $getresult3 = json_decode($response3);
        $ubalnc = $getresult3->array[0]->pltAccount->balance;
        if ($request->amount > $ubalnc) {
            return redirect()->back()->withErrors(['not enough balance.']);
        }
        return redirect()->back();

        $data = $request->all();
        $adduser = array();
        $adduser['mt4account'] = $data['mt4account'];
        $adduser['benename'] = $data['benename'];
        $adduser['country'] = $data['country'];
        $adduser['bankname'] = $data['bankname'];
        $adduser['bankaddress'] = $data['bankaddress'];
        $adduser['bankaccount'] = $data['accountno'];
        $adduser['swiftcode'] = $data['swiftcode'];
        $adduser['userid'] = Auth::user()->id;
        $adduser['amount'] = $data['amount'];
        $adduser['clientnote'] = $data['description'];

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

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

    public function manualwithdraw()
    {
        $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');
        if ($checkadmin == true) {
            // $accounts = Mtaccount::get();
            $accounts = DB::table('mtaccount')
                ->join('users', 'mtaccount.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'mtaccount.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = DB::table('mtaccount')
                ->join('users', 'mtaccount.userid', '=', 'users.id')
                ->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);
            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(600);
            } 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(600);
            }
        } else {
            abort(403);
        }

        return view('admin.withdraw.manual', compact('accounts'));
    }

    public function storemanualwithdraw(Request $request)
    {
        //$this->makeconnection();
        // $url = $this->apicall.'GET_ACCOUNT_INFO?Account='.$request->mt4account.'&ManagerIndex='.$this->manager; $request->mt4account
        $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
        $postdata = array();
        $postdata['LOGIN'] = $request->mt4account;
        $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);
        curl_close($ch);
        $getuserdata = json_decode($getallw);
        if (!isset($getuserdata->response->Balance)) {
            return redirect()->back()->withErrors(['account not found.']);
        }

        $getuserdata2 = $getuserdata->response->Balance;
        if ($request->amount > $getuserdata2) {
            return redirect()->back()->withErrors(['not enough balance.']);
        }
        // return redirect()->back();
        $checkde = Mtaccount::where('loginid', $request->mt4account)->first();
        $getcountry = User::where('id', $checkde->userid)->first();
        $comnt = 'manual-withdraw';

        //  $url2 = $this->apicall.'MAKE_WITHDRAW_BALANCE?MT4Account='.$request->mt4account.'&Amount='.$request->amount.'&Comment='.$comnt.'&ManagerIndex='.$this->manager;

        $amountw = '-' . $request->amount;

        $urlw = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=Withdraw';
        $postdata1 = array();
        $postdata1['LOGIN'] = $request->mt4account;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $amountw;
        $postdata1['COMMENT'] = 'manual-withdraw';
        $postdata1['CHECK_MARGIN'] = '1';
        $option = array(
            'Content-Type:application/json'
        );
        $ch1 = curl_init(str_replace(' ', '', $urlw));
        curl_setopt($ch1, CURLOPT_HTTPHEADER, $option);
        curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch1, CURLOPT_POST, true); // Specify the request method as POST
        curl_setopt($ch1, CURLOPT_POSTFIELDS, json_encode($postdata1));
        $getallw1 = curl_exec($ch1);
        curl_close($ch1);
        $getuserdata1 = json_decode($getallw1);
        // echo '<pre>';print_r($getuserdata1);exit;
        if ($getuserdata1->status == 'success') {

            $data = $request->all();
            $adduser = array();
            $adduser['mt4account'] = $data['mt4account'];
            $adduser['benename'] = '--';
            $adduser['country'] = $getcountry->country;
            $adduser['bankname'] = '--';
            $adduser['bankaddress'] = '--';
            $adduser['bankaccount'] = '--';
            $adduser['swiftcode'] = '--';
            $adduser['userid'] = $checkde->userid;
            $adduser['amount'] = $data['amount'];
            $adduser['clientnote'] = '-';
            $adduser['description'] = $data['description'];
            $adduser['status'] = '1';

            $product = Withdraw::create($adduser);
        }
        return redirect()->route('admin.withdrawlist');
    }

    /**
     * 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)
    {
        return view('admin.products.edit', compact('product'));
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateProductRequest $request, Product $product)
    {
        $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);
    }
}
