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/ElectricityController.php
<?php

namespace App\Http\Controllers;

use App\Models\Key;
use App\Models\Wallet;
use App\Models\Product;
use App\Models\Referrals;
use App\Models\Electricity;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Models\WalletHistory;
use Illuminate\Support\Facades\Http;

class ElectricityController extends Controller
{
    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 __construct()
    {
        if (config('app.verification') === true) {
            $this->middleware(['auth', 'verified']);
        } else {
            $this->middleware(['auth']);
        }
    }

    public function buyElectricity(Request $request)
    {
        $body = [
            'disco' => $request->get('disco'),
            'type' => $request->get('type'),
            'meterNo' => $request->get('meterNo'),
            'phoneNumber' => $request->get('phone'),
            'amount' => $request->get('amount'),
        ];

        $amount = str_replace(',', '', $request->get('amount'));
        $disco = $request->get('disco');
        $beneficiary = $request->get('beneficiary');
        $address = $request->get('customerAddress');
        $meterNo = $request->get('meterNo');

        $user = auth()->user();

        $userBalance = $user->wallet->balance;
        if ($userBalance < $amount) {
            return redirect()->route('fund.index')->with('error', 'Insufficient fund. Kindly fund your wallet to proceed!');
        }




        try {
            $purchase = $this->baseUrl() . '/api/v2/electricity/buy';
            $response = Http::withHeaders($this->header())->post($purchase, $body);
            $info = $response->json();
            info($info);
            if ($response->successful()) {
                // Debit the amount from the user's wallet
                $userWallet = $user->wallet;
                $userWallet->balance -= $amount;
                $userWallet->save();

                // Add Commission to the user
                if ($response->json()['status'] == '200') {
                    $power = Product::where('name', 'power')->first();
                    if ($power) {
                        $wallet = Wallet::where('user_id', $user->id)->first();
                        if ($wallet) {
                            $fetchValue = $power->commission;
                            $commissionPercentage = $fetchValue / 100;
                            $newCommission = $commissionPercentage * $amount;
                            $wallet->commission += $newCommission;
                            $wallet->save();
                        } else {
                            $newCommission = 0.25;
                            $wallet->commission += $newCommission;
                            $wallet->save();
                        }
                    }
                }
                // extract parameters
                $status = $response->json()['data']['status'];
                $reference = $response->json()['data']['reference'];
                $token = $response->json()['data']['token'];
                $unit = $response->json()['data']['unit'];

                // Check if the user has not done a transaction before
                $hasNotDoneTransaction = !Transaction::where('user_id', $user->id)->exists();
                // User has not done a transaction before
                if ($hasNotDoneTransaction) {
                    // Find the referral record where the referree_id matches the user's wallet_id and status is 0
                    $referral = Referrals::where('referral_id', $user->wallet_id)->where('status', 0)->first();
                    if ($referral) {
                        $referreeWallet = Wallet::where('wallet_id', $referral->referree_id)->first();
                        if ($referreeWallet) {
                            $referreeWallet->commission += 20;
                            $referreeWallet->save();

                            // Update the referral record to mark it as credited
                            $referral->status = 1;
                            $referral->save();
                        } else {
                            info('record of wallet id not found');
                        }
                    } else {
                        info('bonus given already');
                    }
                }

                //save to DB
                $trans = new Transaction();
                $trans->reference = 'refID ' .  $reference . ' meterNo ' . $meterNo;
                $trans->amount = $amount;
                $trans->commission = $newCommission;
                $trans->status = $status;
                $trans->type = "electricity";
                $trans->destination = $beneficiary;
                $trans->unit = $unit;
                $trans->network = 'type ' . $disco . ' address ' . $address;
                $trans->token = $token;
                $trans->user_id = $user->id;
                $trans->save();

                $currentBal = $userBalance - $amount; //Get current balance of the user

                // Save to Wallet History
                $walletHistory = new WalletHistory();
                $walletHistory->previous_balance = $userBalance;
                $walletHistory->current_balance = $currentBal;
                $walletHistory->amount = $amount;
                $walletHistory->transaction_id = $reference;
                $walletHistory->transaction_type = "Electricity Purchase";
                $walletHistory->user_id = $user->id;
                $walletHistory->save();

                return redirect(route('dashboard'))->with('status', $response->json()['data']['msg']);
            } else {
                $errorMessages = '';
                foreach ($info['error'] as $error) {
                    $errorMessage = $error['msg'];
                    $errorMessages .= $errorMessage . ' ';
                }
                return redirect(route('dashboard'))->with('error', $errorMessages);
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Electricity Provider currently not available. Please check back later. Thank you.');
        }
    }

    public function getElectricity(Product $product)
    {
        try {
            $listelectricty = $this->baseUrl() . '/api/v2/electricity';
            $response = Http::withHeaders($this->header())->get($listelectricty);
            if ($response->successful()) {
                $electricity = $response->json()['data'];
                $provider = Electricity::select('id', 'reseller_commission', 'provider')->where('status', '0')->get();
                return view('dashboard.agent.products.electricity.list', compact('electricity', 'product', 'provider'));
            } else {
                return redirect()->back()->with('status', $response->json()['error'][0]['msg']);
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to connect to the API. Please check your internet connection and try again later.');
        }
    }
    public function store(Request $request)
    {
        $validatedData = $request->validate([
            'provider' => 'required|string',
            'commission' => 'required|string',
            'reseller_commission' => 'required|string',
            'status' => 'sometimes',
        ]);
        $provider = $validatedData['provider'];
        unset($validatedData['provider']);
        $dataPlan = Electricity::firstOrNew(['provider' => $provider]);
        $dataPlan->fill($validatedData);
        $dataPlan->save();
        return redirect()->back()->with('status', 'Commission % Updated');
    }

    public function valida(Request $request)
    {
        $body = [
            'type' => $request->get('type'),
            'meterNo' => $request->get('meterNo'),
            'disco' => $request->get('disco'),
            'amount' => $request->get('amount'),
            'phone' => $request->get('phone'),
        ];
        $power = [
            'type' => $request->get('type'),
            'disco' => $request->get('disco'),
            'meterNo' => $request->get('meterNo'),

        ];

        $amount = $request->get('amount');
        // check if the user wallet balance is sufficient
        $user = auth()->user();
        $userBalance = $user->wallet->balance;
        if ($userBalance < $amount) {
            return redirect()->route('fund.index')->with('error', 'Insufficient fund. Kindly fund your wallet and try again!');
        }

        try {
            $validation = $this->baseUrl() . '/api/v2/electricity/validate';
            $response = Http::withHeaders($this->header())->post($validation, $power);
            if ($response->successful()) {
                $validated = $response->json()['data'];
                info($validated);

                return view('dashboard.agent.products.electricity.summary', compact('body', 'validated'));
            } else {
                return redirect()->back()->with('error', $response->json()['error'][0]['msg']);
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', $response->json()['error'][0]['msg']);
        }
    }
}