<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\AdminThirdPartySignageController;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\AdminRole;
use App\Models\Apphistory;
use App\Models\AppHistoryFirstPartyTemporaryAds;
use App\Models\AppHistoryMobile;
use App\Models\AppHistorySmallFormatDetails;
use App\Models\ThirdPartyOutdoorSignDetails;
use App\Models\AppHistoryStreetLamp;
use App\Models\AppHistoryThirdPartyOutdoor;
use App\Models\FirstPartyTemporaryAds;
use App\Models\FirstPartyTemporaryAdsDetails;
use App\Models\kycdetail;
use App\Models\KycThirdParty;
use App\Models\KycThirdPartyFirstApprovalSequence;
use App\Models\KycThirdPartyPayment;
use App\Models\mobilead;
use App\Models\MobileAdsVehicleLicense;
use App\Models\MobilePayment;
use App\Models\onpremise;
use App\Models\OnpremiseInfo;
use App\Models\PaymentFirstPartyTemporaryAds;
use App\Models\PaymentOnPremise;
use App\Models\PaymentSmallFormatAds;
use App\Models\PaymentStreetLamp;
use App\Models\PaymentThirdPartyMobile;
use App\Models\PaymentThirdPartyOutdoorSignage;
use App\Models\PermitStepMobile;
use App\Models\PermitStepOnpremise;
use App\Models\PermitStepOutdoor;
use App\Models\PermitStepStreetLamp;
use App\Models\SmallFormatAds;
use App\Models\SmallFormatDetails;
use App\Models\StreetLampInfo;
use App\Models\StreetLampsAds;
use App\Models\ThirdPartyMobile;
use App\Models\ThirdPartyMobileAppHistory;
use App\Models\ThirdPartyMobilePermitStep;
use App\Models\ThirdPartyOutdoor;
use App\Models\ThirdPartyUpgradeAndDowngrade;
use App\Models\User;
use App\Models\UserWallet;
use App\Models\ThirdPartyReceipts;
use App\Models\SmallFormatReceipts;
use App\Models\FirstPartyTemporaryReceipts;
use App\Models\KycThirdPartyPricing;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use js\tools\numbers2words\Speller;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class PaymentController extends Controller   {
    //
    public function __construct(AdminThirdPartySignageController $adminThirdPartySignageController) {
        $this->adminThirdPartySignageController = $adminThirdPartySignageController;
        $this->middleware('auth:api', ['except' => ['setPaymentReferencePaystack']]);
    }

    public function mobileAdsPayment($mobileId) {

        $getPaymentInfo = AppHistoryMobile::where('mobilead_id', $mobileId)->get()->last();
        $getPaymentFee = ceil((float)$getPaymentInfo['ads_price']);
        if($getPaymentFee <= 133333.33) {
            $chargeFee =  (2 / 100) * $getPaymentFee;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total Fee' => $getPaymentFee, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('MOBILE_BRANDING_BACK') ], 200);
    }

    public function thirdPartyMobilePayment($mobileId) {

        $getPaymentInfo = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $mobileId)->get()->last();
        $getPaymentFee = ceil((float)$getPaymentInfo['ads_price']);
        if($getPaymentFee <= 133333.33) {
            $chargeFee = (2 / 100) * $getPaymentFee;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total Fee' =>  $getPaymentFee, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('THIRD_PARTY_BACK')], 200);
    }

    public function streetLampPayment($streetLampId) {

        $getPermitFee = StreetLampInfo::where('street_lamps_ads_id', $streetLampId)->sum('permit_price');
        $getAdministrativeFee = StreetLampInfo::where('street_lamps_ads_id', $streetLampId)->sum('administrative_price');
        $totalFeeForStreetLamp = ceil($getPermitFee + $getAdministrativeFee);
        if($totalFeeForStreetLamp <= 133333.33) {
            $chargeFee = (2 / 100) * $totalFeeForStreetLamp;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['PermitFee' => $getPermitFee, 'AdmininstrativeFee' => $getAdministrativeFee,
            'Total Fee' => $totalFeeForStreetLamp, 'ChargeFee' => $chargeFee,  'additionalInfo' => env('STREETLAMPPOLES_BACK') ], 200);
    }

    public function outdoorSignagePayment($outdoorId) {

        $getOutdooorObj = ThirdPartyOutdoor::find($outdoorId);
        if($getOutdooorObj->bill_generated) {
            $getPrice = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $getOutdooorObj->id)->latest()->first();
            $getAdsPrice = $getPrice->ads_price;
            $getLegalFee = $getPrice->legal_fee;
            $totalFee = bcadd($getAdsPrice, $getLegalFee, 2);
            Log::Info(['check total' => $totalFee]);
            if ($totalFee <= 133333.33) {
                $chargeFee = (2/100) * $totalFee;
            } else {
                $chargeFee = 2000;
            }
            return response()->json(['PermitFee' => $getAdsPrice, 'LegalFee' => $getLegalFee, 'ChargeFee' => $chargeFee,
                'Total' => (float)$totalFee, 'additionalInfo' => getenv('THIRD_PARTY_BACK'), 'first_pay' => $getOutdooorObj->first_permit_pay], 200);
         } else {
            return response()->json(['success' => false, 'data' => 'Bill has not be generated for the outdoor signage'], 422);
        }
    }

    public function getArrearsforOutdoor($outdoorId) {

        $getOutdooorObj = ThirdPartyOutdoor::find($outdoorId);
        if($getOutdooorObj->bill_generated ) {
            $getPrice = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $getOutdooorObj->id)->get()->last();

            if($getPrice->balance !== null || 0) {
                    $getArrears = $getPrice->balance;
                if ($getArrears <= 133333.33) {
                    $chargeFee = (2 / 100) * $getArrears;
                } else {
                    $chargeFee = 2000;
                }
                return response()->json(['ChargeFee' => $chargeFee,
                    'Total' => $getArrears, 'additionalInfo' => getenv('THIRD_PARTY_BACK')], 200);
            } else {
                return response()->json(['success' => false, 'data' => 'No arrears available for the outdoor signage'], 422);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'Bill has not be generated for the outdoor signage'], 422);
        }
    }
    
    public function getBulkArrearsforOutdoor() {
        
        $userId  = Auth::user()->id;
        $getOutdooor = ThirdPartyOutdoor::where('user_id', $userId)->where('permit_pay_status', 'paid')->where('hod_bill_generate', 'approved')->pluck('id')->toArray();
        $count = count($getOutdooor) - 1;
        $getArrears = [];
        
        for($i=0; $i <= $count; $i++) {
            $getOutdooorObj = ThirdPartyOutdoor::find($getOutdooor[$i]);
            if($getOutdooorObj->bill_generated) {
                $getPrice = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $getOutdooorObj->id)->get()->last();
    
                if($getPrice->balance !== null || 0) {
                        $getArrears [] = $getPrice->balance;
                    
                    
                } else {
                    $getArrears [] = 0;
                }
            
            } else {
                return response()->json(['success' => false, 'data' => 'Bill has not be generated for the outdoor signage'], 422);
            }
        }
        $getallArrears = array_sum(array_map('intval', $getArrears));
        
        // if($getallArrears > 80000000){
        //         $getallArrears = 80000000;
        //     }
            
        if ($getallArrears <= 133333.33) {
            $chargeFee = (2 / 100) * $getallArrears;
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['success' => true, 'ChargeFee' => $chargeFee,
                'total_price' => $getallArrears, 'additionalInfo' => getenv('THIRD_PARTY_BACK'), 'applicationId' => $getOutdooor], 200);
    }

    public function getSmallFormatDetailsArrears($smallFormatDetails) {

        $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetails);

        $getAppHistory = AppHistorySmallFormatDetails::where('small_format_details_id', $getSmallFormatDetailsObj->id)->get()->last();
        $getAdsPrice = $getAppHistory->balance;
        $counter = $getAppHistory->payment_counter;

        if($getAdsPrice <= 133333.33) {
            $chargeFee = (2/100) * $getAdsPrice;
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total' => $getAdsPrice, 'ChargeFee' => $chargeFee, 'counter' => $counter,
            'additionalInfo' => env('THIRD_PARTY_BACK'), 'first_pay' => $getSmallFormatDetailsObj->first_permit_pay], 200);
    }
    
    public function getBulkSmallFormatDetailsArrears() {
        
        $userId  = Auth::user()->id;
        $getSmallFormatads = SmallFormatAds::where('user_id', $userId)->pluck('id')->toArray();
        $count = count($getSmallFormatads) - 1;
        $getArrears = [];
        $counter = [];
        $firstPermitPay = [];
        
        for($i=0; $i <= $count; $i++) {
            $getSmallFormatDetailsObj = SmallFormatDetails::where('small_format_ads_id', $getSmallFormatads[$i])->get();
            foreach($getSmallFormatDetailsObj as $getSmallFormatDetails){
                
            
                if($getSmallFormatDetails->final_bill_generated == "approved") {
                    $getPrice = AppHistorySmallFormatDetails::where('small_format_details_id', $getSmallFormatDetails->id)->get()->last();
        
                    if($getPrice->balance !== null || 0) {
                            $getArrears [] = $getPrice->balance;
                            $counter [] = $getPrice->payment_counter;
                            $firstPermitPay [] = $getSmallFormatDetails->first_permit_pay;
                        
                        
                    } else {
                        $getArrears [] = 0;
                    }
                
                }
            }
        }
        $getallArrears = array_sum(array_map('intval', $getArrears));
        
        // if($getallArrears > 80000000){
        //         $getallArrears = 80000000;
        //     }
            
        if ($getallArrears <= 133333.33) {
            $chargeFee = (2 / 100) * $getallArrears;
        } else {
            $chargeFee = 2000;
        }
                
        return response()->json(['success' => true, 'total_price' => $getallArrears, 'ChargeFee' => $chargeFee, 'counter' => $counter,
            'additionalInfo' => env('THIRD_PARTY_BACK'), 'first_pay' => $firstPermitPay, 'applicationId' => $getSmallFormatads], 200);
    }

    public function firstPartyTemporaryAds($temporaryId) {

        $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
        $getPaymentInfo = AppHistoryFirstPartyTemporaryAds::where('first_party_temporary_ads_id', $temporaryObj->id)->get()->last();
        $getAdsFee = $getPaymentInfo->ads_price;

        if($getAdsFee <= 133333.33) {
            $chargeFee = (2/ 100) * $getAdsFee;
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total' => $getAdsFee, 'ChargeFee' => $chargeFee, 'additionalInfo' => env('THIRD_PARTY_BACK')], 200);
    }

    public function onpremisePayment($onpremiseId) {

        $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremiseId)->get()->last();
        $getOnPremiseFee = ceil($getOnpremiseInfo['balance']);
        if($getOnPremiseFee <= 133333.33) {
            $chargeFee = (2 / 100) * $getOnPremiseFee;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total Fee' =>$getOnPremiseFee, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('ONPREMISE_BACK')]);
    }
    
    
    public function bulkOnpremisePermitFeepayment(){
        $userId  = Auth::user()->id;
        $getonPremise = onpremise::where('user_id', $userId)->where('audit_status', 'approved')->pluck('id')->toArray();
        
        $countDetails = count($getonPremise) - 1;
        $totalprice = [];
        for($i=0; $i <= $countDetails; $i++) {
            
        
            
            $totalbalance = Apphistory::where('onpremise_id', $getonPremise[$i])->get()->last();
            if($totalbalance['balance'] > 0){
                $totalprice [] = $totalbalance['balance'];
            }else{
                $totalprice [] = 0;
            }
            
        }
            $totalSum = array_sum(array_map('intval', $totalprice));
            $totalSum = ceil($totalSum);
            
            if($totalSum <= 133333.33) {
                $chargeFee = (2 / 100) * $totalSum;
                $chargeFee = ceil($chargeFee);
            } else {
                $chargeFee = 2000;
            }
            
            return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
                'additionalInfo' => env('ONPREMISE_BACK'), 'applicationId' => $getonPremise], 200);
    }
    

    public function kycThirdPartyPayment($kycThirdPartyId) {

        $getKycObj = KycThirdParty::find($kycThirdPartyId);
        $appprice = KycThirdPartyPricing::find(1);
        $totalFee = $appprice->permit_fee;
        $chargeFee = 2000;

        return response()->json(['totalFee' => $totalFee, 'ChargeFee' => $chargeFee, 'additionalInfo' => getenv('THIRD_PARTY_BACK')], 200);
    }

    public function smallFormatDetailsPayment($smallFormatDetailsId) {
        $getSmallFormatObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);

        if(is_null($getSmallFormatObj)) {
            return response()->json(['success' => false, 'data' => 'Small Format Details does not exist'], 422);
        }

        $getAdPrice = $getSmallFormatObj->ads_price;
        if($getAdPrice <= 133333.33) {
            $chargeFee = (2/100) * $getAdPrice;
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['Total' => $getAdPrice, 'ChargeFee' => $chargeFee, 'additionalInfo' => env('THIRD_PARTY_BACK')], 200);
    }

    public function setAdsPaymentInfo(Request $request) {

        $validate = Validator::make($request->all(), [
            'type_ads' => 'required|string|in:StreetLamp,Mobile,ThirdPartyMobile,Onpremise, expressionApplication, expressionPayment',
            'reference_id' => 'required|string',
            'payment_id' => 'required|string',
            'payment_type' => 'required|string|in:Paystack,Wallet'
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }


        $setPaymentForm =  $request->all();
        $userId = Auth::user()->id;
        $userEmail = Auth::user()->email;

        if($setPaymentForm['payment_type'] == 'Wallet') {
            if($setPaymentForm['type_ads'] == 'StreetLamp'){

                $getSteetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->get();
                $getPermitFee = StreetLampInfo::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->sum('permit_price');
                $getAdministrativeFee = StreetLampInfo::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->sum('administrative_price');
                $totalSum = round($getPermitFee + $getAdministrativeFee);
                $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->get();
                $applicationPurpose = $appHistoryLamp[0]['purpose'];

                $getwallet = UserWallet::where('user_id', $userId)->get();
                $getTotalBalance = $getwallet[0]['balance'];
                $getWalletAdmin = $getwallet[0]['streetlamp_administrative_balance'];
                $getWalletProcess = $getwallet[0]['streetlamp_processing_balance'];
                $paymentType = Str::lower($setPaymentForm['payment_type']);

                if($getWalletProcess  >= $getPermitFee && $getWalletAdmin >= $getAdministrativeFee) {

                    $newProcessingBalance = $getWalletProcess - $getPermitFee;
                    $newAdminBalance = $getWalletAdmin - $getAdministrativeFee;
                    $newTotalBalance = $getTotalBalance - $totalSum;
                    $getStreetLampObj  = StreetLampsAds::find($getSteetLamp[0]['id']);
                    $paymentInfo = new PaymentStreetLamp();
                    $paymentStatus = 'Successful payment';
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $paymentInfo->payment_type = $paymentType;
                    $getUser = User::find($userId);
                    $response = $getUser->payment()->save($paymentInfo);
                    $setStreetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'permit_payment_status' => 'paid', 'legal_status' => 'pending']);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalBalance,
                        'streetlamp_processing_balance' => $newProcessingBalance, 'streetlamp_administrative_balance' => $newAdminBalance ]);
                    $currentStep = AdminRole::where('id', 6)->get();
                    $permitStep = new PermitStepStreetLamp();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $getStreetLampObj->permitStepStreetLamp()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                }  else {
                    return response()->json(['error' => 'Insufficient wallet balance'], 422);
                }
            } elseif ($setPaymentForm['type_ads'] == 'Mobile') {

                $getMobile = mobilead::where('payment_id', $setPaymentForm['payment_id'])->get();
                $total = AppHistoryMobile::where('mobilead_id', $getMobile[0]['id'])->get()->last();
                $getMobileId = $getMobile[0]['id'];
                $appHistoryThirdPartyMobile = AppHistoryMobile::where('mobilead_id', $getMobile[0]['id'])->get();
                $applicationPurpose = $appHistoryThirdPartyMobile[0]['purpose'];
                $totalSum = $total->ads_price;

                $getwallet = UserWallet::where('user_id', $userId)->get();
                $getWalletBalance = $getwallet[0]['mobile_balance'];
                $getTotalBalance = $getwallet[0]['balance'];
                $paymentType = Str::lower($setPaymentForm['payment_type']);

                if($getWalletBalance  >= $totalSum) {

                    $newWalletBalance = $getWalletBalance - $totalSum;
                    $newTotalBalance = $getTotalBalance - $totalSum;
                    $paymentStatus = 'Successful payment';
                    $mobileObj = mobilead::find($getMobile[0]['id']);
                    $paymentInfo = new MobilePayment();
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $paymentInfo->payment_type = $paymentType;
                    $getUser = User::find($userId);
                    $response = $getUser->mobilePayment()->save($paymentInfo);
                    $setStreetLamp = mobilead::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'hod_permit_status' => 'approved', 'legal_status' => 'approved', 'final_status' => 'approved']);
                    $this->sendDetailsforQrcode($getMobileId);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalBalance,
                        'mobile_balance' =>  $newWalletBalance]);
                    $currentStep = AdminRole::where('id', 5)->get();
                    $permitStep = new PermitStepMobile();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $mobileObj->permitStepMobile()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                } else {
                    return response()->json(['error' => 'Insufficient wallet balance'], 422);
                }
            } elseif ($setPaymentForm['type_ads'] == 'ThirdPartyMobile') {

                $getThirdPartyMobile = ThirdPartyMobile::where('payment_id', $setPaymentForm['payment_id'])->get();
                $total = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $getThirdPartyMobile[0]['id'])->get()->last();
                $appHistoryThirdPartyMobile = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $getThirdPartyMobile[0]['id'])->get();
                $applicationPurpose = $appHistoryThirdPartyMobile[0]['purpose'];
                $totalSum = $total->ads_price;

                $getwallet = UserWallet::where('user_id', $userId)->get();
                $getWalletBalance = $getwallet[0]['pav_balance'];
                $getTotalBalance = $getwallet[0]['balance'];
                $paymentType = Str::lower($setPaymentForm['payment_type']);

                if($getWalletBalance  >= $totalSum) {

                    $newWalletBalance = $getWalletBalance - $totalSum;
                    $newTotalBalance = $getTotalBalance - $totalSum;
                    $paymentStatus = 'Successful payment';
                    $thirdPartyObj = ThirdPartyMobile::find($getThirdPartyMobile[0]['id']);
                    $paymentInfo = new PaymentThirdPartyMobile();
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->payment_type = $paymentType;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $getUser = User::find($userId);
                    $response = $getUser->paymentThirdPartyMobile()->save($paymentInfo);
                    $setStreetLamp = ThirdPartyMobile::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'legal_status' => 'pending']);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalBalance, 'pav_balance' => $newWalletBalance]);
                    $currentStep = AdminRole::where('id', 6)->get();
                    $permitStep = new ThirdPartyMobilePermitStep();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $thirdPartyObj->thirdPartyMobilePermitStep()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                }  else {
                    return response()->json(['error' => 'Insufficient wallet balance'], 422);
                }
            }  elseif ($setPaymentForm['type_ads'] == 'Onpremise') {
                $getOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->get();
                $getAdPriceFee = Apphistory::where('onpremise_id', $getOnpremise[0]['id'])->get()->last();
                $totalSum = round($getAdPriceFee->ads_price);
                $applicationPurpose = $getAdPriceFee->purpose;

                $getwallet = UserWallet::where('user_id', $userId)->get();
                $getWalletBalance = $getwallet[0]['balance'];
                $paymentType = Str::lower($setPaymentForm['payment_type']);

                if($getWalletBalance  >= $totalSum) {

                    $newWalletBalance = $getWalletBalance - $totalSum;
                    $paymentStatus = 'Successful payment';

                    $getOnpremiseObj  = onpremise::find($getOnpremise[0]['id']);
                    $paymentInfo = new PaymentOnPremise();
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $paymentInfo->payment_type = $paymentType;
                    $getUser = User::find($userId);
                    $response = $getUser->paymentOnpremise()->save($paymentInfo);
                    $setOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'legal_status' => 'pending',  'final_status' => 'approved']);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newWalletBalance]);
                    $currentStep = AdminRole::where('id', 6)->get();
                    $permitStep = new PermitStepOnpremise();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $getOnpremiseObj->permitStepOnpremise()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                } else {
                    return response()->json(['error' => 'Insufficient wallet balance'], 422);
                }
            }
        }


//        elseif ($setPaymentForm['payment_type'] == 'Paystack') {
//            if ($setPaymentForm['type_ads'] == 'StreetLamp') {
//                $getSteetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->get();
//                // $totalSum = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->first();
//                $getPermitFee = StreetLampInfo::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->sum('permit_price');
//                $getAdministrativeFee = StreetLampInfo::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->sum('administrative_price');
//                $totalSum = round($getPermitFee + $getAdministrativeFee);
//                $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->get();
//                $applicationPurpose = $appHistoryLamp[0]['purpose'];
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('STREETLAMPPOLES_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
//                    // var_dump($data); die();
//                    //$newamount = $totalSum * 100;
//                    $totalSum = ceil($totalSum);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//                    // var_dump($userEmail, $newamount);die();
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $refcheck = paymentStreetLamp::where('reference_id', $reference)->exists();
//
//                    if ($refcheck) {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//                $getStreetLampObj = StreetLampsAds::find($getSteetLamp[0]['id']);
//                $paymentInfo = new PaymentStreetLamp();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($userId);
//                $response = $getUser->payment()->save($paymentInfo);
//                $setStreetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                    'permit_payment_status' => 'paid',  'legal_status' => 'pending']);
//                $currentStep = AdminRole::where('id', 6)->get();
//                $permitStep = new PermitStepStreetLamp();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $getStreetLampObj->permitStepStreetLamp()->save($permitStep);
//                return response()->json(['data' => $response], 200);
//            } elseif ($setPaymentForm['type_ads'] == 'ThirdPartyMobile') {
//                $getThirdPartyMobile = ThirdPartyMobile::where('payment_id', $setPaymentForm['payment_id'])->get();
//                $totalSum = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $getThirdPartyMobile[0]['id'])->get()->last();
//                $appHistoryThirdPartyMobile = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $getThirdPartyMobile[0]['id'])->get();
//                $applicationPurpose = $appHistoryThirdPartyMobile[0]['purpose'];
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum->ads_price) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('THIRD_PARTY_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
////                      var_dump($data); die();
////                    $menmount = round($totalSum->ads_price);
////                    $newamount = $menmount * 100;
//                    $totalSum = ceil($totalSum->ads_price);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//                    // var_dump($newamount); die();
//
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//                $thirdPartyObj = ThirdPartyMobile::find($getThirdPartyMobile[0]['id']);
//                $paymentInfo = new PaymentThirdPartyMobile();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($userId);
//                $response = $getUser->paymentThirdPartyMobile()->save($paymentInfo);
//                $setStreetLamp = ThirdPartyMobile::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                    'legal_status' => 'pending']);
//                $currentStep = AdminRole::where('id', 6)->get();
//                $permitStep = new ThirdPartyMobilePermitStep();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $thirdPartyObj->thirdPartyMobilePermitStep()->save($permitStep);
//                return response()->json(['data' => $response], 200);
//            } elseif ($setPaymentForm['type_ads'] == 'Mobile') {
//                $getMobile = mobilead::where('payment_id', $setPaymentForm['payment_id'])->get();
//                $totalSum = AppHistoryMobile::where('mobilead_id', $getMobile[0]['id'])->get()->last();
//                $getMobileId = $getMobile[0]['id'];
//                $appHistoryThirdPartyMobile = AppHistoryMobile::where('mobilead_id', $getMobile[0]['id'])->get();
//                $applicationPurpose = $appHistoryThirdPartyMobile[0]['purpose'];
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum->ads_price) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('MOBILE_BRANDING_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
////                      var_dump($data); die();
////                    $menmount = round($totalSum->ads_price);
////                    $newamount = $menmount * 100;
//                    $totalSum = ceil($totalSum->ads_price);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//                $mobileObj = mobilead::find($getMobile[0]['id']);
//                $paymentInfo = new MobilePayment();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($userId);
//                $response = $getUser->mobilePayment()->save($paymentInfo);
//                $setStreetLamp = mobilead::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                    'hod_permit_status' => 'approved', 'legal_status' => 'approved',  'final_status' => 'approved']);
//                $this->sendDetailsforQrcode($getMobileId);
//                $currentStep = AdminRole::where('id', 5)->get();
//                $permitStep = new PermitStepMobile();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $mobileObj->permitStepMobile()->save($permitStep);
//                return response()->json(['data' => $response], 200);
//            } elseif ($setPaymentForm['type_ads'] == 'Onpremise') {
//
//                $getOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->get();
//                // $totalSum = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->first();
//                $getAdPriceFee = Apphistory::where('onpremise_id', $getOnpremise[0]['id'])->get()->last();
//                $totalSum = round($getAdPriceFee->ads_price);
//
//                $applicationPurpose = $getAdPriceFee->purpose;
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('ONPREMISE_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
//                    // var_dump($data); die();
////                    $newamount = $totalSum * 100;
//                    $totalSum = ceil($totalSum);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//                    // var_dump($userEmail, $newamount);die();
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $refcheck = paymentStreetLamp::where('reference_id', $reference)->exists();
//
//                    if ($refcheck) {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//                $getOnpremiseObj = onpremise::find($getOnpremise[0]['id']);
//                $paymentInfo = new PaymentOnPremise();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($userId);
//                $response = $getUser->paymentOnpremise()->save($paymentInfo);
//                $setOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                 'legal_status' => 'pending',   'final_status' => 'approved']);
//                $currentStep = AdminRole::where('id', 6)->get();
//                $permitStep = new PermitStepOnpremise();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $getOnpremiseObj->permitStepOnpremise()->save($permitStep);
//                return response()->json(['data' => $response], 200);
//            }
//        }
    }

    public function setPaymentReferencePaystack() {
        Log::info("This is to check Paystack");

//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();

        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('MOBILE_BRANDING_BACKSTREET'));
        //define('PAYSTACK_SCRET_KEY', getenv('MOBILE_BRANDING_FORWARDSTREET'));

//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
        Log::info("Permit payment webhook");
        http_response_code(200);
        $event = json_decode($input);
        // Log::info(json_encode($event));

        if($event->data->status == 'success') {
            if($event->data->metadata->paymentFor == 'Permit Bill') {
                if ($event->data->metadata->appType == 'Mobile') {
                    $mobileObj = mobilead::find($event->data->metadata->applicationId);
                    $appHistoryMobile = AppHistoryMobile::where('mobilead_id', $mobileObj->id)->get();
                    $applicationPurpose = $appHistoryMobile[0]['purpose'];

                    $amountpaid = ($event->data->amount) / 100;
                    $reference = $event->data->reference;

                    $paymentInfo = new MobilePayment();
                    $paymentInfo->amount_paid = $amountpaid;
                    $paymentInfo->reference_id = $reference;
                    $paymentInfo->payment_id = $mobileObj->payment_id;
                    $paymentInfo->status = $event->data->status;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $getUser = User::find($mobileObj->user_id);
                    $response = $getUser->mobilePayment()->save($paymentInfo);
                    $setStreetLamp = mobilead::where('payment_id', $mobileObj->payment_id)->update(['hod_permit_status' => 'approved', 'legal_status' => 'approved',  'final_status' => 'approved']);
                    $this->sendDetailsforQrcode($mobileObj->id);
                    $currentStep = AdminRole::where('id', 5)->get();
                    $permitStep = new PermitStepMobile();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $mobileObj->permitStepMobile()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'StreetLamp') {
                    $streetLampObj = StreetLampsAds::find($event->data->metadata->applicationId);
                    $appHistoryMobile = AppHistoryStreetLamp::where('street_lamps_ads_id', $streetLampObj->id)->get();
                    $applicationPurpose = $appHistoryMobile[0]['purpose'];

                    $amountpaid = ($event->data->amount) / 100;
                    $reference = $event->data->reference;

                    $paymentInfo = new PaymentStreetLamp();
                    $paymentInfo->amount_paid = $amountpaid;
                    $paymentInfo->reference_id = $reference;
                    $paymentInfo->payment_id = $streetLampObj->payment_id;
                    $paymentInfo->status = $event->data->status;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $getUser = User::find($streetLampObj->user_id);
                    $response = $getUser->payment()->save($paymentInfo);
                    $setStreetLamp = StreetLampsAds::where('payment_id', $streetLampObj->payment_id)->update(['Application_pay_status' => 'paid',
                        'permit_payment_status' => 'paid',  'legal_status' => 'pending']);
                    $currentStep = AdminRole::where('id', 6)->get();
                    $permitStep = new PermitStepStreetLamp();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $streetLampObj->permitStepStreetLamp()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'ThirdPartyMobile') {
                    $thirdPartyMobileObj = ThirdPartyMobile::find($event->data->metadata->applicationId);
                    $appHistoryMobile = ThirdPartyMobileAppHistory::where('third_party_mobile_id', $thirdPartyMobileObj->id)->get();
                    $applicationPurpose = $appHistoryMobile[0]['purpose'];

                    $amountpaid = ($event->data->amount) / 100;
                    $reference = $event->data->reference;

                    $paymentInfo = new PaymentThirdPartyMobile();
                    $paymentInfo->amount_paid = $amountpaid;
                    $paymentInfo->reference_id = $reference;
                    $paymentInfo->payment_id = $thirdPartyMobileObj->payment_id;
                    $paymentInfo->status = $event->data->status;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $getUser = User::find($thirdPartyMobileObj->user_id);
                    $response = $getUser->paymentThirdPartyMobile()->save($paymentInfo);
                    ThirdPartyMobile::where('payment_id', $thirdPartyMobileObj->payment_id)->update(['Application_pay_status' => 'paid',
                        'legal_status' => 'pending']);
                    $currentStep = AdminRole::where('id', 6)->get();
                    $permitStep = new ThirdPartyMobilePermitStep();
                    $permitStep->purpose = $applicationPurpose;
                    $permitStep->current_steps = $currentStep[0]['role'];
                    $thirdPartyMobileObj->thirdPartyMobilePermitStep()->save($permitStep);
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'Onpremise') {
                    
                    $applid = $event->data->metadata->applicationId;
                    if(is_array($applid)){
                        
                        $count = count($applid) - 1;
                        // Log::info(json_encode($applid));
                        
                        for($i=0;  $i<=$count;  $i++) {
                            
                            $onpremiseObj = onpremise::find($applid[$i]);
                            $appHistoryMobile = Apphistory::where('onpremise_id', $onpremiseObj->id)->get()->last();
                            if($appHistoryMobile['balance'] > 0){
                                
                                $applicationPurpose = $appHistoryMobile['purpose'];
                                
                                $amountpaid = $appHistoryMobile['balance'];
                                $reference = $event->data->reference;
                                // $theupdate = Apphistory::where('onpremise_id', $onpremiseObj->id)->latest('created_at')->first();
                                $theupdate = Apphistory::where('onpremise_id', $onpremiseObj->id)->get()->last();
                                if($theupdate->balance > 0){
                                    $theupdate->balance -= $amountpaid;
                                    $theupdate->save();  
                                }
                                
                                $paymentInfo = new PaymentOnPremise();
                                $paymentInfo->amount_paid = $amountpaid;
                                $paymentInfo->reference_id = $reference;
                                $paymentInfo->payment_id = $onpremiseObj->payment_id;
                                $paymentInfo->status = $event->data->status;
                                $paymentInfo->application_purpose = $applicationPurpose;
                                $getUser = User::find($onpremiseObj->user_id);
                                $response = $getUser->paymentOnpremise()->save($paymentInfo);
                                $setOnpremise = onpremise::where('payment_id', $onpremiseObj->payment_id)->update(['Application_pay_status' => 'paid',
                                    'legal_status' => 'approved',   'final_status' => 'approved']);
                                $currentStep = AdminRole::where('id', 6)->get();
                                $permitStep = new PermitStepOnpremise();
                                $permitStep->purpose = $applicationPurpose;
                                $permitStep->current_steps = $currentStep[0]['role'];
                                $onpremiseObj->permitStepOnpremise()->save($permitStep);
                            }
                        }
                        
                    }else{
                        
                        $onpremiseObj = onpremise::find($event->data->metadata->applicationId);
                        $appHistoryMobile = Apphistory::where('onpremise_id', $onpremiseObj->id)->get()->last();
                        $applicationPurpose = $appHistoryMobile['purpose'];
                        
                        $amountpaid = ($event->data->metadata->permitFee);
                        $reference = $event->data->reference;
                        // $theupdate = Apphistory::where('onpremise_id', $onpremiseObj->id)->latest('created_at')->first();
                        $theupdate = Apphistory::where('onpremise_id', $onpremiseObj->id)->get()->last();
                        $theupdate->balance -= $amountpaid;
                        $theupdate->save();
    
                        $paymentInfo = new PaymentOnPremise();
                        $paymentInfo->amount_paid = $amountpaid;
                        $paymentInfo->reference_id = $reference;
                        $paymentInfo->payment_id = $onpremiseObj->payment_id;
                        $paymentInfo->status = $event->data->status;
                        $paymentInfo->application_purpose = $applicationPurpose;
                        $getUser = User::find($onpremiseObj->user_id);
                        $response = $getUser->paymentOnpremise()->save($paymentInfo);
                        $setOnpremise = onpremise::where('payment_id', $onpremiseObj->payment_id)->update(['Application_pay_status' => 'paid',
                            'legal_status' => 'approved',   'final_status' => 'approved']);
                        $currentStep = AdminRole::where('id', 6)->get();
                        $permitStep = new PermitStepOnpremise();
                        $permitStep->purpose = $applicationPurpose;
                        $permitStep->current_steps = $currentStep[0]['role'];
                        $onpremiseObj->permitStepOnpremise()->save($permitStep);
                        
                    }
                    
                    
                    
                    
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'OutDoor Site') {
                    $applid = $event->data->metadata->applicationId;
                    if(is_array($applid)){
                        $count = count($applid) - 1;
                        Log::info(json_encode($applid));
                        for($i=0;  $i<=$count;  $i++) {
                            $thirdPartyOutdoorObj = ThirdPartyOutdoor::find($applid[$i]);
                            $appHistoryMobile = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $thirdPartyOutdoorObj->id)->get()->last();
                            $applicationPurpose = $appHistoryMobile['purpose_application'];
                            if($appHistoryMobile->balance !== null || 0) {
                                $amountpaid = $appHistoryMobile->balance;
                                
                                
                            
                                // Log::Info("Out door payment");
            
                                // $amountpaid = ($event->data->metadata->permitFee);
                                $reference = $event->data->reference;
                                
            
                                $paymentInfo = new PaymentThirdPartyOutdoorSignage();
                                $paymentInfo->amount_paid = $amountpaid;
                                $paymentInfo->reference_id = $reference;
                                $paymentInfo->payment_id = $thirdPartyOutdoorObj->payment_id;
                                $paymentInfo->status = $event->data->status;
                                $paymentInfo->application_purpose = $applicationPurpose;
                                $getUser = User::find($thirdPartyOutdoorObj->user_id);
                                $response = $getUser->paymentThirdPartyMobile()->save($paymentInfo);
                                $this->calculateOutdoorBalance($thirdPartyOutdoorObj->id, $amountpaid);
                                if($thirdPartyOutdoorObj->ongoing_request == "upgrade" || $thirdPartyOutdoorObj->ongoing_request == "downgrade") {
                                    $getRecord = ThirdPartyUpgradeAndDowngrade::where('third_party_outdoor_id', $thirdPartyOutdoorObj->id)->latest()->first();
                                    if ($getRecord->bill_status == "generated" && !$getRecord->bill_payment_status) {
                                        ThirdPartyUpgradeAndDowngrade::where('id', $getRecord->id)->update(['bill_payment_status' => 'paid']);
                                        ThirdPartyOutdoor::where('id', $thirdPartyOutdoorObj->id)->update(['ongoing_request' => null, 'first_permit_pay' => true]);
                                        $this->adminThirdPartySignageController->sendUpgradeorDowngradeApprovalLetter($thirdPartyOutdoorObj->id, $getRecord->id);
                                    } else {
                                        Log::error('Does not have any ongoing request');
                                    }
                                } else {
                                    ThirdPartyOutdoor::where('id', $thirdPartyOutdoorObj->id)->update(['permit_pay_status' => 'paid', 'first_permit_pay' => true]);
                                }
                                
                                if($thirdPartyOutdoorObj->first_permit_pay == false) {
                                    $getOutdoorObj = ThirdPartyOutdoor::find($thirdPartyOutdoorObj->id);
                                    // $getUpgradeandDowngradeObj = ThirdPartyUpgradeAndDowngrade::find($requestId);
                            
                                    // if(Auth::user()->id == (string)$getOutdoorObj->assigned_officer) {
                                            $userDetails = KycThirdParty::where('user_id', $getOutdoorObj->user_id)->with(['user'])->get();
                                            $getThirdPartyDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getOutdoorObj->id)->get();
                                            $getUpgradeandDowngrade = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getOutdoorObj->id)->get();
                            
                                            $outdoorSignageName = ucwords($getUpgradeandDowngrade[0]['designation']);
                                            $outdoorRequest = "New Application";
                                            $outdoorWidth = $getThirdPartyDetails[0]['breadth_sign'];
                                            $outdoorLength = $getThirdPartyDetails[0]['length_sign'];
                                            $outdoorDimension = $getThirdPartyDetails[0]['dimension_sign'];
                                            $outdoorSide = $getThirdPartyDetails[0]['number_faces'];
                                            $signageSite = $getOutdoorObj->address_proposed_site;
                                            $date = Carbon::parse($getUpgradeandDowngrade[0]['updated_at'])->format('jS F, Y');
                                            $refno = UtilMethods::outdoorRequestAppId();
                                            ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['application_id' => $refno]);
                                            
                            
                                            $data = [
                                                'companyName' => $userDetails[0]['company_name'],
                                                'officeAddress' => $userDetails[0]['office_address'],
                                                'signageId' => $getOutdoorObj->id,
                                                'signageName' => $outdoorSignageName,
                                                'signageWidth' => $outdoorWidth,
                                                'signageHeight' => $outdoorLength,
                                                'signageDimension' => $outdoorDimension,
                                                'signageSide' => $outdoorSide,
                                                'signageDuration' => 'Annual',
                                                'signageRequest' => $outdoorRequest,
                                                'signageSite' => $signageSite,
                                                'appId' => $refno,
                                                'date' => $date
                                            ];
                            
                                            $pdf = Pdf::loadView('outdoorapproval', compact('data'));
                                            $fileObj = $pdf->download('outdoorapproval.pdf');
                            
                                            $getUserObj = User::find($userDetails[0]['user']['id']);
                            
                                            $body = "This is your approval letter for your " . $outdoorSignageName;
                                            $templateData = [
                                                'body' => $body,
                                                'name' => $getUserObj->company_name
                                            ];
                                            $templateContent = view('hodeoitemplate', $templateData)->render();
                                            UtilMethods::outdoorSignageApproval($getUserObj->email, $templateContent, $fileObj);
                                            
                                            $pdfContent = $pdf->output();
                                            $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
                                            $relativePath = 'invoices/' . $filename;
                                            $savePath = public_path($relativePath); // Full path to /public/invoices/
                                        
                                            if (!File::exists(public_path('invoices'))) {
                                                File::makeDirectory(public_path('invoices'), 0755, true);
                                            }
                                            file_put_contents($savePath, $pdfContent);
                                            $fileUrl = config('app.url') . '/public/' . $relativePath;
                                            $adnewrec = new ThirdPartyReceipts();
                                            $adnewrec->link = $fileUrl;
                                            $adnewrec->type = "Letter";
                                            // $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
                                            $thirdPartyOutdoorObj->thirdpartyreceipts()->save($adnewrec);
                                            
                                        
                                }
                            }
                        }
                    }else{
                        $thirdPartyOutdoorObj = ThirdPartyOutdoor::find($event->data->metadata->applicationId);
                        $appHistoryMobile = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $thirdPartyOutdoorObj->id)->get();
                        $applicationPurpose = $appHistoryMobile[0]['purpose_application'];
                        Log::Info("Out door payment");
    
                        $amountpaid = ($event->data->metadata->permitFee);
                        $reference = $event->data->reference;
                        
    
                        $paymentInfo = new PaymentThirdPartyOutdoorSignage();
                        $paymentInfo->amount_paid = $amountpaid;
                        $paymentInfo->reference_id = $reference;
                        $paymentInfo->payment_id = $thirdPartyOutdoorObj->payment_id;
                        $paymentInfo->status = $event->data->status;
                        $paymentInfo->application_purpose = $applicationPurpose;
                        $getUser = User::find($thirdPartyOutdoorObj->user_id);
                        $response = $getUser->paymentThirdPartyMobile()->save($paymentInfo);
                        $this->calculateOutdoorBalance($thirdPartyOutdoorObj->id, $amountpaid);
                        if($thirdPartyOutdoorObj->ongoing_request == "upgrade" || $thirdPartyOutdoorObj->ongoing_request == "downgrade") {
                            $getRecord = ThirdPartyUpgradeAndDowngrade::where('third_party_outdoor_id', $thirdPartyOutdoorObj->id)->latest()->first();
                            if ($getRecord->bill_status == "generated" && !$getRecord->bill_payment_status) {
                                ThirdPartyUpgradeAndDowngrade::where('id', $getRecord->id)->update(['bill_payment_status' => 'paid']);
                                ThirdPartyOutdoor::where('id', $thirdPartyOutdoorObj->id)->update(['ongoing_request' => null, 'first_permit_pay' => true]);
                                $this->adminThirdPartySignageController->sendUpgradeorDowngradeApprovalLetter($thirdPartyOutdoorObj->id, $getRecord->id);
                            } else {
                                Log::error('Does not have any ongoing request');
                            }
                        } else {
                            ThirdPartyOutdoor::where('id', $thirdPartyOutdoorObj->id)->update(['permit_pay_status' => 'paid', 'first_permit_pay' => true]);
                        }
                        
                        if($thirdPartyOutdoorObj->first_permit_pay == false) {
                            $getOutdoorObj = ThirdPartyOutdoor::find($thirdPartyOutdoorObj->id);
                            // $getUpgradeandDowngradeObj = ThirdPartyUpgradeAndDowngrade::find($requestId);
                    
                            // if(Auth::user()->id == (string)$getOutdoorObj->assigned_officer) {
                                    $userDetails = KycThirdParty::where('user_id', $getOutdoorObj->user_id)->with(['user'])->get();
                                    $getThirdPartyDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getOutdoorObj->id)->get();
                                    $getUpgradeandDowngrade = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getOutdoorObj->id)->get();
                    
                                    $outdoorSignageName = ucwords($getUpgradeandDowngrade[0]['designation']);
                                    $outdoorRequest = "New Application";
                                    $outdoorWidth = $getThirdPartyDetails[0]['breadth_sign'];
                                    $outdoorLength = $getThirdPartyDetails[0]['length_sign'];
                                    $outdoorDimension = $getThirdPartyDetails[0]['dimension_sign'];
                                    $outdoorSide = $getThirdPartyDetails[0]['number_faces'];
                                    $signageSite = $getOutdoorObj->address_proposed_site;
                                    $date = Carbon::parse($getUpgradeandDowngrade[0]['updated_at'])->format('jS F, Y');
                                    $refno = UtilMethods::outdoorRequestAppId();
                                    ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['application_id' => $refno]);
                                    
                    
                                    $data = [
                                        'companyName' => $userDetails[0]['company_name'],
                                        'officeAddress' => $userDetails[0]['office_address'],
                                        'signageId' => $getOutdoorObj->id,
                                        'signageName' => $outdoorSignageName,
                                        'signageWidth' => $outdoorWidth,
                                        'signageHeight' => $outdoorLength,
                                        'signageDimension' => $outdoorDimension,
                                        'signageSide' => $outdoorSide,
                                        'signageDuration' => 'Annual',
                                        'signageRequest' => $outdoorRequest,
                                        'signageSite' => $signageSite,
                                        'appId' => $refno,
                                        'date' => $date
                                    ];
                    
                                    $pdf = Pdf::loadView('outdoorapproval', compact('data'));
                                    $fileObj = $pdf->download('outdoorapproval.pdf');
                    
                                    $getUserObj = User::find($userDetails[0]['user']['id']);
                    
                                    $body = "This is your approval letter for your " . $outdoorSignageName;
                                    $templateData = [
                                        'body' => $body,
                                        'name' => $getUserObj->company_name
                                    ];
                                    $templateContent = view('hodeoitemplate', $templateData)->render();
                                    UtilMethods::outdoorSignageApproval($getUserObj->email, $templateContent, $fileObj);
                                    
                                    $pdfContent = $pdf->output();
                                    $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
                                    $relativePath = 'invoices/' . $filename;
                                    $savePath = public_path($relativePath); // Full path to /public/invoices/
                                        
                                    if (!File::exists(public_path('invoices'))) {
                                        File::makeDirectory(public_path('invoices'), 0755, true);
                                    }
                                    file_put_contents($savePath, $pdfContent);
                                    $fileUrl = config('app.url') . '/public/' . $relativePath;
                                    $adnewrec = new ThirdPartyReceipts();
                                    $adnewrec->link = $fileUrl;
                                    $adnewrec->type = "Letter";
                                    // $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
                                    $getOutdoorObj->thirdpartyreceipts()->save($adnewrec);
                                
                        }
                    }
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'Firstparty TemporaryAds') {
                    Log::info('Firstparty TemporaryAds');
                    $reference = $event->data->reference;
                    $amount = ($event->data->amount) / 100;
                    $temporaryObj = FirstPartyTemporaryAds::find($event->data->metadata->applicationId);
                    $appHistory = AppHistoryFirstPartyTemporaryAds::where('first_party_temporary_ads_id', $temporaryObj->id)->get();
                    $purpose = $appHistory[0]['purpose'];
                    $applicationPayment = new PaymentFirstPartyTemporaryAds();
                    $applicationPayment->application_purpose = $purpose;
                    $applicationPayment->amount_paid = $amount;
                    $applicationPayment->status = $event->data->status;
                    $applicationPayment->reference_id = $reference;
                    $applicationPayment->payment_id = $temporaryObj->payment_id;
                    $applicationPayment->payment_type = 'paystack';
                    $temporaryAds = FirstPartyTemporaryAds::where('id', $temporaryObj->id)->get();
                    if ($temporaryAds->isEmpty()) {
                        Log::error('No First Party Temporary Ads found for payment ID: ' .$temporaryObj->id);
                        return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                    }
                    $userObj = User::find($temporaryAds[0]['user_id']);
                    if(is_null($userObj)) {
                        Log::error('No user found for user ID: ' . $temporaryAds->user_id);
                        return response()->json(['error' => 'No user found'], 422);
                    }
                    $response = $userObj->paymentFirstPartyTemporaryAds()->save($applicationPayment);
                    FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['pay_status' => 'paid', 'application_status' => 'approved']);
                    $this->getTemporaryAdsApprovalLetter($temporaryObj->id);
                    return response()->json(['data' => $response], 200);
                } elseif ($event->data->metadata->appType == 'SmallFormat Details') {
                    $applid = $event->data->metadata->applicationId;
                    if(is_array($applid)){
                        $count = count($applid) - 1;
                        for($i=0;  $i<=$count;  $i++) {
                            $smallformOb = SmallFormatAds::find($applid[$i]);
                            $smallformObdet = SmallFormatDetails::where('small_format_ads_id', $smallformOb->id)->get();
                            foreach($smallformObdet as $smallformObdetail){
                                
                            
                                if($smallformObdetail->final_bill_generated == "approved") {
                                    $getPrice = AppHistorySmallFormatDetails::where('small_format_details_id', $smallformObdetail->id)->get()->last();
            
                                    if($getPrice->balance !== null || 0) {
                                        $reference = $event->data->reference;
                                        $amount = $getPrice->balance;
                                        $smallFormatDetailsObj  = SmallFormatDetails::find($smallformObdetail->id);
                                        $smallFormatAds = SmallFormatAds::where('id', $smallFormatDetailsObj->small_format_ads_id)->get();
                                        $appHistoryInfo = AppHistorySmallFormatDetails::where('small_format_details_id', $smallFormatDetailsObj->id)->get()->last();
                                        $purpose = $smallFormatAds[0]['purpose_application'];
                                        $paymentId = $smallFormatAds[0]['payment_id'];
                                        $counter = $appHistoryInfo->payment_counter;
                    
                                        $applicationPayment = new PaymentSmallFormatAds();
                                        $applicationPayment->application_purpose = $purpose;
                                        $applicationPayment->amount_paid = $amount;
                                        $applicationPayment->status = $event->data->status;
                                        $applicationPayment->reference_id = $reference;
                                        $applicationPayment->payment_id = $paymentId;
                                        $applicationPayment->payment_type = 'paystack';
                                        if ($smallFormatAds->isEmpty()) {
                                            Log::error('No Small Format Ads found for payment ID: ' . $paymentId);
                                            return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                                        }
                                        $userObj = User::find($smallFormatAds[0]['user_id']);
                                        if(is_null($userObj)) {
                                            Log::error('No user found for user ID: ' . $smallFormatAds->user_id);
                                            return response()->json(['error' => 'No user found'], 422);
                                        }
                                        $response = $userObj->paymentSmallFormatAds()->save($applicationPayment);
                                        $counter++;
                                        $getOutstanding = $appHistoryInfo->balance;
                                        $balance = bcsub($getOutstanding, $amount, 2);
                        
                                        AppHistorySmallFormatDetails::where('small_format_details_id', $smallFormatDetailsObj->id)
                                            ->update(['payment_counter' => $counter, 'balance' => $balance]);
                        
                                        Log::info('Payment counter updated to: ' . $counter);
                                        Log::info('New balance calculated as: ' . $balance);
                        
                                        if ($counter < 3 && $balance > 0) {
                                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'part_paid', 'first_permit_pay' => true]);
                                            Log::info('Ad price payment status updated to: part_paid');
                                        } elseif ($counter < 3 && $balance == 0) {
                                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'paid', 'first_permit_pay' => true]);
                                            $this->getSmallFormatApprovalLetter($smallFormatDetailsObj->id);
                                            Log::info('Ad price payment status updated to: paid');
                                        } elseif ($counter >= 3 && $balance == 0) {
                                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'paid', 'first_permit_pay' => true]);
                                            $this->getSmallFormatApprovalLetter($smallFormatDetailsObj->id);
                                            Log::info('Ad price payment status updated to: paid');
                                        }
                                    }
                                }
                            }
                        }
                    }else{
                        $reference = $event->data->reference;
                        $amount = ($event->data->metadata->permitFee);
                        $smallFormatDetailsObj  = SmallFormatDetails::find($event->data->metadata->applicationId);
                        $smallFormatAds = SmallFormatAds::where('id', $smallFormatDetailsObj->small_format_ads_id)->get();
                        $appHistoryInfo = AppHistorySmallFormatDetails::where('small_format_details_id', $smallFormatDetailsObj->id)->get()->last();
                        $purpose = $smallFormatAds[0]['purpose_application'];
                        $paymentId = $smallFormatAds[0]['payment_id'];
                        $counter = $appHistoryInfo->payment_counter;
    
                        $applicationPayment = new PaymentSmallFormatAds();
                        $applicationPayment->application_purpose = $purpose;
                        $applicationPayment->amount_paid = $amount;
                        $applicationPayment->status = $event->data->status;
                        $applicationPayment->reference_id = $reference;
                        $applicationPayment->payment_id = $paymentId;
                        $applicationPayment->payment_type = 'paystack';
                        if ($smallFormatAds->isEmpty()) {
                            Log::error('No Small Format Ads found for payment ID: ' . $paymentId);
                            return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                        }
                        $userObj = User::find($smallFormatAds[0]['user_id']);
                        if(is_null($userObj)) {
                            Log::error('No user found for user ID: ' . $smallFormatAds->user_id);
                            return response()->json(['error' => 'No user found'], 422);
                        }
                        $response = $userObj->paymentSmallFormatAds()->save($applicationPayment);
                        $counter++;
                        $getOutstanding = $appHistoryInfo->balance;
                        $balance = bcsub($getOutstanding, $amount, 2);
        
                        AppHistorySmallFormatDetails::where('small_format_details_id', $smallFormatDetailsObj->id)
                            ->update(['payment_counter' => $counter, 'balance' => $balance]);
        
                        Log::info('Payment counter updated to: ' . $counter);
                        Log::info('New balance calculated as: ' . $balance);
        
                        if ($counter < 3 && $balance > 0) {
                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'part_paid', 'first_permit_pay' => true]);
                            Log::info('Ad price payment status updated to: part_paid');
                        } elseif ($counter < 3 && $balance == 0) {
                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'paid', 'first_permit_pay' => true]);
                            $this->getSmallFormatApprovalLetter($smallFormatDetailsObj->id);
                            Log::info('Ad price payment status updated to: paid');
                        } elseif ($counter >= 3 && $balance == 0) {
                            SmallFormatDetails::where('id', $smallFormatDetailsObj->id)->update(['adprice_payment_status' => 'paid', 'first_permit_pay' => true]);
                            $this->getSmallFormatApprovalLetter($smallFormatDetailsObj->id);
                            Log::info('Ad price payment status updated to: paid');
                        }
                    return response()->json(['data' => $response], 200);
                    }
                }
            } elseif ($event->data->metadata->paymentFor == 'Practitioner License Fee') {

                $getKycObj = KycThirdParty::find($event->data->metadata->appId);
                $getUserObj = User::find($event->data->metadata->userId);
                $getPaymentId = KycThirdPartyPayment::where('kyc_third_party_id' , $getKycObj->id)->get();

                $amountpaid = ($event->data->amount) / 100;
                $reference = $event->data->reference;

                $paymentInfo = new KycThirdPartyPayment();
                $paymentInfo->status = $event->data->status;
                $paymentInfo->reference_id = $reference;
                $paymentInfo->amount_paid = $amountpaid;
                $paymentInfo->payment_purpose = $event->data->metadata->paymentFor;
                $paymentInfo->payment_type = 'Paystack';
                $paymentInfo->permit_year = now()->year();
                $paymentInfo->payment_id = $getPaymentId[0]['payment_id'];
                $response = $getKycObj->kycThirdPartyPayment()->save($paymentInfo);
                KycThirdParty::where('id', $getKycObj->id)->update(['license_fee_status' => 'paid', 'md_status' => 'pending']);
                return response()->json(['data' => $response], 200);
            }
        }
    }

//    public function setPaymentReferencePaystackForMobile() {
//
//        Log::info("This is to check Paystack");
//
////        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
////            exit();
//
//        $input = @file_get_contents("php://input");
//        //define('PAYSTACK_SECRET_KEY', getenv('MOBILE_BRANDING_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('MOBILE_BRANDING_FORWARDSTREET'));
//
////        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
////            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == 'success') {
//            if($event->data->metadata->paymentFor == 'Permit Bill') {
//                $mobileObj = mobilead::find($event->data->metadata->applicationId);
//                $appHistoryThirdPartyMobile = AppHistoryMobile::where('mobilead_id', $mobileObj->id)->get();
//                $applicationPurpose = $appHistoryThirdPartyMobile[0]['purpose'];
//
//                $amountpaid = ($event->data->amount) / 100;
//                $reference = $event->data->reference;
//
//                $paymentInfo = new MobilePayment();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $reference;
//                $paymentInfo->payment_id = $mobileObj->payment_id;
//                $paymentInfo->status = $event->data->status;
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($mobileObj->user_id);
//                $response = $getUser->mobilePayment()->save($paymentInfo);
//                $setStreetLamp = mobilead::where('payment_id', $mobileObj->payment_id)->update(['Application_pay_status' => 'paid',
//                    'hod_permit_status' => 'approved', 'legal_status' => 'approved',  'final_status' => 'approved']);
//                $this->sendDetailsforQrcode($mobileObj->id);
//                $currentStep = AdminRole::where('id', 5)->get();
//                $permitStep = new PermitStepMobile();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $mobileObj->permitStepMobile()->save($permitStep);
//                return response()->json(['data' => $response], 200);
//            }
//        }
//    }
//
//    public function setPaymentReferencePaystackforExpressionofInterestApplication() {
//
//        Log::info("This is to check Paystack");
//
//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();
//
//        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('THIRD_PARTY_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('THIRD_PARTY_FORWARDSTREET'));
//
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == "success") {
//            if($event->data->metadata->paymentFor == 'Practitioner Application') {
//
//
//            }
//        }
//    }
//
//    public  function setPaymentReferenceforStreetLamp() {
//
//        Log::info("This is to check Paystack");
//
//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();
//
//        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('STREETLAMPPOLES_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('STREETLAMPPOLES_FORWARDSTREET'));
//
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == 'success') {
//            if($event->data->metadata->paymentFor == 'Permit Bill') {
//                $getStreetLampObj = StreetLampsAds::find($event->data->metadata->applicationId);
//                $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $getStreetLampObj->id)->get();
//                $applicationPurpose = $appHistoryLamp[0]['purpose'];
//                $amountpaid = ($event->data->amount) / 100;
//                $reference = $event->data->reference;
//
//                $paymentInfo = new PaymentStreetLamp();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $reference;
//                $paymentInfo->payment_id = $getStreetLampObj->payment_id;
//                $paymentInfo->status = $event->data->status;
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $getUser = User::find($getStreetLampObj->user_id);
//                $response = $getUser->payment()->save($paymentInfo);
//                $setStreetLamp = StreetLampsAds::where('payment_id', $getStreetLampObj->payment_id)->update(['Application_pay_status' => 'paid',
//                    'permit_payment_status' => 'paid',  'legal_status' => 'pending']);
//                $currentStep = AdminRole::where('id', 6)->get();
//                $permitStep = new PermitStepStreetLamp();
//                $permitStep->purpose = $applicationPurpose;
//                $permitStep->current_steps = $currentStep[0]['role'];
//                $getStreetLampObj->permitStepStreetLamp()->save($permitStep);
//            }
//        }
//    }

    protected function domainExists($email)
    {
        // Extract the domain from the email address
        $parts = explode('@', $email);
        $domain = array_pop($parts);

        // Perform a DNS lookup for the domain
        $mxRecords = [];
        if (checkdnsrr($domain, 'MX')) {
            // MX records found, domain exists
            return true;
        } else {
            // No MX records found, domain does not exist
            return false;
        }
    }

    public function composeEmail($subject, $body,  $userEmail)
    {
        require base_path('vendor/autoload.php');

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'smtp-relay.brevo.com'; //ssl://smtp.gmail.com
        $mail->SMTPAuth = true;
        $mail->Username = 'macdonnad@gmail.com';
        $mail->Password = 'xsmtpsib-93267ec9551960673300f309d7edd9a807648eb7aac5b10b6f80f2e106c7f010-dMSfPhNXDW84pqvY';
        // $mail->SMTPSecure = 'ssl';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
        $mail->addAddress($userEmail);
        $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body = "Here is the price for the Mobile Ads: " .$body;
        $mail->send();

    }

    public function composeEmailV2($subject, $userEmail, $emailContent) {

        if($this->domainExists($userEmail)) {
            Log::info("Domain Exists");
        } else {
            Log::error("Domain does not exist");
        }

        require base_path('vendor/autoload.php');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'smtp-relay.brevo.com'; //ssl://smtp.gmail.com
            $mail->SMTPAuth = true;
            $mail->Username = 'macdonnad@gmail.com';
            $mail->Password = 'xsmtpsib-93267ec9551960673300f309d7edd9a807648eb7aac5b10b6f80f2e106c7f010-dMSfPhNXDW84pqvY';
            // $mail->SMTPSecure = 'ssl';
            $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = 587;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            Log::info($userEmail);
            $mail->Subject = $subject;
            $mail->Body = $emailContent;
            $mail->send();
            Log::info("message sent");
        } catch (Exception $exception) {
//            error_log('Email delivery failed: ' . $mail->ErrorInfo);
            $message = $exception->getMessage();
            Log::error($message);
            return true;
        }
    }

    private function sendDetailsforQrcode($id) {

        $url = getenv('QRcode_URL');

        $headers = [
            'Authorization' => 'Bearer ' . getenv('QRcode_BEARER_LIVE'),
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
        ];

        $getMobileDetails = mobilead::where('id', $id)->get();
        $getUserInfo = User::where('id', $getMobileDetails[0]['user_id'])->get();
        $getMobileLicense = MobileAdsVehicleLicense::where('mobilead_id', $id)->get();
        $count = count($getMobileLicense) - 1;
        $currentYear = date('Y');

        $data = [];

        for ($i=0; $i<= $count; $i++) {
            $postData = [
                'email' => $getUserInfo[0]['email'],
                'phone' => $getUserInfo[0]['phone_number'],
                'businessName' => $getMobileDetails[0]['brand_name'],
                'brandingType' => $getMobileLicense[$i]['branding_details'],
                'vehicleType' => $getMobileLicense[$i]['vehicle_type'],
                'permitYear' => $currentYear,
                'plateNumber' => $getMobileLicense[$i]['vehicle_license'],
                'branding_id' => $id
            ];
            $data [] = $postData;
        }

        $response = Http::withHeaders($headers)->post($url, $data);
        if($response->successful()) {
            $responseData = $response->json();

        } else {
            $responseData = "Unable to send data";
        }
        Log::info( response()->json(['data' => $responseData], $response->status()));
    }

    private function calculateOutdoorBalance($outdoorId, $amountPaid) {
        Log::info("entering into the balance checker  function");
        $appHistory =  AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoorId)->latest()->first();
        if($appHistory->balance == 0) {
            $adsPrice = $appHistory->ads_price;
            $legalFee = $appHistory->legal_fee;
            $applicationFee = $appHistory->application_price;
            $getRate = $appHistory->price_rate;
            $applicationPurpose = $appHistory->purpose_application;
            $outdoorSiteObj = ThirdPartyOutdoor::find($outdoorId);
            $totalFee = bcadd($adsPrice, $legalFee, 2);

            $balance  = bcsub($totalFee, $amountPaid, 2);
            Log::info(["totalfee"=>$totalFee, "new balance" => $balance, "paystack fee" => $amountPaid]);
            $appHistoryInput = new  AppHistoryThirdPartyOutdoor();
            $appHistoryInput->purpose_application = $applicationPurpose;
            $appHistoryInput->application_price = $applicationFee;
            $appHistoryInput->ads_price = $adsPrice;
            $appHistoryInput->legal_fee = $legalFee;
            $appHistoryInput->price_rate = $getRate;
            $appHistoryInput->balance = $balance;
            $outdoorSiteObj->appHistoryThirdPartyOutdoor()->save($appHistoryInput);
        } elseif ($appHistory->balance > 0) {
            $adsPrice = $appHistory->ads_price;
            $legalFee = $appHistory->legal_fee;
            $applicationFee = $appHistory->application_price;
            $getRate = $appHistory->price_rate;
            $applicationPurpose = $appHistory->purpose_application;
            $outdoorSiteObj = ThirdPartyOutdoor::find($outdoorId);
            $balance = $appHistory->balance;

            $newBalance  = bcsub($balance, $amountPaid, 2);
            
            Log::info(["balance"=>$balance, "new balance" => $newBalance, "paystack fee" => $amountPaid]);
            $appHistoryInput = new  AppHistoryThirdPartyOutdoor();
            $appHistoryInput->purpose_application = $applicationPurpose;
            $appHistoryInput->application_price = $applicationFee;
            $appHistoryInput->ads_price = $adsPrice;
            $appHistoryInput->legal_fee = $legalFee;
            $appHistoryInput->price_rate = $getRate;
            $appHistoryInput->balance = $newBalance;
            $outdoorSiteObj->appHistoryThirdPartyOutdoor()->save($appHistoryInput);
        }

    }

    private function getTemporaryAdsApprovalLetter($temporaryId) {

            $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
                if ($temporaryObj->pay_status !== 'paid') {
                    return response()->json(['success' => false, 'data' => 'Temporary ads has not been paid'], 422);
                }

                if($temporaryObj->ref_no == null) {
                    $refNo = $this->getTemporaryRefNo();
                    FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['ref_no' => $refNo]);
                }
                $getTemporaryAds = FirstPartyTemporaryAds::where('id', $temporaryObj->id)->get();
                $userDetails = User::where('id', $temporaryObj->user_id)->get();
                $getTemporaryInfo = FirstPartyTemporaryAdsDetails::where('first_party_temporary_ads_id', $temporaryObj->id)->get();
            $getAddress = '';
            $getLga = '';
            $getBustop = '';
        $companyName = '';

        if($userDetails[0]['user_type'] == 'first_party') {
            $companyName = $userDetails[0]['business_name'];
            $getKycDetails = kycdetail::where('user_id', $temporaryObj->user_id)->get();
            $getAddress = $getKycDetails[0]['full_address'];
            $getLga = $getKycDetails[0]['lga'];
            $getBustop = $getKycDetails[0]['bustop'];
        } else {
            $getKycDetails = KycThirdParty::where('user_id', $temporaryObj->user_id)->get();
            $getAddress = $getKycDetails[0]['office_address'];
            $getBustop = $getKycDetails[0]['nearest_bustop'];
            $getLga = $getKycDetails[0]['lga'];
            $companyName = $getKycDetails[0]['company_name'];
        }

                //$getAddressInfo = kycdetail::where('user_id',  $temporaryObj->user_id)->get();
                $carbonStartDate = Carbon::parse($getTemporaryAds[0]['start_date']);
                $carbonEndDate = Carbon::parse($getTemporaryAds[0]['end_date']);
                $validity = $carbonStartDate->diffInDays($carbonEndDate);
                $validityInWords = UtilMethods::temporaryInWords($validity);
                
                // Adjust the start date to the start of its week (Monday)
                $startOfMonth = $carbonStartDate->copy()->startOfMonth();
            
                // Adjust the end date to the end of its week (Sunday)
                $endOfMonth = $carbonEndDate->copy()->endOfMonth();
            
                // Calculate the total number of weeks
                $monthsvalidity = $startOfMonth->diffInMonths($endOfMonth) + 1;
                $monthsvalidityInWords = UtilMethods::temporaryInWords($monthsvalidity);
                
                
                $countDetails = count($getTemporaryInfo) - 1;
                $signTypes = [];
                $quantitySigns = [];

                for($i=0;$i <= $countDetails; $i++) {
                    $signTypes [] = $getTemporaryInfo[$i]['type_sign'];
                    $quantitySigns [] = $getTemporaryInfo[$i]['number_wearable'];
                }
                $combinedArray = [];
                foreach ($signTypes as $index => $value) {
                    $combinedArray [] = [
                        'key' => $value,
                        'value' => $quantitySigns[$index],
                        'words' => $this->getWordsofNumber($quantitySigns[$index]),
                    ];
                    
                }

                $data = [
                    'userinfo' => $companyName,
                    'usertype' => $userDetails[0]['user_type'],
                    'useraddress' => $getAddress,
                    'bustop' =>$getBustop,
                    'lga' => $getLga,
                    'permitNumber' =>  $getTemporaryAds[0]['ref_no'],
                    'date' => Carbon::parse($getTemporaryAds[0]['start_date'])->format('d F Y'),
                    'validity' => $validity,
                    'validityInWords' => $validityInWords,
                    'monthvalidity' => $monthsvalidity,
                    'monthsvalidityInWords' => $monthsvalidityInWords,
                    'nameAds' => $getTemporaryAds[0]['name_of_service'],
                    'duration' => $getTemporaryAds[0]['duration'],
                    'startdate' => $carbonStartDate->format('jS F'),
                    'enddate' => $carbonEndDate->format('jS F Y'),
                ];
                
                
                
                // Define the array of types you want to check against
                $standard = ['Standard'];
                
                // Check if there is any intersection between $signTypes and $standard
                $standardcommonTypes = array_intersect($signTypes, $standard);
                
                // Define the array of types you want to check against
                $intermediate = ['Intermediate'];
                
                // Check if there is any intersection between $signTypes and $intermediate
                $intermediatecommonTypes = array_intersect($signTypes, $intermediate);
                
                // Define the array of types you want to check against
                $premium = ['Premium'];
                
                // Check if there is any intersection between $signTypes and $premium
                $premiumcommonTypes = array_intersect($signTypes, $premium);
                
                if (!empty($standardcommonTypes)) {
                    $pdf = Pdf::loadView('firstpartytemporaryadsletterstandard', compact('data', 'combinedArray'));
                    $fileObj = $pdf->download('firstpartytemporaryadsletterstandard.pdf');
                } elseif(!empty($intermediatecommonTypes)) {
                    $pdf = Pdf::loadView('firstpartytemporaryadsletterintermediate', compact('data', 'combinedArray'));
                    $fileObj = $pdf->download('firstpartytemporaryadsletterintermediate.pdf');
                } elseif(!empty($premiumcommonTypes)){
                    $pdf = Pdf::loadView('firstpartytemporaryadsletterpremium', compact('data', 'combinedArray'));
                    $fileObj = $pdf->download('firstpartytemporaryadsletterpremium.pdf');
                } else{
                    $pdf = Pdf::loadView('firstpartytemporaryadsletter', compact('data', 'combinedArray'));
                    $fileObj = $pdf->download('firstpartytemporaryadsletter.pdf');
                }
                

                $userObj = User::find($getTemporaryAds[0]['user_id']);
                $body = "We are pleased to inform you that your application for temporary ads has been approved. Please find your approval letter attached";
                $templateData = [
                    'body' => $body,
                    'name' => $userObj->business_name
                ];
                $templateContent = view('hodeoitemplate', $templateData)->render();
                UtilMethods::temporaryAdsSendApproval($userObj->email, $templateContent, $fileObj);
                
                
                $pdfContent = $pdf->output();
                $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
                $relativePath = 'invoices/' . $filename;
                $savePath = public_path($relativePath); // Full path to /public/invoices/
                                        
                if (!File::exists(public_path('invoices'))) {
                    File::makeDirectory(public_path('invoices'), 0755, true);
                }
                file_put_contents($savePath, $pdfContent);
                $fileUrl = config('app.url') . '/public/' . $relativePath;
                $adnewrec = new FirstPartyTemporaryReceipts();
                $adnewrec->link = $fileUrl;
                $adnewrec->type = "Letter";
                // $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
                $temporaryObj->firstpartytemporaryreceipts()->save($adnewrec);
                
                
              //Log::info('email sent to ' . $userObj->email);
        return response()->json(['success' => true, 'data' => "Email Sent successfully"], 200);
    }

     private function getSmallFormatApprovalLetter($smallFormatDetailsId)     {
         $smallFormatDetailObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);

         if($smallFormatDetailObj->adprice_payment_status !== 'paid') {
             return response()->json(['success' => false, 'data' => 'small format details is not yet fully paid'], 422);
         }

         if ($smallFormatDetailObj->reference_id == null) {
             $refno = $this->getRefNo();
             SmallFormatDetails::where('id', $smallFormatDetailObj->id)->update(['reference_id' => $refno]);
         }

         $getSmallFormat = SmallFormatAds::where('id', $smallFormatDetailObj->small_format_ads_id)->get();
         $getUserInfo = User::where('id', $getSmallFormat[0]['user_id'])->get();
         $getAddress = '';
         $getLga = '';
         $getBustop = '';

         if($getUserInfo[0]['user_type'] == 'first_party') {
             $companyName = $getUserInfo[0]['business_name'];
             $getKycDetails = kycdetail::where('user_id', $getSmallFormat[0]['user_id'])->get();
             $getAddress = $getKycDetails[0]['full_address'];
             $getLga = $getKycDetails[0]['lga'];
             $getBustop = $getKycDetails[0]['bustop'];
         } else {
             $getKycDetails = KycThirdParty::where('user_id', $getSmallFormat[0]['user_id'])->get();
             $getAddress = $getKycDetails[0]['office_address'];
             $getBustop = $getKycDetails[0]['nearest_bustop'];
             $getLga = $getKycDetails[0]['lga'];
             $companyName = $getKycDetails[0]['company_name'];
         }


         $location = $getSmallFormat[0]['address_site'];
         $date = Carbon::parse($smallFormatDetailObj->created_at);
         $endYear = Carbon::create($date->year, 12, 31);
         $diffInMonths = $date->diffInMonths($endYear);
         $diffInMonthsInWords = UtilMethods::smallFormatInMonth($diffInMonths);

         $data = [
             'date' => Carbon::parse($smallFormatDetailObj->created_at)->format('jS F, Y'),
             'refno' => $smallFormatDetailObj->reference_id,
             'company' => $companyName,
             'address' => $getAddress,
             'bustop' => $getBustop,
             'lga' => $getLga,
             'startDate' => $date->format('F, Y'),
             'endDate' => $endYear->format('d F, Y'),
             'siteLocation' => $location,
             'appNumber' => $smallFormatDetailsId,
             'signType' => $smallFormatDetailObj->type_signs,
             'numberMonths' => $diffInMonths
         ];

         $pdf = Pdf::loadView('smallformat', compact('data'));
         $fileObj = $pdf->download('smallformat.pdf');

         $userObj = User::find($getSmallFormat[0]['user_id']);
         $body = "We are pleased to inform you that your application for small format ads has been approved. Please find your approval letter attached";
         $templateData = [
             'body' => $body,
             'name' => $userObj->business_name
         ];
         $templateContent = view('hodeoitemplate', $templateData)->render();
         UtilMethods::smallFormatSendApproval($userObj->email, $templateContent, $fileObj);
         
         $pdfContent = $pdf->output();
         $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
         $relativePath = 'invoices/' . $filename;
         $savePath = public_path($relativePath); // Full path to /public/invoices/
                                        
         if (!File::exists(public_path('invoices'))) {
             File::makeDirectory(public_path('invoices'), 0755, true);
         }
         file_put_contents($savePath, $pdfContent);
         $fileUrl = config('app.url') . '/public/' . $relativePath;
         $adnewrec = new SmallFormatReceipts();
         $adnewrec->link = $fileUrl;
         $adnewrec->type = "Letter";
         $tosaveoutd = SmallFormatAds::find($smallFormatDetailObj->small_format_ads_id);
         $tosaveoutd->smallformatreceipts()->save($adnewrec);
         
         //Log::info('email sent to ' . $userObj->email);
         return response()->json(['success' => true, 'data' => "Email Sent successfully"], 200);
     }

    private function getTemporaryRefNo() {
        $static = 'LASAA/TP';
        $date = Carbon::now()->format('Y/M');
        $sequence = KycThirdPartyFirstApprovalSequence::firstOrCreate([]);
        $lastNumber = $sequence->last_number + 1;
        return $static . '/' .$date . '/' . $lastNumber;
    }

    private function getRefNo() {
        $prefix = 'LASAA/SF';
        $batchKey = Carbon::now()->format('Y/M');
        $sequence = KycThirdPartyFirstApprovalSequence::firstOrCreate([]);
        $lastNumber = $sequence->last_number + 1;
        $sequence->update(['last_number' => $lastNumber]);
        return $prefix . '/' . $batchKey . '/' . $lastNumber;
    }

    private  function getWordsofNumber($number) {
        Log::info($number);
        $words = Speller::spellNumber((int)$number, Speller::LANGUAGE_ENGLISH);
        return $words;
    }
}
