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

namespace App\Http\Controllers;

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

class CableController 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 validat(Request $request)
    {
        $body = [
            'type' => $request->get('type'),
            'smartCardNo' => $request->get('smartCardNo'),
            'productsCode' => $request->get('code'),
            'packagename' => $request->get('name'),
            'price' => $request->get('price'),
            'amount' => $request->get('reseller_price'),
            'month' => $request->get('month'),
        ];

        info($body);

        $amount = $request->get('reseller_price');

        $smartCard = [
            'type' => $request->get('type'),
            'smartCardNo' => $request->get('smartCardNo'),
        ];
        // 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/cables/validate';
            $response = Http::withHeaders($this->header())->post($validation, $smartCard);
            // dd($response->json());

            if ($response->successful()) {
                $validated = $response->json()['data'];
                return view('dashboard.agent.products.cable.summary', compact('body', 'validated'));
            } else {
                return redirect()->back()->with('error', $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 buyCable(Request $request)
    {
        $body = [
            'type' => $request->get('type'),
            'smartCardNo' => $request->get('smartCardNo'),
            'productsCode' => $request->get('productsCode'),
            'packagename' => $request->get('packagename'),
        ];


        $amount = $request->get('amount');
        $packagename = $request->get('packagename');
        $smartCardNo = $request->get('smartCardNo');

        // 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 to proceed!');
        }

        // Deduct the amount from the user's wallet
        $userWallet = $user->wallet;
        $userWallet->balance -= $amount;
        $userWallet->save();

        try {
            $purchase = $this->baseUrl() . '/api/v2/cables/buy';
            $response = Http::withHeaders($this->header())->post($purchase, $body);
            $info = $response->json();
            info($info);

            if ($response->successful()) {
                // Add Commission to the user
                $cable = Product::where('name', 'cable')->first();
                if ($cable) {
                    $wallet = Wallet::where('user_id', $user->id)->first();
                    if ($wallet) {
                        $fetchValue = $cable->commission;
                        $commissionPercentage = $fetchValue / 100;
                        $newCommission = $commissionPercentage * $amount;
                        $wallet->commission += $newCommission;
                        $wallet->save();
                    } else {
                        $newCommission = 0.25;
                        $wallet->commission += $newCommission;
                        $wallet->save();
                    }
                }

                // extract params
                $reference = $response->json()['data']['reference'];
                $code = $response->json()['data']['code'];

                // 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 = $reference;
                $trans->amount = $amount;
                $trans->commission = $newCommission;
                $trans->status = $code;
                $trans->type = "Cable";
                $trans->network = $packagename;
                $trans->destination = $smartCardNo;
                $trans->user_id = $user->id;
                $trans->save();

                $currentBal = $userBalance - $amount; //Calculate the 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 = "Cable Purchase";
                $walletHistory->user_id = $user->id;
                $walletHistory->save();

                return redirect(route('product.cable.package'))->with('status', $response->json()['message']);
            } else {
                // Credit Back the amount to the user's wallet
                $userWallet = $user->wallet;
                $userWallet->balance += $amount;
                $userWallet->save();

                $errorMessages = '';
                foreach ($info['error'] as $error) {
                    $errorMessage = $error['msg'];
                    $errorMessages .= $errorMessage . ' '; // You can adjust the format as needed
                }
                return redirect(route('dashboard'))->with('error', $errorMessages);
            }
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Cable Provider currently not available. Please check back later.');
        }
    }

    public function store(Request $request)
    {
        try {
            $validatedData = $request->validate([
                'reseller_price' => 'required|string',
                'name' => 'required|string',
                'code' => 'required|string',
                'month' => 'required|string',
                'price' => 'required|string',
                'type' => 'required|string',
            ]);
            $code = $validatedData['code'];
            unset($validatedData['code']);
            $cablePackage = Cable::firstOrNew(['code' => $code]);
            $cablePackage->fill($validatedData);
            $cablePackage->save();

            return redirect()->back()->with('status', 'Cable Package Updated');
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'An error occurred while saving the cable package.');
        }
    }



    public function getCablePackage(Product $product)
    {
        try {
            $packages = $this->baseUrl() . '/api/v2/cables';
            $response = Http::withHeaders($this->header())->get($packages);
            // info($response->json());
            if ($response->successful()) {
                $gotv = $response->json()['data']['gotv'] ?? []; // for Gotv
                $dstv = $response->json()['data']['dstv'] ?? [];  // for dstv
                $startimes = $response->json()['data']['startimes'] ?? []; // startimes
            }
            return view('dashboard.agent.products.cable.cable_package', compact('product', 'gotv', 'dstv', 'startimes'));
        } catch (\Exception $e) {
            return redirect()->back()->with('error', 'Failed to connect to the API. Please check your internet connection and try again later.');
        }
    }
}