<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Models\Deposit;
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;

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

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

    public function getcode()
    {
        $accounts = Mtaccount::get();
        $allacc = array();
        foreach ($accounts as $key => $mta) {
            $allacc[$key]['index'] = $key;
            $allacc[$key]['accountID'] = $mta->loginid;
        }
        //dd($allacc);
        $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);
        dd($getresult->array);
        if ($getresult->systemErrorStatus == '') {
            $getresult->array[0]->accountID;
        }
    }

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

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

    public function editdeposit($id){
        $cid = $id;

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

    public function depositapproved(Request $request){

        $docdata = Deposit::where('id', $request->id)->first();
        $comment = 'deposit';

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

        $urlw = 'http://api.tradeactive.com/mt5api3/api/api.php?MODE=Deposit';
        $postdata1 = array();
        $postdata1['LOGIN'] = $docdata->mt4account;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $amountw;
        $postdata1['COMMENT'] = 'deposit';
        $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);
        curl_setopt($ch1, CURLOPT_POSTFIELDS, json_encode($postdata1));
        $getallw1 = curl_exec($ch1);
        curl_close($ch1);
        $getresult = json_decode($getallw1);
        echo '<pre>';print_r($getresult);exit;
        if ($getresult->status == 'success') {
          Deposit::where('id', $request->id)->update(array(
            'description'     => $request->description,
            'status'     => $request->status,
          ));
        }
        return redirect('admin/depositlist');
    }

    public function manualdeposit()
    {
        $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.deposit.manual', compact('accounts'));
    }

    public function storemanual(Request $request)
    {
        //$this->makeconnection();
        // abort_unless(\Gate::allows('product_create'), 403);
        $checkde = Mtaccount::where('loginid', $request->mt4account)->first();
        $comnt = 'deposit';

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


        $urlw = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=Deposit';
        $postdata1 = array();
        $postdata1['LOGIN'] = $request->mt4account;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $request->amount;
        $postdata1['COMMENT'] = 'manual-deposit';
        $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') {
            $data = $request->all();
            $adduser = array();
            $adduser['mt4account'] = $data['mt4account'];
            $adduser['userid'] = $checkde->userid;
            $adduser['amount'] = $data['amount'];
            $adduser['clientnote'] = '-';
            $adduser['description'] = $data['description'];
            $adduser['status'] = '1';
            $adduser['displaystatus'] = '1';
            $adduser['method'] = 'manual-deposit';

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $data = $request->all();
        $adduser = array();
        $adduser['mt4account'] = $data['mt4account'];
        $adduser['userid'] = Auth::user()->id;
        $adduser['amount'] = $data['amount'];
        $adduser['clientnote'] = $data['description'];
        $adduser['displaystatus'] = '0';
        $adduser['method'] = $data['paymentmethod'];
        $product = Deposit::create($adduser);

        if ($data['paymentmethod'] == 'global') {
            $userdetail = array();
            $userdetail['first_name'] = Auth::user()->name;
            $userdetail['last_name'] = Auth::user()->name;
            $userdetail['email'] = Auth::user()->email;
            $userdetail['currency'] = 'EUR';
            $userdetail['country_code'] = '+44';
            $userdetail['phone'] = Auth::user()->mobile;
            $userdetail['gender'] = 'male';
            $userdetail['city'] = 'London';
            $userdetail['birth'] = '21/08/1980';
            $userdetail['country'] = 'GB';
            $userdetail['address'] = 'address';
            $userdetail['trader']['callback_url'] = "https://crm.finanza-invest.com/dopayment";
            $userdetail['trader']['label'] = 'finanza';
            $userdetail['trader']['amount'] = $data['amount'];
            $userdetail['trader']['depoid'] = $product->id;
            $userdetail['trader']['custom2'] = 'payment';
            /*
                $userdetail['password'] = 'Abc1234@1';
                $userdetail['password_confirmation'] = 'Abc1234@1';
                $userdetail['phone'] = 'Abc1234@1';
                $userdetail['conditions']['terms_agree'] = true;
                $userdetail['conditions']['privacy_policy'] = true;
                $userdetail['conditions']['age_check'] = true;
            */

            $getd = json_encode($userdetail);

            $url = 'https://allglobalpay.com/api/register';
            //  $url = 'https://allglobalpay.com/en/referral_form';
            $ch = curl_init($url);
            # Setup request to send json via POST.

            curl_setopt($ch, CURLOPT_POSTFIELDS,  $getd);
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
            # Return response instead of printing.
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            # Send request.
            $result = curl_exec($ch);
            curl_close($ch);
            $getresult = json_decode($result, true);

            if ($getresult['success'] == '1') {
                return redirect($getresult['redirect_url']);
            } else {
                return redirect()->route('admin.deposit.index');
            }
        }
        if ($data['paymentmethod'] == 'bitlocus') {

            $percntage = $data['amount'] * 0.06;
            $finalamount = $data['amount'] + $percntage;
            //  https://app.staging.bitlocus.com/checkout/deposit?accountuuid=7e04f103-263f-420c-8819-70596b54be2e&orderid=IFS007&methods=VISA&amount=15&currency=EUR&redirecturl=https%3A%2F%2Fwww.google.com
            $redirct = 'https://app.bitlocus.com/checkout/deposit?accountuuid=05d3ed84-3d04-4046-9985-67d86debeb6e&orderid=' . $product->id . '&methods=VISA&amount=' . $finalamount . '&currency=EUR&redirecturl=https%3A%2F%2Fcrm.empirecfd.com%2Fadmin%2Fdeposit';
            return redirect($redirct);
        }
    }

    /**
     * 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);
    }
}
