GOOD SHELL MAS BOY
Server: Apache/2.4.52 (Ubuntu)
System: Linux vmi1836763.contaboserver.net 5.15.0-130-generic #140-Ubuntu SMP Wed Dec 18 17:59:53 UTC 2024 x86_64
User: www-data (33)
PHP: 8.4.10
Disabled: NONE
Upload Files
File: /var/www/vaspayment.com/app/Http/Controllers/HomeController.php
<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\Key;
use App\Models\Blog;
use App\Models\User;
use App\Models\Wallet;
use App\Models\Gateway;
use App\Models\Product;
use App\Models\Business;
use App\Models\FundRequest;
use App\Models\Transaction;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Models\WalletHistory;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use App\Mail\ScammerAlert;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Mail;

class HomeController extends Controller
{
    private function ringoUrl()
    {
        return config('app.ringo');
    }

    private function ringoHeader()
    {
        $email = config('app.mail');
        $password = config('app.mail');


        $headers = [
            'email: ' . $email,
            'password: ' . $password,
            'Content-Type: application/json',
            'Authorization: Basic ' . base64_encode("$email:$password"),
        ];
        return $headers;
    }
    private function station()
    {
        $toke = config("app.station");
        $headers = [
            'Authorization' => 'Token ' . $toke,
            'Content-Type' => 'application/json',
        ];
        return $headers;
    }

    public function __construct()
    {
        // if (config('app.verification') === true) {
        $this->middleware(['auth', 'verified'])->except('home');
        // } else {
        //     $this->middleware(['auth'])->except('home');
        // }
    }

    private function baseUrl()
    {
        return config('app.honour_world');
    }

    private function header()
    {
        $email = config('app.mail');
        $token = Key::where('email', $email)->value('live_key');
        $headers = [
            "Authorization" => "Bearer " . $token,
            "Accept" => "application/json",
            "Content-Type" => "application/json",
        ];
        return $headers;
    }



    public function index(User $user, Request $request)
    {
        $user = auth()->user();

        if (
            ($user->wallet && strpos($user->wallet->balance, '-') === 0) ||
            strpos($user->wallet->commission, '-') === 0
        ) {
            // Update user status to 1
            $user->status = 1;
            $user->save();

            // Logout the user
            Auth::logout();

            // Send scammer alert email to support
            Mail::to('support@vaspayment.com')->send(new ScammerAlert($user->name, $user->email, $user->phone));

            // Redirect or respond as needed
            return redirect()->route('login');
        }

        $user = auth()->user();
        $email = config('app.mail');
        $password = config('app.mail');


        if ($user->role == 'customer') {
            // CHECK IF THE USER IS ACTIVE
            if ($user->status == 1) {
                auth()->logout(); // Log out the user
                return redirect()->route('login')->with('error', 'Your account has been deactivated. Please contact the admin for assistance.');
            }
            $products = Product::orderBy('name', 'asc')->where('status', '0')->get();
            $transactions = Transaction::where('user_id', $user->id)->latest()->paginate(10);
            $email = config('app.name');
            $business = Business::where('name', $email)->first();

            //update user table with referree code if he do not have. and this will be temporary 
            if (!$user->referree_id) {
                $user = User::where('id', $user->id)->first();
                $user->referree_id = $user->wallet_id;
                $user->save();
            }
            //Create Budy Account
            // $this->createBudPayAccount($user);


            return view('dashboard.customer', compact('products', 'transactions', 'business'));
        } elseif ($user->role == 'agent') {

            $toke = Key::where('email', $user->email)->first();
            if (!$toke || !$toke->token) {
                return redirect(route('verify.agent'));
            }

            $biz = Business::where('email', $email)->first();

            if ($biz) {
                // Agent has business info. DO NOTHING
            } else {
                // Agent doesn't have business info, redirect with a flash message
                return redirect(route('setting.business'))->with('error', 'Please provide business information.');
            }
            $totalUsers = User::select('id')->count('id');
            $products = Product::where('status', '0')->get();
            $transactions = Transaction::latest()->paginate(10);
            $funds = Wallet::latest()->get();

            // GET AGENT WALLET FORM HONOURWORLD API
            try {
                $wallet = [];
                $agentWallet = $this->baseUrl() . '/api/v2/wallet/manage-wallet-balance';
                $response = Http::withHeaders($this->header())->get($agentWallet);
                if ($response->getStatusCode() == 200) {
                    $wallet = $response->json()['data'] ?? [];

                    // Update the agent wallet to his platform
                    $userWallet = Wallet::where('user_id', $user->id)->first();
                    if ($userWallet) {
                        $userWallet->balance = $wallet['available'] ?? "0.00";
                        $userWallet->commission = $wallet['commission'] ?? "0.00";
                        $userWallet->save();
                    }
                } else {
                    return $response->json();
                }
            } catch (\Throwable $th) {
                //throw $th;
            }

            // GET AGENT WALLET FROM RINGO 
            try {
                $response = Http::withHeaders([
                    'Content-Type' => 'application/json',
                    'email' => config('app.ringo_email'),
                    'password' => config('app.ringo_password'),
                ])
                    ->post('https://www.api.ringo.ng/api/agent/p2', [
                        'serviceCode' => 'INFO',
                    ]);
                if ($response->successful()) {
                    $balance = $response->json()['wallet']['wallet']['balance'] ?? "0.00";
                    $commission = $response->json()['wallet']['wallet']['commission_balance'] ?? "0.00";
                }
            } catch (\Throwable $th) {
                return $th;
            }

            // GET AGENT WALLET FROM DATASTATION
            try {
                $get = 'https://datastation.com.ng/api/user/';
                $response =  Http::withHeaders($this->station())->get($get);
                if ($response->successful()) {
                    $stationAccount = $response->json()['user']['Account_Balance'] ?? "0.00";
                } else {
                    return $response->json();
                }
            } catch (\Throwable $th) {
                return $th;
            }
            return view('dashboard.agent', compact('stationAccount', 'wallet', 'products', 'transactions', 'funds', 'totalUsers', 'balance', 'commission'));
        }

        return redirect()->route('home')->with('error', 'Unauthorized access.');
    }

    protected function verifyAgentToken($user)
    {
        $token = Key::where('email', $user->email)->first();

        if (!$token || !$token->token) {
            return redirect(route('verify.agent'));
        }
    }

    protected function checkBusinessInfo($email)
    {
        $business = Business::where('email', $email)->first();

        if (!$business) {
            return redirect(route('setting.business'))->with('error', 'Please provide business information.');
        }
    }

    protected function getWalletDataFromHonourworld($user)
    {
        try {
            $agentWalletUrl = $this->baseUrl() . '/api/v2/wallet/manage-wallet-balance';
            $response = Http::withHeaders($this->header())->get($agentWalletUrl);

            if ($response->successful()) {
                return $response->json()['data'];
            }

            return null;
        } catch (\Throwable $th) {
            // Log the error or handle it accordingly
            return null;
        }
    }

    protected function getWalletDataFromRingo()
    {
        try {
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'email' => config('app.ringo_email'),
                'password' => config('app.ringo_password'),
            ])->post('https://www.api.ringo.ng/api/agent/p2', [
                'serviceCode' => 'INFO',
            ]);

            if ($response->successful()) {
                return [
                    'balance' => $response->json()['wallet']['wallet']['balance'],
                    'commission' => $response->json()['wallet']['wallet']['commission_balance'],
                ];
            }

            return null;
        } catch (\Throwable $th) {
            // Log the error or handle it accordingly
            return null;
        }
    }

    protected function getDataFromDatastation()
    {
        try {
            $getUrl = 'https://datastation.com.ng/api/user/';
            $response = Http::withHeaders($this->header())->get($getUrl);

            if ($response->successful()) {
                return [
                    'stationAccount' => $response->json()['user']['Account_Balance'],
                    'stationBalance' => $response->json()['user']['wallet_balance'],
                    'stationBonus' => $response->json()['user']['bonus_balance'],
                ];
            }

            return null;
        } catch (\Throwable $th) {
            // Log the error or handle it accordingly
            return null;
        }
    }

    // private function createBudPayAccount($user)
    // {
    //     $body = [
    //         'first_name' => $user->name,
    //         'email' => $user->email,
    //         'phone' => $user->phone,
    //     ];
    //     $token = env('BUDPAY_KEY');
    //     $headers = [
    //         'Content-Type' => 'application/json',
    //         'Authorization' => 'Bearer ' . $token
    //     ];
    //     try {
    //         $create = 'https://api.budpay.com/api/v2/customer';
    //         $response = Http::withHeaders($headers)->post($create, $body);
    //         if ($response->successful()) {
    //             $customer_code = $response->json()['data']['customer_code'];
    //             //Create the virtual account
    //             $username = ['customer' => $customer_code];
    //             $account = 'https://api.budpay.com/api/v2/dedicated_virtual_account';
    //             $request = Http::withHeaders($headers)->post($account, $username);
    //             if ($request->successful()) {
    //                 $account_no = $request->json()['data']['account_number'];
    //                 $reference = $request->json()['data']['reference'];
    //                 $bank = $request->json()['data']['bank']['name'];
    //                 // update the user model// may not be needed self to save
    //                 $user->account_number_3 = $account_no;
    //                 $user->account_bank_3 = $bank;
    //                 $user->budPay_customer_code = $customer_code;
    //                 $user->budPay_customer_reference = $reference;
    //                 $user->save();
    //             }

    //             info('BudPay Wema Virtual Account Created');
    //         } else {
    //             Log::error('Unable to create BudPay customer: ' . $response->json()['message']);
    //         }
    //     } catch (\Throwable $th) {
    //         Log::error('Error creating BudPay customer: ' . $th->getMessage());
    //     }
    // }

    public function user(Request $request)
    {
        $sumwallets = Wallet::select('balance')->sum('balance');
        $sumtransactions = Transaction::select('amount')->sum('amount');
        $users = User::select('id')->count();

        if ($request->search) {
            $all = User::where('name', 'like', '%' . $request->search . '%')
                ->orWhere('wallet_id', 'like', '%' . $request->search . '%')
                ->orWhere('email', 'like', '%' . $request->search . '%')
                ->latest()
                ->paginate(20);
        } else {
            $all = User::latest()->paginate(10);
        }
        return view('dashboard.agent.users', compact('all', 'users', 'sumwallets', 'sumtransactions'));
    }

    public function updateUser(Request $request, User $user)
    {
        $user->status = $request->get('status');
        $user->lastname = $request->get('lastname');
        $user->save();
        return redirect()->back()->with('status', 'User Updated Successful');
    }

    public function updateWallet(Request $request, Wallet $wallet)
    {
        $transactionReference = Str::random(20);

        $wallet->balance = $request->get('balance');
        $wallet->commission = $request->get('commission');
        $wallet->save();

        //save to DB
        $trans = new Transaction();
        $trans->reference = $transactionReference;
        $trans->amount = $wallet->balance;
        $trans->commission = $wallet->commission;
        $trans->status = "200";
        $trans->type = "DEBIT FUNDS";
        $trans->destination = $wallet->user->email;
        $trans->network = "ADMIN FUND";
        $trans->user_id = $wallet->user->id;
        $trans->save();


        return redirect()->back()->with('status', 'Wallet Updated Successful');
    }

    public function customerTransaction()
    {
        if (auth()->user()->role == 'customer') {
            $user_id = auth()->user()->id;
            $email = config('app.mail');
            $transactions = Transaction::where('user_id', $user_id)->latest()->paginate(10);
            $transx = Transaction::where('user_id', $user_id);
            $sumAmounts = $transx->sum('amount');

            $today = now()->format('Y-m-d');
            $todaytransactions = $transx
                ->whereDate('created_at', $today)
                ->sum('amount');

            $currentMonth = now()->format('Y-m');
            $monthlytransactions = $transx
                ->whereYear('created_at', '=', now()->year)
                ->whereMonth('created_at', '=', now()->month)
                ->sum('amount');
            $business = Business::where('email', $email)->first();

            return view('dashboard.agent.transaction.customer', compact('sumAmounts', 'todaytransactions', 'monthlytransactions', 'transactions', 'business'));
        } else {
            $transactions = Transaction::latest()->paginate(10);
            return view('dashboard.agent.transaction.agent', compact('transactions'));
        }
    }

    public function airtimeTransaction()
    {
        return $this->getTransactionData('airtime');
    }

    public function dataTransaction()
    {
        return $this->getTransactionData('data');
    }

    public function cableTransaction()
    {
        return $this->getTransactionData('cable');
    }

    public function electricityTransaction()
    {
        return $this->getTransactionData('electricity');
    }

    private function getTransactionData($type)
    {
        // Fetch all transactions of the specified type
        $tranx = Transaction::where('type', $type);

        // Fetch the latest 10 transactions for pagination
        $transactions = $tranx->latest()->paginate(10);

        // Calculate the total sum and count of all transactions
        $sum = $tranx->sum('amount');
        $count = $tranx->count();

        // Calculate today's transactions
        $todayTransactions = Transaction::where('type', $type)
            ->whereDate('created_at', today())
            ->sum('amount');

        // Calculate monthly transactions
        $currentMonth = now()->format('Y-m');
        $monthlyTransactions = Transaction::where('type', $type)
            ->whereYear('created_at', now()->year)
            ->whereMonth('created_at', now()->month)
            ->sum('amount');

        // Calculate yearly transactions
        $currentYear = now()->year;
        $yearlyTransactions = Transaction::where('type', $type)
            ->whereYear('created_at', $currentYear)
            ->sum('amount');

        // Pass the data to the view
        return view('dashboard.agent.transaction.' . $type, compact('transactions', 'sum', 'count', 'todayTransactions', 'monthlyTransactions', 'yearlyTransactions'));
    }


    public function product()
    {
        $user_id = auth()->user()->id;
        $products = Product::orderBy('name', 'asc')->where('status', '0')->get();
        if (auth()->user()->role == 'customer') {
            $transactions = Transaction::where('user_id', $user_id)->latest()->paginate(10);
        } else {
            $products = Product::orderBy('name', 'asc')->get();
            $transactions = Transaction::latest()->paginate(10);
        }
        return view('dashboard.agent.index', compact('products', 'transactions'));
    }

    public function walletHistory(Request $request)
    {
        $user = auth()->user();
        if ($user->role == 'agent') {
            $wallet = WalletHistory::latest()->paginate(10);
        } else {
            $wallet = WalletHistory::where('user_id', $user->id)->latest()->paginate(10);
        }
        return view('dashboard.agent.wallet.history', compact('wallet'));
    }
}