<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Requests\MassDestroyUserRequest;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Mail\DocumentStatusMail;
use App\Mail\WelcomeMail;
use App\Models\Creditin;
use App\Models\Creditout;
use App\Models\Deposit;
use App\Models\Documents;
use App\Models\Leads;
use App\Models\Leverage;
use App\Models\Mtaccount;
use App\Models\Role;
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\File;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
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 UsersController extends Controller
{
    public function messages()
    {
        return [
            'currentpassword.required' => 'current password required',
        ];
    }

    /**
     * Display a listing of the resource.
     */
    public function index()
    {
        $parts = parse_url($_SERVER['REQUEST_URI']);
        if (!empty($parts['query'])) {
            parse_str($parts['query'], $query);
            $from = $query['fromdate'];
            $to = $query['todate'];
            $comment = '';
            $checkdate = 'yes';
            $fm = $query['fromdate'] . ' 00:00:00';
            $to2 = $query['todate'] . ' 23:59:59';
        } else {
            $getaccpara = null;
            $to = date('Y-m-d');
            $from = date('Y-m-d', strtotime('-7 days'));
            $fm =  $to . '00:00:00';
            $to2 = $from . '23:59:59';
            $checkdate = '';
            $comment = '';
        }
        $checkuser = User::where('id', Auth::user()->id)->first();
        if ($checkuser->affiliate != '1' && $checkuser->issubadmin != '1') {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id');
            $users = $users->where('users.deleted_at', null);
            $users = $users->where('role_user.role_id', '2');
            if (!empty($comment)) {
                //$users = $users->where('users.note', 'like', '%' . $comment . '%');
            }
            if ($checkdate == 'yes') {
                $users = $users->whereBetween('users.created_at', [$fm, $to2]);
            }
            $users = $users->get();
        } elseif (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);
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('role_user.role_id', '2')
                ->where('users.deleted_at', null)
                ->whereIn('users.id', $finalids)
                ->get();
        } elseif (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);
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('role_user.role_id', '2')
                ->where('users.deleted_at', null)
                ->whereIn('users.id', $finalids)
                ->get();
        } else {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('role_user.role_id', '2')
                ->where('users.deleted_at', null)
                ->where('users.afid', Auth::user()->id)
                ->get();
        }

        return view('admin.users.index', compact('users', 'to', 'from', 'comment'));
    }

    public function bulkuser()
    {
        $checkadmin = Gate::allows('permission_create');
        if ($checkadmin == true) {
            $accounts = User::where('affiliate', '1')->get();
            $leaddata = Leads::get();
        } else {
            abort(403);
        }
        return view('admin.users.bulkuser', compact('accounts', 'leaddata'));
    }

    public function indexusers()
    {
        $checkuser = User::where('id', Auth::user()->id)->first();
        if ($checkuser->affiliate != '1' && $checkuser->issubadmin != '1') {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('users.deleted_at', null)
                ->where('users.affiliate', '1')
                ->get();
        } elseif ($checkuser->issubadmin == '1') {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('users.deleted_at', null)
                ->where('users.afid', Auth::user()->id)
                ->where('users.affiliate', '1')
                ->get();
        } else {
            $users = array();
        }

        return view('admin.users.indexusers', compact('users'));
    }

    /**
     * Show the form for creating a new resource.
     */
    public function create()
    {
        $affiliates = User::where('affiliate', '1')->get();
        $roles = Role::all()->pluck('title', 'id');
        $countries = DB::table('countries')->get();

        return view('admin.users.create', compact('roles', 'affiliates','countries'));
    }

    public function assignsub()
    {
        abort_unless(Gate::allows('user_create'), 403);
        $affiliates = User::where('affiliate', '1')->where('issubadmin', '0')->get();
        $subadmins = User::where('issubadmin', '1')->get();
        $roles = Role::all()->pluck('title', 'id');
        $affiliatenames = User::where('affiliate', '1')->where('afid', '>', 0)->get();
        return view('admin.users.assignsub', compact('roles', 'affiliates', 'subadmins', 'affiliatenames'));
    }

    public function createsubadmin()
    {
        $roles = Role::all()->pluck('title', 'id');

        return view('admin.users.createsub', compact('roles'));
    }

    public function storesubadmin(StoreUserRequest $request)
    {
        abort_unless(Gate::allows('user_create'), 403);
        $data = $request->all();
        $fourRandomDigit = mt_rand(1000, 9999);
        $adduser = array();
        $adduser['name'] = $data['name'];
        $adduser['email'] = $data['email'];
        $adduser['mobile'] = $data['mobile'];
        $adduser['password'] = Hash::make($data['password']);
        $adduser['mypass'] = base64_encode($data['password']);
        $adduser['issubadmin'] = '1';
        if (!empty($data['promo'])) {
            $adduser['promo'] = 'AF-' . $fourRandomDigit;
        } else {
            $adduser['promo'] = '0';
        }
        if (!empty($data['usermanage'])) {
            $adduser['usermanager'] = $data['usermanage'];
        } else {
            $adduser['usermanager'] = '0';
        }
        if (!empty($data['mt4access'])) {
            $adduser['mt4access'] = $data['mt4access'];
        } else {
            $adduser['mt4access'] = '0';
        }
        if (!empty($data['deposit'])) {
            $adduser['deposit'] = $data['deposit'];
        } else {
            $adduser['deposit'] = '0';
        }
        if (!empty($data['withdrawal'])) {
            $adduser['withdrawal'] = $data['withdrawal'];
        } else {
            $adduser['withdrawal'] = '0';
        }
        if (!empty($data['leads'])) {
            $adduser['leads'] = $data['leads'];
        } else {
            $adduser['leads'] = '0';
        }
        // echo '<pre>';print_r($adduser);exit;
        $user = User::create($adduser);
        $user->roles()->sync(array('2'));

        return redirect()->route('admin.users.assignsub')->with('success','Subadmin added successfully');
    }

    public function storesub(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'subadmin' => 'required',
            'afid' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        User::where('id', $request->afid)->update(array(
            'afid'     => $request->subadmin
        ));
        return redirect()->back()->with('success','Affiliate assigned successfully');
    }

    public function createaffiliate()
    {
        abort_unless(Gate::allows('user_create'), 403);
        if (Auth::user()->affiliate == '1') {
            abort(403);
        }
        $roles = Role::all()->pluck('title', 'id');

        return view('admin.users.createaffiliate', compact('roles'));
    }

    public function changepass()
    {
        return view('admin.users.changepass');
    }

    public function savepass(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'currentpassword' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        $checkpass = base64_decode(Auth::user()->mypass);

        if ($request->currentpassword != $checkpass) {
            return redirect()->back()->withErrors(['Enter correct current password']);
        }
        $adduser = array();
        $adduser['password'] = Hash::make($request->password);
        $passencode = base64_encode($request->password);
        //User::update($adduser);
        User::where('id', Auth::user()->id)->update(array(
            'password'     => Hash::make($request->password),
            'mypass' => base64_encode($request->password),
        ));
        return redirect()->back()->with('success', 'Your password changed successfully.');
    }

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

    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        abort_unless(Gate::allows('user_create'), 403);
        $data = $request->all();
        $adduser = array();
        $adduser['name'] = $data['name'];
        $adduser['email'] = $data['email'];
        $adduser['mobile'] = $data['mobile'];
        $adduser['country'] = $data['country'];
        $adduser['password'] = Hash::make($data['password']);
        $adduser['mypass'] = base64_encode($data['password']);
        if (!empty($data['afid'])) {
            $adduser['afid'] = $data['afid'];
        }
        $user = User::create($adduser);
        $user->roles()->sync(array('2'));

        try {
            Mail::to($user->email)->send(new WelcomeMail($user, $adduser['mypass']));
        } catch (\Exception $e) {
            Log::error('Mail sending failed: ' . $e->getMessage());
        }

        return redirect()->route('admin.users.index')->with('success','User added successfully');
    }

    public function storeaffiliate(StoreUserRequest $request)
    {
        abort_unless(Gate::allows('user_create'), 403);
        $data = $request->all();
        $fourRandomDigit = mt_rand(1000, 9999);
        $adduser = array();
        $adduser['name'] = $data['name'];
        $adduser['email'] = $data['email'];
        $adduser['mobile'] = $data['mobile'];
        $adduser['password'] = Hash::make($data['password']);
        $adduser['mypass'] = base64_encode($data['password']);
        $adduser['affiliate'] = '1';
        $adduser['promo'] = 'AF-' . $fourRandomDigit;
        if (!empty($data['usermanager'])) {
            $adduser['usermanager'] = $data['usermanager'];
        } else {
            $adduser['usermanager'] = '0';
        }
        if (!empty($data['mt4access'])) {
            $adduser['mt4access'] = $data['mt4access'];
        } else {
            $adduser['mt4access'] = '0';
        }
        if (!empty($data['deposit'])) {
            $adduser['deposit'] = $data['deposit'];
        } else {
            $adduser['deposit'] = '0';
        }
        if (!empty($data['withdrawal'])) {
            $adduser['withdrawal'] = $data['withdrawal'];
        } else {
            $adduser['withdrawal'] = '0';
        }
        if (!empty($data['leads'])) {
            $adduser['leads'] = $data['leads'];
        } else {
            $adduser['leads'] = '0';
        }
        $user = User::create($adduser);
        $user->roles()->sync(array('3'));

        return redirect()->route('admin.users.usersaffiliate')->with('success','Affiliate added successfully');
    }

    /**
     * Display the specified resource.
     */
    public function show(User $user)
    {
        abort_unless(Gate::allows('user_show'), 403);

        $user->load('roles');

        return view('admin.users.show', compact('user'));
    }

    // Particular User fetch code start
    public function showUser(User $user, Request $request)
    {
        abort_unless(Gate::allows('user_show'), 403);

        // MT5 Account Fetch
        $mt4ids = array();
        $getuserdata = array();
        $accounts = DB::table('users')
            ->join('mtaccount', 'users.id', '=', 'mtaccount.userid')
            ->select('users.name', 'users.email', 'mtaccount.*')
            ->where('userid', $user->id)
            ->get();
        // echo '<pre>';print_r($accounts);exit;
        $allacc = array();
        foreach ($accounts as $key => $mta) {
            $allacc[$key]['index'] = $key;
            $allacc[$key]['accountID'] = $mta->loginid;
        }
        $getids = Mtaccount::select('loginid')->where('userid', $user->id)->pluck('loginid')->toArray();
        $getuserdata = array();

        foreach ($getids as $mtid) {

            $url = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
            $postdata = array();
            $postdata['LOGIN'] = $mtid;
            $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);
            // echo '<pre>';print_r($getuserdata);exit;
        }

        // Deposit Fetch
        $deposit = DB::table('deposit')
            ->join('users', 'deposit.userid', '=', 'users.id')
            ->select('users.name', 'users.email', 'deposit.*')
            ->where('users.id', $user->id)
            ->where('deposit.displaystatus', '1')
            ->get();

        // Withdraw Fetch
        $withdraw = DB::table('withdraw')
            ->join('users', 'withdraw.userid', '=', 'users.id')
            ->select('users.name', 'users.email', 'withdraw.*')
            ->where('users.id', $user->id)
            ->get();

        // OpenTrade
        $accounts = Mtaccount::where('userid', $user->id)->get();
        $positions = [];

        if ($accounts->isNotEmpty()) {
            foreach ($accounts as $account) {
                $mtaccount = $account->loginid;

                $userdetail = [
                    'LOGIN' => $mtaccount,
                ];

                $apiurl = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=GetPosition';
                $option = [
                    '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);

                if (isset($getresult->status) && $getresult->status == 'success') {
                    $positions[$mtaccount] = $getresult->response;
                } else {
                    $positions[$mtaccount] = [];
                }

                curl_close($ch);
            }
        } else {
            $positions = [];
        }
        // echo "<pre>"; print_r($positions); exit;

        // CloseTrade
        $accountclosetrade = Mtaccount::where('userid', $user->id)->get();
        $allid = [];
        if (count($accountclosetrade) > 0) {
            foreach ($accountclosetrade as $mtid) {
                $allid[] = $mtid->loginid;
            }
        }

        $mtaccount = $request->account ?? $allid[0];

        $from = '2024-10-28 00:00:00';
        $to = date('Y-m-d 23:59:59');
        $fromdate1 = strtotime($from);
        $fromdate2 = strtotime($to);

        $closedTrades = [];

        foreach ($allid as $mtaccount) {
            $userdetail = [
                'LOGIN' => $mtaccount,
                'FROM' => $fromdate1,
                'TO' => $fromdate2,
            ];

            $apiurl = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=GetClosedOrders';
            $option = [
                '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);

            if ($getresult->status == 'success') {
                $closedTrades[$mtaccount] = $getresult->response;
            } else {
                $closedTrades[$mtaccount] = [];
            }

            curl_close($ch);
        }

        return view('admin.users.showUser', compact('accounts', 'getids', 'getuserdata', 'deposit', 'withdraw', 'positions', 'closedTrades'));
    }

    public function depositForm(Request $request, $login)
    {
        $accounts = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($accounts);exit;
        if (!$accounts) {
            return redirect()->back()->with('error', 'User account not found');
        }

        return view('admin.users.userDeposit', compact('accounts'));
    }

    public function storeDeposit(Request $request, $login)
    {
        $checkde = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($checkde);exit;
        $urlw = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=Deposit';
        $postdata1 = array();
        $postdata1['LOGIN'] = $login;
        $postdata1['TYPE'] = 2;
        $postdata1['BALANCE'] = $request->amount;
        $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); // 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'] = $login;
            $adduser['userid'] = $checkde->userid;
            $adduser['amount'] = $data['amount'];
            $adduser['clientnote'] = '-';
            $adduser['description'] = $data['description'];
            $adduser['status'] = '1';
            $adduser['displaystatus'] = '1';
            $adduser['method'] = 'deposit';
            // echo '<pre>';print_r($adduser);exit;
            $product = Deposit::create($adduser);
        }

        return redirect()->route('admin.users.index')->with('success', 'Deposit added successfully');
    }

    public function withdrawForm(Request $request, $login)
    {
        $accounts = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($accounts);exit;
        if (!$accounts) {
            return redirect()->back()->with('error', 'User account not found');
        }

        return view('admin.users.userWithdraw', compact('accounts'));
    }

    public function storeWithdraw(Request $request, $login)
    {
        $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
        $postdata = array();
        $postdata['LOGIN'] = $login;
        $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);
        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', $login)->first();
        $getcountry = User::where('id', $checkde->userid)->first();
        $comnt = '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'] = $login;
        $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);
        // echo '<pre>';print_r($getuserdata1);exit;
        if ($getuserdata1->status == 'success') {

            $data = $request->all();
            $adduser = array();
            $adduser['mt4account'] = $login;
            $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.users.index')->with('success', 'Withdraw amount successfully');
    }

    public function creditinForm(Request $request, $login)
    {
        $accounts = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($accounts);exit;
        if (!$accounts) {
            return redirect()->back()->with('error', 'User account not found');
        }

        return view('admin.users.userCreditin', compact('accounts'));
    }

    public function storeCreditin(Request $request, $login)
    {
        $checkde = Mtaccount::where('loginid', $login)->first();
        $comnt = 'creditin';

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

            $product = Creditin::create($adduser);
        }
        return redirect()->route('admin.users.index')->with('success', 'Credit amount successfully');
    }

    public function creditoutForm(Request $request, $login)
    {
        $accounts = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($accounts);exit;
        if (!$accounts) {
            return redirect()->back()->with('error', 'User account not found');
        }

        return view('admin.users.userCreditout', compact('accounts'));
    }

    public function storeCreditout(Request $request, $login)
    {
        $url = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=FetchUser';
        $postdata = array();
        $postdata['LOGIN'] = $login;
        $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', $login)->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'] = $login;
        $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'] = $login;
            $adduser['userid'] = $checkde->userid;
            $adduser['amount'] = $data['amount'];
            $adduser['description'] = $data['description'];
            $adduser['status'] = '1';

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

    public function leverageForm(Request $request, $login)
    {
        $accounts = Mtaccount::where('loginid', $login)->first();
        // echo '<pre>';print_r($accounts);exit;
        if (!$accounts) {
            return redirect()->back()->with('error', 'User account not found');
        }

        return view('admin.users.userLeverage', compact('accounts'));
    }

    public function storeLeverage(Request $request, $login, User $user)
    {
        $docdata = Leverage::where('mtaccount', $login)->first();
        // echo '<pre>';print_r($docdata);exit;
        $adduser = array();

        if ($docdata->status == '1') {
            $userdetail = array();
            $userdetail['LOGIN'] = $login;
            $userdetail['LEVERAGE'] = $request->leverage;
            $apiurl = 'http://api.tradeactive.com/mt5demo/api/api.php?MODE=UpdateUser';

            $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 !== '') {
                Mtaccount::where('loginid', $login)->update(array(
                    'leverage'   => $request->leverage,
                ));

                Leverage::where('mtaccount', $login)->update([
                    'leverage' => $request->leverage,
                ]);
            }
        }

        return redirect()->route('admin.users.index')->with('success', 'Leverage changed successfully');
    }

    public function openTrade(Request $request, User $user)
    {
        abort_unless(Gate::allows('user_client'), 403);
        $accounts = Mtaccount::where('userid', $user->id)->get();
        $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::where('userid', $user->id)->first();
            $mtaccount = $accountdata->loginid;
        }

        $userdetail = array();
        $userdetail['LOGIN'] = $mtaccount;

        $apiurl = 'https://api.tradeactive.com/mt5demo/api/api.php?MODE=GetPosition';
        $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.users.userOpenTrade', compact('accounts', 'positions', 'mtaccount'));
    }

    public function closeTrade(Request $request, User $user)
    {
        //$this->makeconnection();
        abort_unless(Gate::allows('user_client'), 403);
        $accounts = Mtaccount::where('userid', $user->id)->get();
        $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::where('userid', $user->id)->first();
            $mtaccount = $accountdata->loginid;
        }
        $from = '2020-06-01 00:00:00';
        $to = date('Y-m-d 23:59:59');

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

        $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.users.userCloseTrade', compact('accounts', 'positions', 'mtaccount'));
    }
    // Particular User fetch code ends

    /**
     * Show the form for editing the specified resource.
     */
    public function edit(User $user)
    {
        abort_unless(Gate::allows('user_edit'), 403);

        $roles = Role::all()->pluck('title', 'id');
        $affiliates = User::where('affiliate', '1')->get();
        $user->load('roles');

        return view('admin.users.edit', compact('roles', 'user', 'affiliates'));
    }

    public function myprofile()
    {
        $user = User::where('id', Auth::user()->id)->first();
        return view('admin.users.myprofile', compact('user'));
    }

    public function updateprofile(Request $request)
    {

        if (!empty($request->name)) {
            $name = $request->name;
        } else {
            $name = Auth::user()->name;
        }
        if (!empty($request->email)) {
            $email = $request->email;
        } else {
            $email = Auth::user()->email;
        }
        if (!empty($request->mobile)) {
            $mobile = $request->mobile;
        } else {
            $mobile = Auth::user()->mobile;
        }

        User::where('id', Auth::user()->id)->update(array(
            'name'     => $name,
            'email' => $email,
            'mobile' => $mobile,
        ));
        return redirect()->back()->with('success', 'Your profile changed successfully.');
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(UpdateUserRequest $request, User $user)
    {
        abort_unless(Gate::allows('user_edit'), 403);
        if (Auth::user()->affiliate == '1') {
            $checkuser = User::where('id', $request->id)->where('afid', Auth::user()->id)->get();
            if (count($checkuser) == 0) {
                abort(403);
            }
        }

        if (!empty($request->password)) {
            $request['mypass'] = base64_encode($request->password);
        }
        if (empty($request->usermanager)) {
            $request['usermanager'] = '0';
        } else {
            $request['usermanager'] = '1';
        }
        if (empty($request->mt4access)) {
            $request['mt4access'] = '0';
        } else {
            $request['mt4access'] = '1';
        }
        if (empty($request->deposit)) {
            $request['deposit'] = '0';
        } else {
            $request['deposit'] = '1';
        }
        if (empty($request->withdrawal)) {
            $request['withdrawal'] = '0';
        } else {
            $request['withdrawal'] = '1';
        }
        if (empty($request->leads)) {
            $request['leads'] = '0';
        } else {
            $request['leads'] = '1';
        }
        $user->update($request->all());

        return redirect()->route('admin.users.index')->with('success','Updated successfully');
    }

    public function createdocadmin()
    {
        abort_unless(Gate::allows('user_access'), 403);

        $checkuser = User::where('id', Auth::user()->id)->first();
        if ($checkuser->affiliate != '1') {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('role_user.role_id', '2')
                ->get();
        } else {
            $users = DB::table('users')
                ->join('role_user', 'users.id', '=', 'role_user.user_id')
                ->select('users.*', 'role_user.role_id')
                ->where('role_user.role_id', '2')
                ->where('users.afid', Auth::user()->id)
                ->get();
        }

        return view('admin.users.createdocadmin', compact('users'));
    }

    public function createdoc()
    {
        return view('admin.users.createdoc');
    }

    public function indexdoc()
    {
        if (Auth::user()->id == '1') {
            $docs = Documents::get();
            // echo '<pre>';print_r($docs);exit;
            return view('admin.users.indexdoc', compact('docs'));
        }
        if (Auth::user()->affiliate == '1') {
            $docs = DB::table('documents')
                ->join('users', 'documents.userid', '=', 'users.id')
                ->select('documents.*', 'users.name')
                ->where('users.afid', Auth::user()->id)
                ->get();
        } else {
            $docs = Documents::where('userid', Auth::user()->id)->get();
        }

        if (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);
            $docs = DB::table('documents')
                ->join('users', 'documents.userid', '=', 'users.id')
                ->select('documents.*', 'users.name')
                ->whereIn('users.id', $finalids)
                ->get();
        }

        return view('admin.users.indexdoc', compact('docs'));
    }

    public function storedoc(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'identity' => 'required',
            'residential' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        $documents = new Documents();
        $documents->userid = Auth::user()->id;
        $identity = $request->file('identity');
        $residential = $request->file('residential');
        $identityfile = str_replace(' ', '_', $identity->getClientOriginalName());
        $residentfile = str_replace(' ', '_', $residential->getClientOriginalName());
        $path = public_path('documents/' . $documents->userid);
        $secondaryPath = '/home/fxdemosi/cabinet.fxdemo.site/public/documents/' . $documents->userid;

        if (!File::isDirectory($path)) {
            File::makeDirectory($path, 0777, true, true);
        }
        if (!File::isDirectory($secondaryPath)) {
            File::makeDirectory($secondaryPath, 0777, true, true);
        }
        $identity->move($path, $identityfile);
        $residential->move($path, $residentfile);
        File::copy($path . '/' . $identityfile, $secondaryPath . '/' . $identityfile);
        File::copy($path . '/' . $residentfile, $secondaryPath . '/' . $residentfile);
        $documents->identity = $identityfile;
        $documents->resident = $residentfile;
        $documents->save();
        return redirect('admin/users/documents')->with('success','Documents upload successfully');
    }

    public function storedocadmin(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'identity' => 'required',
            'residential' => 'required'
        ]);
        if ($validator->fails()) {
            return redirect()->back()
                ->withErrors($validator)
                ->withInput();
        }
        $documents = new Documents();
        $documents->userid = $request->userid;
        $identity = $request->file('identity');

        $residential = $request->file('residential');
        $identityfile = str_replace(' ', '_', $identity->getClientOriginalName());
        $residentfile = str_replace(' ', '_', $residential->getClientOriginalName());
        $path = public_path('documents/' . $request->userid);
        // echo $path;exit;
        $secondaryPath = '/home/fxdemosi/cabinet.fxdemo.site/public/documents/' . $documents->userid;
        if (str_contains($residentfile, 'php')) {
            dd("not allowed");
        }
        if (str_contains($identityfile, 'php')) {
            dd("not allowed");
        }
        if (!File::isDirectory($path)) {
            File::makeDirectory($path, 0777, true, true);
        }
        if (!File::isDirectory($secondaryPath)) {
            File::makeDirectory($secondaryPath, 0777, true, true);
        }
        $identity->move($path, $identityfile);
        $residential->move($path, $residentfile);
        File::copy($path . '/' . $identityfile, $secondaryPath . '/' . $identityfile);
        File::copy($path . '/' . $residentfile, $secondaryPath . '/' . $residentfile);
        $documents->identity = $identityfile;
        $documents->resident = $residentfile;
        $documents->save();
        return redirect('admin/users/documents')->with('success','Documents upload successfully by Admin');
    }

    public function approve($id)
    {
        $document = Documents::findOrFail($id);
        $document->status = '1';
        $document->save();

        $user = User::findOrFail($document->userid);

        try {
            Mail::to($user->email)->send(new DocumentStatusMail($user, $document->status));
        } catch (\Exception $e) {
            Log::error('Mail sending failed: ' . $e->getMessage());
        }

        return response()->json(['success' => true]);
    }

    public function reject($id)
    {
        $document = Documents::findOrFail($id);
        $document->status = '2';
        $document->save();

        $user = User::findOrFail($document->userid);

        try {
            Mail::to($user->email)->send(new DocumentStatusMail($user, $document->status));
        } catch (\Exception $e) {
            Log::error('Mail sending failed: ' . $e->getMessage());
        }

        return response()->json(['success' => true]);
    }

    public function docdestroy(Documents $document,$id)
    {
        // echo $document;exit;
        $document = Documents::findOrFail($id);
        $path = public_path('documents/' . $document->userid);

        if (File::exists($path . '/' . $document->identity)) {
            File::delete($path . '/' . $document->identity);
        }

        if (File::exists($path . '/' . $document->resident)) {
            File::delete($path . '/' . $document->resident);
        }

        if (File::isDirectory($path) && count(File::files($path)) === 0) {
            File::deleteDirectory($path);
        }

        $document->forceDelete();

        return redirect()->back()->with('message', 'Document deleted successfully.');
    }

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

        $user->forceDelete();

        return back();
    }

    public function massDestroy(MassDestroyUserRequest $request)
    {
        User::whereIn('id', request('ids'))->forceDelete();

        return response(null, 204);
    }

    public function exportClients()
    {
        $userData = User::all();

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

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

            public function array(): array
            {
                return $this->userData->map(function ($user) {
                    $affiliateName = null;
                    if ($user->afid) {
                        $affiliate = User::select('name')->where('id', $user->afid)->first();
                        $affiliateName = $affiliate ? $affiliate->name : 'No Affiliate Assigned';
                    }

                    return [
                        $user->name,
                        $user->email,
                        $user->mobile,
                        $user->country,
                        base64_decode($user->mypass),
                        $affiliateName,
                    ];
                })->toArray();
            }

            public function headings(): array
            {
                return [
                    'Name', 'Email', 'Mobile', 'Country', 'Password', 'Affiliate',
                ];
            }
        }, 'Clients.xlsx');
    }
}
