<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Models\Creditout;
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 CreditoutController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $accounts = Creditout::where('userid', Auth::user()->id)->get();

        return view('admin.creditout.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('creditout')
                ->join('users', 'creditout.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'creditout.*')
                ->get();
        } elseif ($checkadmin == false && Auth::user()->affiliate == '1') {
            $accounts = DB::table('creditout')
                ->join('users', 'creditout.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'creditout.*')
                ->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('creditout')
                ->join('users', 'creditout.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'creditout.*')
                ->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('creditout')
                ->join('users', 'creditout.userid', '=', 'users.id')
                ->select('users.name', 'users.email', 'creditout.*')
                ->whereIn('users.id', $finalids)
                ->get();
        } else {
            abort(403);
        }

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

    /**
     * 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.creditout.create', compact('accounts', 'countries'));
    }

    /**
     * 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['userid'] = Auth::user()->id;
        $adduser['amount'] = $data['amount'];
        $adduser['description'] = $data['description'];

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

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

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

    public function storecreditout(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 = 'creditout';

        //  $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=CreditOut';
        $postdata1 = array();
        $postdata1['LOGIN'] = $request->mt4account;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $amountw;
        $postdata1['COMMENT'] = 'creditout';
        $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['userid'] = $checkde->userid;
            $adduser['amount'] = $data['amount'];
            $adduser['description'] = $data['description'];
            $adduser['status'] = '1';

            $product = Creditout::create($adduser);
        }
        return redirect()->route('admin.creditoutlist')->with('success', 'CreditOut successfully');
    }

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