<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\AdminActivity;
use App\Models\AdminRole;
use App\Models\Apphistory;
use App\Models\AppHistoryMobile;
use App\Models\AppHistoryStreetLamp;
use App\Models\AppHistoryThirdPartyOutdoor;
use App\Models\AppHistorySmallFormatDetails;
use App\Models\ExpressionOfStreetLamps;
use App\Models\mobilead;
use App\Models\MobileAdsVehicleLicense;
use App\Models\MobilePayment;
use App\Models\onpremise;
use App\Models\OnpremiseInfo;
use App\Models\PaymentStreetLamp;
use App\Models\PaymentThirdPartyMobile;
use App\Models\PermitStepMobile;
use App\Models\PermitStepOnpremise;
use App\Models\PermitStepStreetLamp;
use App\Models\StreetLampInfo;
use App\Models\StreetLampsAds;
use App\Models\SmallFormatDetails;
use App\Models\SmallFormatAds;
use App\Models\ThirdPartyOutdoor;
use App\Models\ThirdPartyOutdoorSignDetails;
use App\Models\ThirdPartyMobile;
use App\Models\ThirdPartyMobileAppHistory;
use App\Models\ThirdPartyMobilePermitStep;
use App\Models\ThirdPartyMobileVehicleLicense;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\UserWallet;
use App\Models\VehicleMobileAds;
use App\Models\VehicleThirdPartyMobile;
use App\Models\WalletTransaction;
use App\Models\KycThirdParty;
use Carbon\Carbon;
use Barryvdh\DomPDF\Facade\Pdf;
use GuzzleHttp\Client;
use http\Env\Response;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
use PhpOffice\PhpSpreadsheet\IOFactory;

class AdminOperationController extends Controller   {



    public function getAllUserDetails(Request $request) {

        $keyword = $request->input('search');

            $getUser = User::where(function ($query) use ($keyword) {
                $query->where('first_name', 'like', '%'. $keyword . '%')
                                ->orWhere('last_name', 'like', '%'. $keyword . '%')
                                ->orWhere('business_name', 'like', '%'. $keyword . '%')
                                ->orWhere('email', 'like', '%'. $keyword .'%')
                                ->orWhere('phone_number', 'like', '%' . $keyword . '%');
            })->get();
            return response()->json(['data' => $getUser], 200);
    }

    public function paginateUserDetails(Request $request) {

        $keyword = $request->input('search');

        $getUser = User::where(function ($query) use ($keyword) {
            $query->where('first_name', 'like', '%'. $keyword . '%')
                ->orWhere('last_name', 'like', '%'. $keyword . '%')
                ->orWhere('business_name', 'like', '%'. $keyword . '%')
                ->orWhere('email', 'like', '%'. $keyword .'%')
                ->orWhere('phone_number', 'like', '%' . $keyword . '%');
        })->paginate(20);
        return response()->json(['data' => $getUser], 200);

    }
    
    public function pageGetUserInfo($id) {

        $user = Auth::user();
        if($user) {
            $user = User::select('id','first_name','last_name','email','phone_number','business_name','user_type','account_active',
            'kyc_status','verified_account','is_institution')->where('id', $id)->with(['expressionOfStreetLamps', 'kycdetail','kycThirdParty']);
            $userInfo = $user->get();
            $response = $userInfo;
            
            $onpremse = onpremise::where('user_id', $id)->where('hod_status', 'approved')->get()->toArray();
            $outdoor = ThirdPartyOutdoor::where('user_id', $id)->where('md_second_approval', 'approved')->get()->toArray();
            $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
            $getOutDoorObjcount = count($outdoor) - 1;
            $getOnpremseObjcount = count($onpremse) - 1;
            $getSmallformObjcount = count($smallform) - 1;
            // foreach($getOutDoorObj as $outdoors){
            $totalOnp = [];
            $totalOutd = [];
            $totalSmf = [];
            for ($i = 0; $i <= $getOutDoorObjcount; $i++) {
                $getOnpremiseInfo = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoor[$i]['id'])->get()->last();
                if ($getOnpremiseInfo) {
                    $getOnPremiseFee = ceil($getOnpremiseInfo['balance']);
                    $totalOutd[] = $getOnPremiseFee;
                }
            }
            for ($i = 0; $i <= $getOnpremseObjcount; $i++) {
                $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremse[$i]['id'])->get()->last();
                if ($getOnpremiseInfo) {
                    $getOnPremiseFee = ceil($getOnpremiseInfo['balance']);
                    $totalOnp[] = $getOnPremiseFee;
                }
            }
            for ($i = 0; $i <= $getSmallformObjcount; $i++) {
                $smallformde = SmallFormatDetails::where('small_format_ads_id', $smallform[$i]['id'])->where('md_approval', 'approved')->get()->toArray();
                foreach ($smallformde as $small){
                    $getOnpremiseInfo = AppHistorySmallFormatDetails::where('small_format_details_id', (int)$small['id'])->get()->last();
                    if ($getOnpremiseInfo) {
                        $getOnPremiseFee = ceil($getOnpremiseInfo['balance']);
                        $totalSmf[] = $getOnPremiseFee;
                    }
                }
            }
            
            $plustotalOnp = array_sum($totalOnp);
            $plustotalOutd = array_sum($totalOutd);
            $plustotalSmf = array_sum($totalSmf);

            return response()->json(['success' => true, 'data' => $response, 'total_onpremise' => $plustotalOnp, 'total_outdoor' => $plustotalOutd, 'total_small_format' => $plustotalSmf ], 200);
        }
    }
    
    public function onPremiseDebitNote($id, Request $request) {
        $validate = Validator::make($request->all(), [
                    'amount' => 'nullable|numeric|between:0,999999999.99',
                    'productType' => 'required|string|in:outdoor,premise',
                    'paymentId' => 'nullable|string',
                    'type' => 'required|string|in:debit,credit',
                    'applyToAccount' => 'required|boolean',
                    'comments' => 'required|string'
                ]);

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

        $user = Auth::user();
        $amount = $request['amount'];
        if($user->department == "Billings") {
            if($request['productType'] == "premise"){
                if($request['type'] == "debit"){
                    if($request['applyToAccount'] == true){
                        $onpremse = onpremise::where('user_id', $id)->where('hod_status', 'approved')->where('billing_status', 'approved')->get()->toArray();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($onpremse) {
                            $getObjcount = count($onpremse) - 1;
                            $distributedamount = $amount / count($onpremse);
            
                            // foreach($getOutDoorObj as $outdoors){
                            for ($i = 0; $i <= $getObjcount; $i++) {
                            
                                $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremse[$i]['id'])->get()->last();
                            
                                if ($getOnpremiseInfo) {
                                    // Add the distributed amount to the balance
                                    $getOnpremiseInfo->balance += $distributedamount;
                                    $getOnpremiseInfo->save();
                                }
                            
                            }
                    $OnpremiseInfo = OnpremiseInfo::where('onpremise_id', $onpremse[0]['id'])->where('number_of_sign', '>', 0)->get();
                      $userObj = User::find($onpremse[0]['user_id']);
                     $userdetails = User::where('id', $onpremse[0]['user_id'])->first();
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }else{
                        $onpremse = onpremise::where('payment_id', $request['paymentId'])->where('hod_status', 'approved')->where('billing_status', 'approved')->first();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($onpremse) {
                        
                            
                            $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremse->id)->get()->last();
                        
                            if ($getOnpremiseInfo) {
                                // Add the distributed amount to the balance
                                $getOnpremiseInfo->balance += $amount;
                                $getOnpremiseInfo->save();
                            }
                    $OnpremiseInfo = OnpremiseInfo::where('onpremise_id', $onpremse->id)->where('number_of_sign', '>', 0)->get();
                      $userObj = User::find($onpremse->user_id);
                     $userdetails = User::where('id', $onpremse->user_id)->first();
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }
                    
             
             
                    $lcenLGAs = ["Apapa", "Eti-osa", "Ikoyi-Obalende", "Lekki Phase 1", "Lagos Mainland", "Lagos Island", "Surulere", "Aguda/Itire-Ikate"];
                    $leastLGAs = ["Epe", "Ibeju-Lekki", "Ikorodu", "Kosofe", "Magodo/Isheri", "Shomolu"];
                    $lwest1LGAs = ["Agege", "Ikeja", "Onigbongbo", "Computer Village", "Ifako-Ijaiye", "Mushin", "Oshodi/Isolo"];
                    $lwest2LGAs = ["Alimosho", "Ajeromi-Ifelodun", "Amuwo Odofin", "Badagry", "Ojo", "Mosan Okunola"];
                    
                            
                    if($request['applyToAccount'] == true){
                        if (in_array($onpremse[0]['lga'], $lcenLGAs)) {
                        // The value of $mobileInput['lga'] is one of the allowed LGAs
                        $zone = "Lagos Central";
                    }elseif(in_array($onpremse[0]['lga'], $leastLGAs)){
                        $zone = "Lagos East";
                    }elseif(in_array($onpremse[0]['lga'], $lwest1LGAs)){
                        $zone = "Lagos West 1";
                    }elseif(in_array($onpremse[0]['lga'], $lwest2LGAs)){
                        $zone = "Lagos West 2";
                    } else {
                        $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2" ];
                        $selectedKey = array_rand($listArray);
                        $selectValue = $listArray[$selectedKey];
                        $zone = $selectValue;
                    }
                    
                     $HODe = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->exists();
                     if($HODe){
                         $HOD = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->first();
                         $HODfn = $HOD->first_name;
                         $HODln = $HOD->last_name;
                     }else{
                         $HODfn = "Adekunle";
                         $HODln = "Afolabi";
                     }
                     
                     // Part 1: Current date in "Ymd" format (e.g., 2232024)
                     $part1 = date('Ymd');
                    
                     // Part 2: Random 3 uppercase letters (e.g., JJJ)
                     $part2 = strtoupper(Str::random(3));
                    
                     // Part 3: Random alphanumeric value (e.g., 1P)
                     $part3 = strtoupper(Str::random(2));
                    
                     // Part 4: Random number between 100000 and 999999 (e.g., 193974)
                     $part4 = mt_rand(100000, 999999);
                
                     // Combine all parts into the final string
                     $barcoden = "{$part1}-{$part2}-{$part3}-{$part4}";
                     
                            
                     $startdate = Carbon::parse($onpremse[0]['created_at'])->addMonth()->tz('Africa/Lagos');
                     $enddate = Carbon::parse($onpremse[0]['created_at'])->endOfYear();
                     
                            
                     $countDetails = count($OnpremiseInfo) - 1;
                     $comm = [];
                     if($countDetails == 0){
                     $commentt = strtoupper($OnpremiseInfo[0]['type_of_sign']);
                     }else{
                       for($i=0;$i <= $countDetails; $i++) {
                         $comm [] = $OnpremiseInfo[$i]['type_of_sign'];
                     }
                     $commentt = implode(", ", $comm);
                     }
                     $signTypes = [];
                     $quantitySigns = [];
            
                     for($i=0;$i <= $countDetails; $i++) {
                         $signTypes [] = $OnpremiseInfo[$i]['type_of_sign'];
                         $quantitySigns [] = $OnpremiseInfo[$i]['length_in_meter'] * $OnpremiseInfo[$i]['width_in_meter'];
                     }
                     $combinedArray = [];
                     foreach ($signTypes as $index => $value) {
                         $combinedArray [] = [
                             'key' => $value,
                             'value' => $quantitySigns[$index],
                            //  'words' => $this->getWordsofNumber($quantitySigns[$index]),
                         ];
                         
                     }
                     $amountInWord = UtilMethods::getAmountInWords($onpremse[0]['initial_amount_due'] - $request['price']);
                     $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $onpremse[0]['name_of_owner'],
                          'address' => $onpremse[0]['sign_address'],
                          'email' => $onpremse[0]['email'],
                          'cust_id' => $onpremse[0]['user_id'],
                          'ref_no' => $onpremse[0]['payment_id'],
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $onpremse[0]['initial_amount_due'],
                          'debit' => $amount,
                          'credit' => - $amount,
                          'note_type' => 'debit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'zone' => $zone,
                          'HOD_first_name' => $HODfn,
                          'HOD_last_name' => $HODln,
                          'barcode' => $barcoden,
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL DEBIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                    }else{
                        if (in_array($onpremse->lga, $lcenLGAs)) {
                        // The value of $mobileInput['lga'] is one of the allowed LGAs
                        $zone = "Lagos Central";
                    }elseif(in_array($onpremse->lga, $leastLGAs)){
                        $zone = "Lagos East";
                    }elseif(in_array($onpremse->lga, $lwest1LGAs)){
                        $zone = "Lagos West 1";
                    }elseif(in_array($onpremse->lga, $lwest2LGAs)){
                        $zone = "Lagos West 2";
                    } else {
                        $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2" ];
                        $selectedKey = array_rand($listArray);
                        $selectValue = $listArray[$selectedKey];
                        $zone = $selectValue;
                    }
                    
                     $HODe = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->exists();
                     if($HODe){
                         $HOD = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->first();
                         $HODfn = $HOD->first_name;
                         $HODln = $HOD->last_name;
                     }else{
                         $HODfn = "Adekunle";
                         $HODln = "Afolabi";
                     }
                     
                     // Part 1: Current date in "Ymd" format (e.g., 2232024)
                     $part1 = date('Ymd');
                    
                     // Part 2: Random 3 uppercase letters (e.g., JJJ)
                     $part2 = strtoupper(Str::random(3));
                    
                     // Part 3: Random alphanumeric value (e.g., 1P)
                     $part3 = strtoupper(Str::random(2));
                    
                     // Part 4: Random number between 100000 and 999999 (e.g., 193974)
                     $part4 = mt_rand(100000, 999999);
                
                     // Combine all parts into the final string
                     $barcoden = "{$part1}-{$part2}-{$part3}-{$part4}";
                     
                            
                     $startdate = Carbon::parse($onpremse->created_at)->addMonth()->tz('Africa/Lagos');
                     $enddate = Carbon::parse($onpremse->created_at)->endOfYear();
                     
                            
                     $countDetails = count($OnpremiseInfo) - 1;
                     $comm = [];
                     if($countDetails == 0){
                     $commentt = strtoupper($OnpremiseInfo[0]['type_of_sign']);
                     }else{
                       for($i=0;$i <= $countDetails; $i++) {
                         $comm [] = $OnpremiseInfo[$i]['type_of_sign'];
                     }
                     $commentt = implode(", ", $comm);
                     }
                     $signTypes = [];
                     $quantitySigns = [];
            
                     for($i=0;$i <= $countDetails; $i++) {
                         $signTypes [] = $OnpremiseInfo[$i]['type_of_sign'];
                         $quantitySigns [] = $OnpremiseInfo[$i]['length_in_meter'] * $OnpremiseInfo[$i]['width_in_meter'];
                     }
                     $combinedArray = [];
                     foreach ($signTypes as $index => $value) {
                         $combinedArray [] = [
                             'key' => $value,
                             'value' => $quantitySigns[$index],
                            //  'words' => $this->getWordsofNumber($quantitySigns[$index]),
                         ];
                         
                     }
                     $amountInWord = UtilMethods::getAmountInWords($onpremse->initial_amount_due - $request['price']);
                        $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $onpremse->name_of_owner,
                          'address' => $onpremse->sign_address,
                          'email' => $onpremse->email,
                          'cust_id' => $onpremse->user_id,
                          'ref_no' => $onpremse->payment_id,
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $onpremse->initial_amount_due,
                          'debit' => $amount,
                          'credit' => - $amount,
                          'note_type' => 'debit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'zone' => $zone,
                          'HOD_first_name' => $HODfn,
                          'HOD_last_name' => $HODln,
                          'barcode' => $barcoden,
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL DEBIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                    }
                     
                    
                     $pdf = Pdf::loadView('CreditDebitNote', compact('data', 'combinedArray'))->setPaper('A3');
                     $fileObj = $pdf->download('CreditDebitNote.pdf');
                    
                     $body = "Please find debit note attached";
                     $templateData = [
                         'body' => $body,
                         'name' => $userObj->business_name
                     ];
                     $templateContent = view('hodeoitemplate', $templateData)->render();
                     UtilMethods::debitnotefirstparty($userObj->email, $templateContent, $fileObj);
                    
                    return response()->json(['success' => true, 'date' => 'debit note successfully sent'], 200);
                }else if($request['type'] == "credit"){
                    if($request['applyToAccount'] == true){
                        $onpremse = onpremise::where('user_id', $id)->where('hod_status', 'approved')->get()->toArray();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($onpremse) {
                            $getObjcount = count($onpremse) - 1;
                            $distributedamount = $amount / count($onpremse);
            
                            // foreach($getOutDoorObj as $outdoors){
                            for ($i = 0; $i <= $getObjcount; $i++) {
                                $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremse[$i]['id'])->get()->last();
                        
                                if ($getOnpremiseInfo) {
                                    // Add the distributed amount to the balance
                                    $getOnpremiseInfo->balance -= $distributedamount;
                                    $getOnpremiseInfo->save();
                                }
                            }
                    $OnpremiseInfo = OnpremiseInfo::where('onpremise_id', $onpremse[0]['id'])->where('number_of_sign', '>', 0)->get();
                    $userObj = User::find($onpremse[0]['user_id']);
                     $userdetails = User::where('id', $onpremse[0]['user_id'])->first();
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }else{
                        $onpremse = onpremise::where('payment_id', $request['paymentId'])->where('hod_status', 'approved')->first();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($onpremse) {
                        
                            
                            $getOnpremiseInfo = Apphistory::where('onpremise_id', $onpremse->id)->get()->last();
                        
                            if ($getOnpremiseInfo) {
                                // Add the distributed amount to the balance
                                $getOnpremiseInfo->balance -= $amount;
                                $getOnpremiseInfo->save();
                            }
                            
                    $OnpremiseInfo = OnpremiseInfo::where('onpremise_id', $onpremse->id)->where('number_of_sign', '>', 0)->get();
                      $userObj = User::find($onpremse->user_id);
                     $userdetails = User::where('id', $onpremse->user_id)->first();
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }
                    
                    
             
             
                    $lcenLGAs = ["Apapa", "Eti-osa", "Ikoyi-Obalende", "Lekki Phase 1", "Lagos Mainland", "Lagos Island", "Surulere", "Aguda/Itire-Ikate"];
                    $leastLGAs = ["Epe", "Ibeju-Lekki", "Ikorodu", "Kosofe", "Magodo/Isheri", "Shomolu"];
                    $lwest1LGAs = ["Agege", "Ikeja", "Onigbongbo", "Computer Village", "Ifako-Ijaiye", "Mushin", "Oshodi/Isolo"];
                    $lwest2LGAs = ["Alimosho", "Ajeromi-Ifelodun", "Amuwo Odofin", "Badagry", "Ojo", "Mosan Okunola"];
                    
                     
                     if($request['applyToAccount'] == true){
                        if (in_array($onpremse[0]['lga'], $lcenLGAs)) {
                        // The value of $mobileInput['lga'] is one of the allowed LGAs
                        $zone = "Lagos Central";
                    }elseif(in_array($onpremse[0]['lga'], $leastLGAs)){
                        $zone = "Lagos East";
                    }elseif(in_array($onpremse[0]['lga'], $lwest1LGAs)){
                        $zone = "Lagos West 1";
                    }elseif(in_array($onpremse[0]['lga'], $lwest2LGAs)){
                        $zone = "Lagos West 2";
                    } else {
                        $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2" ];
                        $selectedKey = array_rand($listArray);
                        $selectValue = $listArray[$selectedKey];
                        $zone = $selectValue;
                    }
                    
                     $HODe = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->exists();
                     if($HODe){
                         $HOD = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->first();
                         $HODfn = $HOD->first_name;
                         $HODln = $HOD->last_name;
                     }else{
                         $HODfn = "Adekunle";
                         $HODln = "Afolabi";
                     }
                     
                     // Part 1: Current date in "Ymd" format (e.g., 2232024)
                     $part1 = date('Ymd');
                    
                     // Part 2: Random 3 uppercase letters (e.g., JJJ)
                     $part2 = strtoupper(Str::random(3));
                    
                     // Part 3: Random alphanumeric value (e.g., 1P)
                     $part3 = strtoupper(Str::random(2));
                    
                     // Part 4: Random number between 100000 and 999999 (e.g., 193974)
                     $part4 = mt_rand(100000, 999999);
                
                     // Combine all parts into the final string
                     $barcoden = "{$part1}-{$part2}-{$part3}-{$part4}";
                     
                            
                     $startdate = Carbon::parse($onpremse[0]['created_at'])->addMonth()->tz('Africa/Lagos');
                     $enddate = Carbon::parse($onpremse[0]['created_at'])->endOfYear();
                     
                            
                     $countDetails = count($OnpremiseInfo) - 1;
                     $comm = [];
                     if($countDetails == 0){
                     $commentt = strtoupper($OnpremiseInfo[0]['type_of_sign']);
                     }else{
                       for($i=0;$i <= $countDetails; $i++) {
                         $comm [] = $OnpremiseInfo[$i]['type_of_sign'];
                     }
                     $commentt = implode(", ", $comm);
                     }
                     $signTypes = [];
                     $quantitySigns = [];
            
                     for($i=0;$i <= $countDetails; $i++) {
                         $signTypes [] = $OnpremiseInfo[$i]['type_of_sign'];
                         $quantitySigns [] = $OnpremiseInfo[$i]['length_in_meter'] * $OnpremiseInfo[$i]['width_in_meter'];
                     }
                     $combinedArray = [];
                     foreach ($signTypes as $index => $value) {
                         $combinedArray [] = [
                             'key' => $value,
                             'value' => $quantitySigns[$index],
                            //  'words' => $this->getWordsofNumber($quantitySigns[$index]),
                         ];
                         
                     }
                     $amountInWord = UtilMethods::getAmountInWords($onpremse[0]['initial_amount_due'] - $request['price']);
                     $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $onpremse[0]['name_of_owner'],
                          'address' => $onpremse[0]['sign_address'],
                          'email' => $onpremse[0]['email'],
                          'cust_id' => $onpremse[0]['user_id'],
                          'ref_no' => $onpremse[0]['payment_id'],
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $onpremse[0]['initial_amount_due'],
                          'debit' => $amount,
                          'credit' => - $amount,
                          'note_type' => 'credit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'zone' => $zone,
                          'HOD_first_name' => $HODfn,
                          'HOD_last_name' => $HODln,
                          'barcode' => $barcoden,
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL CREDIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                     }else{
                         if (in_array($onpremse->lga, $lcenLGAs)) {
                        // The value of $mobileInput['lga'] is one of the allowed LGAs
                        $zone = "Lagos Central";
                    }elseif(in_array($onpremse->lga, $leastLGAs)){
                        $zone = "Lagos East";
                    }elseif(in_array($onpremse->lga, $lwest1LGAs)){
                        $zone = "Lagos West 1";
                    }elseif(in_array($onpremse->lga, $lwest2LGAs)){
                        $zone = "Lagos West 2";
                    } else {
                        $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2" ];
                        $selectedKey = array_rand($listArray);
                        $selectValue = $listArray[$selectedKey];
                        $zone = $selectValue;
                    }
                    
                     $HODe = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->exists();
                     if($HODe){
                         $HOD = UserAdmin::where('zone', $zone)->orWhere('zone2', $zone)->first();
                         $HODfn = $HOD->first_name;
                         $HODln = $HOD->last_name;
                     }else{
                         $HODfn = "Adekunle";
                         $HODln = "Afolabi";
                     }
                     
                     // Part 1: Current date in "Ymd" format (e.g., 2232024)
                     $part1 = date('Ymd');
                    
                     // Part 2: Random 3 uppercase letters (e.g., JJJ)
                     $part2 = strtoupper(Str::random(3));
                    
                     // Part 3: Random alphanumeric value (e.g., 1P)
                     $part3 = strtoupper(Str::random(2));
                    
                     // Part 4: Random number between 100000 and 999999 (e.g., 193974)
                     $part4 = mt_rand(100000, 999999);
                
                     // Combine all parts into the final string
                     $barcoden = "{$part1}-{$part2}-{$part3}-{$part4}";
                     
                            
                     $startdate = Carbon::parse($onpremse->created_at)->addMonth()->tz('Africa/Lagos');
                     $enddate = Carbon::parse($onpremse->created_at)->endOfYear();
                     
                            
                     $countDetails = count($OnpremiseInfo) - 1;
                     $comm = [];
                     if($countDetails == 0){
                     $commentt = strtoupper($OnpremiseInfo[0]['type_of_sign']);
                     }else{
                       for($i=0;$i <= $countDetails; $i++) {
                         $comm [] = $OnpremiseInfo[$i]['type_of_sign'];
                     }
                     $commentt = implode(", ", $comm);
                     }
                     $signTypes = [];
                     $quantitySigns = [];
            
                     for($i=0;$i <= $countDetails; $i++) {
                         $signTypes [] = $OnpremiseInfo[$i]['type_of_sign'];
                         $quantitySigns [] = $OnpremiseInfo[$i]['length_in_meter'] * $OnpremiseInfo[$i]['width_in_meter'];
                     }
                     $combinedArray = [];
                     foreach ($signTypes as $index => $value) {
                         $combinedArray [] = [
                             'key' => $value,
                             'value' => $quantitySigns[$index],
                            //  'words' => $this->getWordsofNumber($quantitySigns[$index]),
                         ];
                         
                     }
                     $amountInWord = UtilMethods::getAmountInWords($onpremse->initial_amount_due - $request['price']);
                         $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $onpremse->name_of_owner,
                          'address' => $onpremse->sign_address,
                          'email' => $onpremse->email,
                          'cust_id' => $onpremse->user_id,
                          'ref_no' => $onpremse->payment_id,
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $onpremse->initial_amount_due,
                          'debit' => $amount,
                          'credit' => - $amount,
                          'note_type' => 'credit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'zone' => $zone,
                          'HOD_first_name' => $HODfn,
                          'HOD_last_name' => $HODln,
                          'barcode' => $barcoden,
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL CREDIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                     }
                     
                    
                     $pdf = Pdf::loadView('CreditDebitNote', compact('data', 'combinedArray'))->setPaper('A3');
                     $fileObj = $pdf->download('CreditDebitNote.pdf');
                    
                     $body = "Please find credit note attached";
                     $templateData = [
                         'body' => $body,
                         'name' => $userObj->business_name
                     ];
                     $templateContent = view('hodeoitemplate', $templateData)->render();
                     UtilMethods::debitnotefirstparty($userObj->email, $templateContent, $fileObj);
                    
                    return response()->json(['success' => true, 'date' => 'credit note successfully sent'], 200);
                }
            }else if($request['productType'] == "outdoor"){
                if($request['type'] == "debit"){
                    if($request['applyToAccount'] == true){
                        $outdoor = ThirdPartyOutdoor::where('user_id', $id)->where('md_second_approval', 'approved')->where('bill_generated', 1)->get()->toArray();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($outdoor) {
                            $getObjcount = count($outdoor) - 1;
                            $distributedamount = $amount / count($outdoor);
            
                            // foreach($getOutDoorObj as $outdoors){
                            for ($i = 0; $i <= $getObjcount; $i++) {
                               $getOnpremiseInfo = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoor[$i]['id'])->get()->last();
                        
                                if ($getOnpremiseInfo) {
                                    // Add the distributed amount to the balance
                                    $getOnpremiseInfo->balance += $distributedamount;
                                    $getOnpremiseInfo->save();
                                } 
                            }
                            
                        $getOutdoorDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $outdoor[0]['id'])->get();
                        $userdetails = User::where('id', $outdoor[0]['user_id'])->first();
                      $userObj = User::find($outdoor[0]['user_id']);
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }else{
                        $outdoor = ThirdPartyOutdoor::where('payment_id', $request['paymentId'])->where('md_second_approval', 'approved')->where('bill_generated', 1)->first();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($outdoor) {
                        
                            
                            $getOnpremiseInfo = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoor->id)->get()->last();
                        
                            if ($getOnpremiseInfo) {
                                // Add the distributed amount to the balance
                                $getOnpremiseInfo->balance += $amount;
                                $getOnpremiseInfo->save();
                            }
                    
                    $getOutdoorDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $outdoor->id)->get();
                     $userdetails = User::where('id', $outdoor->user_id)->first();
                      $userObj = User::find($outdoor->user_id);
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }
                    $initial_amount = $getOutdoorDetails[0]['ads_price'] + $getOutdoorDetails[0]['legal_fee'];
                    $totalFee = bcadd($getOutdoorDetails[0]['ads_price'], $getOutdoorDetails[0]['legal_fee'], 2);
                    $getBillStartDate = Carbon::parse($getOutdoorDetails[0]['created_at']);
                    
                    $startdate = $getBillStartDate;
                     $enddate = Carbon::parse($getOutdoorDetails[0]['created_at'])->endOfYear();
                     
                    
                     $amountInWord = UtilMethods::getAmountInWords($getOnpremiseInfo->balance + $amount);
             
                     $commentt = strtoupper($getOutdoorDetails[0]['designation']);
                     
                     if($request['applyToAccount'] == true){
                            
                     $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $userdetails->business_name,
                          'address' => $outdoor[0]['address_proposed_site'],
                          'email' => $userdetails->email,
                          'cust_id' => $outdoor[0]['user_id'],
                          'ref_no' => $outdoor[0]['payment_id'],
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $getOnpremiseInfo->balance,
                          'debit' => $amount,
                          'credit' => $amount,
                          'note_type' => 'debit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL DEBIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                     
                     }else{
                         $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $userdetails->business_name,
                          'address' => $outdoor->address_proposed_site,
                          'email' => $userdetails->email,
                          'cust_id' => $outdoor->user_id,
                          'ref_no' => $outdoor->payment_id,
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $getOnpremiseInfo->balance,
                          'debit' => $amount,
                          'credit' => $amount,
                          'note_type' => 'debit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL DEBIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                     }
                     
                    
                     $pdf = Pdf::loadView('CreditDebitNote', compact('data'))->setPaper('A3');
                     $fileObj = $pdf->download('CreditDebitNote.pdf');
                    
                     $body = "Please find debit note attached";
                     $templateData = [
                         'body' => $body,
                         'name' => $userObj->business_name
                     ];
                     $templateContent = view('hodeoitemplate', $templateData)->render();
                     UtilMethods::debitnotethirdparty($userObj->email, $templateContent, $fileObj);
                    
                    return response()->json(['success' => true, 'date' => 'debit note successfully sent'], 200);
                }else if($request['type'] == "credit"){
                    if($request['applyToAccount'] == true){
                        $outdoor = ThirdPartyOutdoor::where('user_id', $id)->where('md_second_approval', 'approved')->get()->toArray();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($outdoor) {
                            $getObjcount = count($outdoor) - 1;
                            $distributedamount = $amount / count($outdoor);
            
                            // foreach($getOutDoorObj as $outdoors){
                            for ($i = 0; $i <= $getObjcount; $i++) {
                                
                                $getOnpremiseInfo = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoor[$i]['id'])->get()->last();
                            
                                if ($getOnpremiseInfo) {
                                    // Add the distributed amount to the balance
                                    $getOnpremiseInfo->balance -= $distributedamount;
                                    $getOnpremiseInfo->save();
                                }
                            }
                    $getOutdoorDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $outdoor[0]['id'])->get();
                     $userdetails = User::where('id', $outdoor[0]['user_id'])->first();
                      $userObj = User::find($outdoor[0]['user_id']);
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }else{
                        $outdoor = ThirdPartyOutdoor::where('payment_id', $request['paymentId'])->where('md_second_approval', 'approved')->first();
                        // $outdoor = ThirdPartyOutdoor::where('user_id', $id)->get()->toArray();
                        // $smallform = SmallFormatAds::where('user_id', $id)->get()->toArray();
                        if ($outdoor) {
                        
                            
                            $getOnpremiseInfo = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoor->id)->get()->last();
                        
                            if ($getOnpremiseInfo) {
                                // Add the distributed amount to the balance
                                $getOnpremiseInfo->balance -= $amount;
                                $getOnpremiseInfo->save();
                            }
                            
                    $getOutdoorDetails = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $outdoor->id)->get();
                     $userdetails = User::where('id', $outdoor->user_id)->first();
                      $userObj = User::find($outdoor->user_id);
                            
                        }else{
                            return response()->json(['error' => 'application is not eligible to perform this action'], 422);  
                        }
                    }
                    
                    $initial_amount = $getOutdoorDetails[0]['ads_price'] + $getOutdoorDetails[0]['legal_fee'];
                    $totalFee = bcadd($getOutdoorDetails[0]['ads_price'], $getOutdoorDetails[0]['legal_fee'], 2);
                    $getBillStartDate = Carbon::parse($getOutdoorDetails[0]['created_at']);
                    
                    $startdate = $getBillStartDate;
                     $enddate = Carbon::parse($getOutdoorDetails[0]['created_at'])->endOfYear();
                     
                    
                     $amountInWord = UtilMethods::getAmountInWords($getOnpremiseInfo->balance - $amount);
             
                     $commentt = strtoupper($getOutdoorDetails[0]['designation']);
                            
                    if($request['applyToAccount'] == true){
                     $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $userdetails->business_name,
                          'address' => $outdoor[0]['address_proposed_site'],
                          'email' => $userdetails->email,
                          'cust_id' => $outdoor[0]['user_id'],
                          'ref_no' => $outdoor[0]['payment_id'],
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $getOnpremiseInfo->balance,
                          'debit' => $amount,
                          'credit' => $amount,
                          'note_type' => 'credit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL CREDIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];
                    }else{
                      $data = [
                          'date' => Carbon::now()->format('jS F, Y'),
                          'company' => $userdetails->business_name,
                          'address' => $outdoor->address_proposed_site,
                          'email' => $userdetails->email,
                          'cust_id' => $outdoor->user_id,
                          'ref_no' => $outdoor->payment_id,
                          'user_type' => $userdetails->user_type,
                          'initial_amount_due' => $getOnpremiseInfo->balance,
                          'debit' => $amount,
                          'credit' => $amount,
                          'note_type' => 'credit',
                          'amount_in_words' => $amountInWord,
                          'startDate' => $startdate->format('jS F, Y'),
                          'endDate' => $enddate->format('jS F, Y'),
                          'comment' => $request['comments']
                        //   'comment' => 'ADDITIONAL CREDIT NOTE FOR ' . $commentt . ' RATE'
                          
                     ];  
                    }
                     
                    
                     $pdf = Pdf::loadView('CreditDebitNote', compact('data'))->setPaper('A3');
                     $fileObj = $pdf->download('CreditDebitNote.pdf');
                    
                     $body = "Please find credit note attached";
                     $templateData = [
                         'body' => $body,
                         'name' => $userObj->business_name
                     ];
                     $templateContent = view('hodeoitemplate', $templateData)->render();
                     UtilMethods::debitnotethirdparty($userObj->email, $templateContent, $fileObj);
                    
                    return response()->json(['success' => true, 'date' => 'credit note successfully sent'], 200);
                }
            }
        }else{
            return response()->json(['error' => 'You are not permitted to perfoem this action'], 422);  
        }
    }
    
    public function DebitNoteProdList($id, $productType){
        $user = Auth::user();
        if($productType == "premise"){
            $onpremse = onpremise::where('user_id', $id)->where('hod_status', 'approved')->where('billing_status', 'approved')->get()->toArray();
        }elseif($productType == "outdoor"){
            $onpremse = ThirdPartyOutdoor::where('user_id', $id)->where('md_second_approval', 'approved')->where('bill_generated', 1)->get()->toArray();
        }
        
        
        return response()->json(['success' => true, 'date' => $onpremse], 200);
    }
    
    public function outdoorReassign($id, $newadmin) {
        $user = Auth::user();
        $kycassign = KycThirdParty::where('user_id', $id)->first();
        if($user->admin_role_id == 2 || $user->admin_role_id == 3){
            if($kycassign){
                if((string)$kycassign->assigned_officer == (string)$user->id){
                    $getoutdoor = ThirdPartyOutdoor::where('user_id', $id)->where('assigned_officer', (string)$user->id)->get();

                    foreach ($getoutdoor as $outdoor) {
                        $outdoor->assigned_officer = (string)$newadmin;
                        $outdoor->save();
                    }
                }else{
                  return response()->json(['error' => 'You are not permitted to perform this action'], 422);  
                }
            }else{
               return response()->json(['error' => 'User not a Practitioner'], 422); 
            }
        }elseif($user->admin_role_id == 5){
            if($kycassign){
                $getoutdoor = ThirdPartyOutdoor::where('user_id', $id)->where('assigned_officer', (string)$kycassign->assigned_officer)->get();
                    foreach ($getoutdoor as $outdoor) {
                        $outdoor->assigned_officer = (string)$newadmin;
                        $outdoor->save();
                    }
            }else{
               return response()->json(['error' => 'User not a Practitioner'], 422); 
            }
        }elseif($user->admin_role_id == 7){
            if($kycassign){
                $getoutdoor = ThirdPartyOutdoor::where('user_id', $id)->where('assigned_officer', (string)$kycassign->assigned_officer)->get();
                    foreach ($getoutdoor as $outdoor) {
                        $outdoor->assigned_officer = (string)$newadmin;
                        $outdoor->save();
                    }
                $kycassign->assigned_officer = (string)$newadmin;
                $kycassign->save();
            }else{
               return response()->json(['error' => 'User not a Practitioner'], 422); 
            }
        }else{
            return response()->json(['error' => 'You are not permitted to perform this action'], 422);
        }
        return response()->json(["message" => "re-assigned successfully"], 200);
    }
    
    public function outdoorReverseReassign($id) {
        $user = Auth::user();
        $kycassign = KycThirdParty::where('user_id', $id)->first();
        if($user->admin_role_id == 2 || $user->admin_role_id == 3){
            if($kycassign){
                if((string)$kycassign->assigned_officer == (string)$user->id){
                    $getoutdoor = ThirdPartyOutdoor::where('user_id', $id)->get();
                    foreach ($getoutdoor as $outdoor) {
                        $outdoor->assigned_officer = (string)$kycassign->assigned_officer;
                        $outdoor->save();
                    }
                }else{
                  return response()->json(['error' => 'You are not permitted to perform this action'], 422);  
                }
            }else{
               return response()->json(['error' => 'User not a Practitioner'], 422); 
            }
        }elseif($user->admin_role_id == 5){
            if($kycassign){
                $getoutdoor = ThirdPartyOutdoor::where('user_id', $id)->get();
                foreach ($getoutdoor as $outdoor) {
                    $outdoor->assigned_officer = (string)$kycassign->assigned_officer;
                    $outdoor->save();
                }
            }else{
               return response()->json(['error' => 'User not a Practitioner'], 422); 
            }
        }else{
            return response()->json(['error' => 'You are not permitted to perform this action'], 422);
        }
        return response()->json(["message" => "re-assigned successfully"], 200);
    }

    public function registerUser(Request $request) {
        $validate = Validator::make($request->all(), [
            'first_name' => 'required|string|max:255',
            'last_name' => 'required|string|max:255',
            'business_name' => 'required|string|max:255',
            'phone_number' => 'required|string|min:11',
            'email' => 'required|string|email|max:255',
            'type' => 'required|string'
        ]);

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

        $userId = Auth::user()->id;

        $tokenExpires = Carbon::now()->addDays(7);
        //$userPassword = self::generatePassword();
        $userPassword =  '7£Zz9E!£1ygy';
        $hashPassword  = Hash::make($userPassword);
        $id = self::generateUserId();
        $newUser = new User();
        $newUser->id = $id;
        $newUser->first_name = $request['first_name'];
        $newUser->last_name = $request['last_name'];
        $newUser->business_name = $request['business_name'];
        $newUser->password = $hashPassword;
        $newUser->phone_number = $request['phone_number'];
        $newUser->email = $request['email'];
        $newUser->user_type = $request['type'];
        $newUser->created_by = $userId;

        try {
            $newUser->save();
        } catch (Illuminate\Database\QueryException  $ex) {
            $errorCode = $ex->errorInfo[1];
            if ($errorCode == 1062) {
                Log::error("Duplicate entry  error: " .$ex->getMessage());
                return response()->json(['error' =>  $ex->getMessage()], 500);

            }
        }

        $success['token'] = $newUser->createToken('lasaa-api', ['*'], ['expires_at' => $tokenExpires])->accessToken;
        if(ctype_digit($request->phone_number)) {
            $modifyPhoneNumber = substr($request->phone_number, 1);
            $prepend = '234';
            $modifyPhoneNumber = $prepend . $modifyPhoneNumber;
        }

        $verifycode = $this->generateEmailToken();
        $verifycode = (string) $verifycode;
       $this->sendsmsV2($modifyPhoneNumber, $verifycode);
        //$this->composePasswordEmail('Password', $userPassword, $request->email);
        $templateData = [
            'body' => $verifycode,
            'name' => $request->first_name,
        ];

        $templateData2 = [
            'body' => $userPassword,
            'name' => $request->first_name,
        ];
        $templateContent = view('emailtemplate', $templateData)->render();
        $templateContent2 = view('emailtemplate', $templateData2)->render();
        $this->composeEmailV2('OTP', $request->email,  $templateContent);
        $this->composeEmailV2('Password', $request->email,  $templateContent2);
       $this->sendsmsPassword($modifyPhoneNumber, $userPassword);
        User::where('id', $id)->update(['verify_code' => $verifycode]);
        $getUserObj = User::find($id);
        $wallet = new UserWallet();
        $getUserObj->userWallet()->save($wallet);
        $user = Auth::user();
        $activityInfo = new AdminActivity();
        $fetchActivity = 'Create new user account';
        $activityInfo->action = $fetchActivity;
        $activityInfo->user_admin_id = (string)$user->id;
        $activityInfo->save();
        return response()->json(["message" => "registered successfully"], 200);
    }

//    public function registerUser(Request $request) {
//        $validator = Validator::make($request->all(), [
//            'first_name' => 'required|string|max:255',
//            'last_name' => 'required|string|max:255',
//            'business_name' => 'required|string|max:255',
//            'phone_number' => 'required|string|min:11',
//            'email' => 'required|string|email|max:255',
//            'type' => 'required|string'
//        ]);
//
//        if($validator->fails()) {
//            return response()->json(['errors' => $validator->errors()->all()], 422);
//        }
//        $userId = Auth::user()->id;
//
//        DB::beginTransaction();
//
//        try {
//            $tokenExpires = Carbon::now()->addDays(7);
//            $userPassword =  '7£Zz9E!£1ygy';
//            $hashPassword  = Hash::make($userPassword);
//            $id = self::generateUserId();
//            $newUser = new User();
//            $newUser->id = $id;
//            $newUser->first_name = $request['first_name'];
//            $newUser->last_name = $request['last_name'];
//            $newUser->business_name = $request['business_name'];
//            $newUser->password = $hashPassword;
//            $newUser->phone_number = $request['phone_number'];
//            $newUser->email = $request['email'];
//            $newUser->user_type = $request['type'];
//           $newUser->created_by = $userId;
//            try {
//                $newUser->save();
//            } catch (Illuminate\Database\QueryException  $ex) {
//                $errorCode = $ex->errorInfo[1];
//                if ($errorCode == 1062) {
//                    Log::error("Duplicate entry  error: " .$ex->getMessage());
//                    return response()->json(['error' =>  $ex->getMessage()], 500);
//                }
//            }
//            $getUserObj = User::find($id);
//            $wallet = new UserWallet();
//            $getUserObj->userWallet()->save($wallet);
//            DB::commit();
//
//            $success['token'] = $newUser->createToken('lasaa-api', ['*'], ['expires_at' => $tokenExpires])->accessToken;
//            if(ctype_digit($request->phone_number)) {
//                $modifyPhoneNumber = substr($request->phone_number, 1);
//                $prepend = '234';
//                $modifyPhoneNumber = $prepend . $modifyPhoneNumber;
//            }
//
//            $verifycode = $this->generateEmailToken();
//            $verifycode = (string) $verifycode;
//            //$this->composeEmail('OTP', $verifycode, $request->email);
//
//            $templateData = [
//                'body' => $verifycode,
//                'name' => $request->first_name,
//            ];
//            $templateContent = view('emailtemplate', $templateData)->render();
//            $this->composeEmailV2('OTP', $request->email,  $templateContent);
//            $this->sendsmsV2($modifyPhoneNumber, $verifycode);
//            User::where('id', $id)->update(['verify_code' => $verifycode]);
//            $user = Auth::user();
//            $activityInfo = new AdminActivity();
//            $fetchActivity = 'Create new user account';
//            $activityInfo->action = $fetchActivity;
//            $activityInfo->user_admin_id = (string)$user->id;
//            $activityInfo->save();
//            return response()->json(["message" => "registered successfully"], 200);
//        } catch (\Exception $exception) {
//            DB::rollBack();
//
//            return response()->json(['error' => 'Unable to create user'], 422);
//        }
//
//    }

    public function createMobileAdsforUser(Request $request) {
        $validate = Validator::make($request->all(), [
            'user_id' => 'required|string',
            'brand_name' => 'required|string',
            'lga' => 'required|string',
            'applicationForm' => 'present|array',
            'applicationForm.vehicleInfo.*.image_montage' => 'required|string',
            'applicationForm.vehicle_branding.*.vehicle_license' => 'nullable|array',
            'applicationForm.vehicle_branding.*.vehicle_type' => 'required|string',
            'applicationForm.vehicle_branding.*.excel_file' =>'nullable|string',
            'applicationForm.vehicle_branding.*.branding_details' => 'required|string',
        ]);

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

        $mobileInput = $request->all();
        $count = count($mobileInput['applicationForm']['vehicleInfo']) - 1;
        $countBranding = count($mobileInput['applicationForm']['vehicle_branding']) - 1;

        $userId = $request['user_id'];
        $userObj = User::find($userId);

        $mobileApplication = new mobilead();
        $mobileApplication->payment_id  = $this->mobileAdsPaymentId();
        //$mobileApplication->branding_details = $mobileInput['branding_details'];
        $mobileApplication->brand_name = $mobileInput['brand_name'];
        $mobileApplication->lga = $mobileInput['lga'];
        $lcenLGAs = ["Apapa", "Eti-osa", "Ikoyi-Obalende", "Lekki Phase 1", "Lagos Mainland", "Lagos Island", "Surulere", "Aguda/Itire-Ikate"];
        $leastLGAs = ["Epe", "Ibeju-Lekki", "Ikorodu", "Kosofe", "Magodo/Isheri", "Shomolu"];
        $lwest1LGAs = ["Agege", "Ikeja", "Onigbongbo", "Computer Village", "Ifako-Ijaiye", "Mushin", "Oshodi/Isolo"];
        $lwest2LGAs = ["Alimosho", "Ajeromi-Ifelodun", "Amuwo Odofin", "Badagry", "Ojo", "Mosan Okunola"];
        if (in_array($mobileInput['lga'], $lcenLGAs)) {
            // The value of $mobileInput['lga'] is one of the allowed LGAs
            $zone = "Lagos Central";
        }elseif(in_array($mobileInput['lga'], $leastLGAs)){
            $zone = "Lagos East";
        }elseif(in_array($mobileInput['lga'], $lwest1LGAs)){
            $zone = "Lagos West 1";
        }elseif(in_array($mobileInput['lga'], $lwest2LGAs)){
            $zone = "Lagos West 2";
        } else {
            $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2" ];
            $selectedKey = array_rand($listArray);
            $selectValue = $listArray[$selectedKey];
            $zone = $selectValue;
        }
        $mobileApplication->zone = $zone;
        //$mobileApplication->vehicle_type = $mobileInput['vehicle_type'];
//        $rmRole = [2,3];
//        if($zone == "") {
//            $getAssigned = UserAdmin::where('department', 'M_I')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
//        } else {
//            $getAssigned = UserAdmin::where('department', 'M_I')->where('zone', $zone)->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
//        }
//        $OfficerCounts = [];
//        foreach ($getAssigned as $Officer) {
//            // Count occurrences of each name in the database
//            $counter = mobilead::where('assigned_officer', (string)$Officer)->count();
//
//            // Store the count in the associative array
//            $OfficerCounts[$Officer] = $counter;
//        }
//
//        $leastAppearedOfficer = array_search(min($OfficerCounts), $OfficerCounts);
//
//        $getAssignedOfficer = UserAdmin::where('id', (string)$leastAppearedOfficer)->first();
//
//        // var_dump($getAssignedOfficer[0]['admin_role_id']); die();
//        // $mobileApplication->assigned_officer = (string)$getAssignedOfficer[0]['id'];
//        $mobileApplication->assigned_officer = (string)$leastAppearedOfficer;
        // var_dump($getAssignedOfficer[0]['id']);die();
        $user = $userObj->mobilead()->save($mobileApplication);
        $output [] = $user;

        for ($i=0; $i <= $count; $i++ ) {
            $mobileAdsId = mobilead::find($output[0]['id']);
            $vehicleApplication = new VehicleMobileAds();

            $image64String = $mobileInput['applicationForm']['vehicleInfo'][$i]['image_montage'];
            $vehicleApplication->image_montage = $this->imageNamingSaving($image64String);
            $user1 = $mobileAdsId->vehicleMobile()->save($vehicleApplication);
        }

        $excelDataArray = []; // Initialize array outside the loop

        $countlienceDataArray = []; // Initialize array outside the loop

        for ($k = 0; $k <= $countBranding; $k++) {
            if ($mobileInput['applicationForm']['vehicle_branding'][$k]['excel_file'] != null) {
                $getExcelFile = $mobileInput['applicationForm']['vehicle_branding'][$k]['excel_file'];
                $excelDataArray[$k] = $this->convertExcelToCSV($getExcelFile); // Assign value to the array
            }else{
                $countlienceDataArray[$k] = $mobileInput['applicationForm']['vehicle_branding'][$k]['vehicle_license'];
            }
        }

        foreach ($excelDataArray as $k => $excelcountData) {
            $excelcount = count($excelcountData) - 1;

            for ($j = 0; $j <= $excelcount; $j++) {
                // Access data using $key
                $vehicleLicense = new MobileAdsVehicleLicense();
                $vehicleLicense->vehicle_type = $mobileInput['applicationForm']['vehicle_branding'][$k]['vehicle_type'];
                $vehicleLicense->branding_details = $mobileInput['applicationForm']['vehicle_branding'][$k]['branding_details'];
                $vehicleLicense->vehicle_license = $excelcountData[$j];
                $license = $mobileAdsId->mobileAdsVehicleLicense()->save($vehicleLicense);
            }
        }

        foreach ($countlienceDataArray as $key => $countlienceData) {
            $countlience = count($countlienceData) - 1;

            for ($j = 0; $j <= $countlience; $j++) {
                // Access data using $key
                $vehicleLicense = new MobileAdsVehicleLicense();
                $vehicleLicense->vehicle_type = $mobileInput['applicationForm']['vehicle_branding'][$key]['vehicle_type'];
                $vehicleLicense->branding_details = $mobileInput['applicationForm']['vehicle_branding'][$key]['branding_details'];
                $vehicleLicense->vehicle_license = $countlienceData[$j];
                $license = $mobileAdsId->mobileAdsVehicleLicense()->save($vehicleLicense);
            }
        }

//        $getCurrentStep = AdminRole::where('id', $getAssignedOfficer->admin_role_id)->get();
//        $permitStep = new PermitStepMobile();
//        $permitStep->purpose =  'New Mobile Application';
//        $permitStep->current_steps = $getCurrentStep['0']['role'];
//        $mobileAdsId->permitStepMobile()->save($permitStep);
        $responses = mobilead::where('id', $output[0]['id'])->with('vehicleMobile')->get();
        $user = Auth::user();
        $activityInfo = new AdminActivity();
        $fetchActivity = 'Created Mobile ads for' . $mobileInput['user_id'];
        $activityInfo->action = $fetchActivity;
        $activityInfo->user_admin_id = (string)$user->id;
        $activityInfo->save();
        return  response()->json(['data' => $responses], 200);

    }

    public function createThirdPartyMobileforUser(Request $request) {
        $validate = Validator::make($request->all(), [
            'user_id' => 'required|string',
            'brand_name' => 'required|string',
            'start_date' => 'required|date',
            'duration' => 'required|string',
            'apcon_number' => 'required|string',
            'applicationForm' => 'present|array',
            'applicationForm.vehicleInfo.*.image_montage' => 'required|string',
            'applicationForm.vehiclebranding.*.vehicle_type' => 'required|string',
            'applicationForm.vehiclebranding.*.excel_file' =>'nullable|string',
            'applicationForm.vehiclebranding.*.vehicle_license' => 'nullable|array'
        ]);

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

        $thirdPartyMobile = $request->all();
        $count = count($thirdPartyMobile['applicationForm']['vehicleInfo']) - 1;
        $countBranding = count($thirdPartyMobile['applicationForm']['vehiclebranding']) - 1;
        //$countlience = count($thirdPartyMobile['applicationForm']['vehicle_license']) - 1;
        $userId = $thirdPartyMobile['user_id'];
        $userIdd =User::find($userId);
        $thirdPartyMobileApplication = new ThirdPartyMobile();
        $thirdPartyMobileApplication->payment_id  = $this->thirdPartyMobilePaymentId();
        //$thirdPartyMobileApplication->branding_details = $thirdPartyMobile['branding_details'];
        $thirdPartyMobileApplication->brand_name = $thirdPartyMobile['brand_name'];
        $thirdPartyMobileApplication->start_date = $thirdPartyMobile['start_date'];
        $thirdPartyMobileApplication->duration = $thirdPartyMobile['duration'];
        //$thirdPartyMobileApplication->vehicle_type = $thirdPartyMobile['vehicle_type'];
        $thirdPartyMobileApplication->apcon_number = $thirdPartyMobile['apcon_number'];
        $rmRole = [2,3];

        $getAssigned = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
        $OfficerCounts = [];
        foreach ($getAssigned as $Officer) {
            // Count occurrences of each name in the database
            $counter = ThirdPartyMobile::where('assigned_officer', (string)$Officer)->count();

            // Store the count in the associative array
            $OfficerCounts[$Officer] = $counter;
        }

        // Find the name that appeared the least
        $leastAppearedOfficer = array_search(min($OfficerCounts), $OfficerCounts);
        $getAssignedOfficer = UserAdmin::where('id', (string)$leastAppearedOfficer)->first();


        // $getAssignedOfficer = UserAdmin::where('department', 'M_I')->whereIn('admin_role_id', $rmRole)->inRandomOrder()->get();
        //var_dump($getAssignedOfficer[0]['id']); die();
        $thirdPartyMobileApplication->assigned_officer = (string)$leastAppearedOfficer;
        $user = $userIdd->thirdPartyMobile()->save($thirdPartyMobileApplication);
        $output [] = $user;

        for ($i=0; $i <= $count; $i++ ) {
            $thirdPartyId = ThirdPartyMobile::find($output[0]['id']);
            $vehicleApplication = new VehicleThirdPartyMobile();
            $image64String = $thirdPartyMobile['applicationForm']['vehicleInfo'][$i]['image_montage'];
            $vehicleApplication->image_montage = $this->imageNamingSaving($image64String);
            $user1 = $thirdPartyId->vehicleThirdPartyMobile()->save($vehicleApplication);

        }

        $excelDataArray = [];
        $countlienceDataArray = [];

        for ($k = 0; $k <= $countBranding; $k++) {
            if ($thirdPartyMobile['applicationForm']['vehiclebranding'][$k]['excel_file'] != null) {
                $getExcelFile = $thirdPartyMobile['applicationForm']['vehiclebranding'][$k]['excel_file'];
                $excelDataArray[$k] = $this->convertExcelToCSV($getExcelFile); // Assign value to the array
            }else{
                $countlienceDataArray[$k] = $thirdPartyMobile['applicationForm']['vehiclebranding'][$k]['vehicle_license'];
            }
        }

        foreach ($excelDataArray as $k => $excelcountData) {
            $excelcount = count($excelcountData) - 1;

            for ($j = 0; $j <= $excelcount; $j++) {
                // Access data using $key
                $vehicleLicense = new ThirdPartyMobileVehicleLicense();
                $vehicleLicense->vehicle_type = $thirdPartyMobile['applicationForm']['vehiclebranding'][$k]['vehicle_type'];
//                $vehicleLicense->branding_details = $thirdPartyMobile['applicationForm']['vehiclebranding'][$k]['branding_details'];
                $vehicleLicense->vehicle_license = $excelcountData[$j];
                $license = $thirdPartyId->thirdPartyMobileVehicleLincense()->save($vehicleLicense);
            }
        }

        foreach ($countlienceDataArray as $key => $countlienceData) {
            $countlience = count($countlienceData) - 1;

            for ($j = 0; $j <= $countlience; $j++) {
                // Access data using $key
                $vehicleLicense = new ThirdPartyMobileVehicleLicense();
                $vehicleLicense->vehicle_type = $thirdPartyMobile['applicationForm']['vehiclebranding'][$key]['vehicle_type'];
//                $vehicleLicense->branding_details = $thirdPartyMobile['applicationForm']['vehiclebranding'][$key]['branding_details'];
                $vehicleLicense->vehicle_license = $countlienceData[$j];
                $license = $thirdPartyId->thirdPartyMobileVehicleLincense()->save($vehicleLicense);
            }
        }

        $getCurrentStep = AdminRole::where('id', $getAssignedOfficer->admin_role_id)->get();
        $permitStep =  new ThirdPartyMobilePermitStep();
        $permitStep->purpose =  'New Third Party Mobile Application';
        $permitStep->current_steps = $getCurrentStep['0']['role'];
        $thirdPartyId->thirdPartyMobilePermitStep()->save($permitStep);
        $responses = ThirdPartyMobile::where('id', $output[0]['id'])->with('VehicleThirdPartyMobile')->get();
        $user = Auth::user();
        $activityInfo = new AdminActivity();
        $fetchActivity = 'Created Third Party Mobile ads for' . $thirdPartyMobile['user_id'];
        $activityInfo->action = $fetchActivity;
        $activityInfo->user_admin_id = (string)$user->id;
        $activityInfo->save();
        return  response()->json(['data' => $responses], 200);

    }

    public function createStreetLampforUser(Request $request) {

        $validate = Validator::make($request->all(), [
            'user_id' => 'required|string',
            'name_of_display' => 'required|string',
            'purpose' => 'required|string',
            'material_for_deployment' => 'nullable|string',
            'source_of_electricity' => 'nullable|string',
            'start_date' => 'required|string',
            'type_of_sign' => 'required|string|in:LED,FLEX,BACKLIT',
            'location_of_generator' => 'nullable|string',
            'authorization_letter_lseb' => 'nullable|string',
            'duration' => 'required|string',
            'height_sign' => 'required|integer',
            'width_sign' => 'required|integer',
            'weight_sign' => 'required|integer',
            'photo_montage' => 'required|string',
            'streetlampform' => 'present|array',
            'streetlampform.streetlampinfo.*.site_address' => 'required|string',
            'streetlampform.streetlampinfo.*.owner_consent' =>'nullable|string',
            'streetlampform.streetlampinfo.*.number_poles' => 'required|integer',
        ]);

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

        $paymentId =  $this->streetLampPaymentId();
        $streetLampsInput = $request->all();
        $userId = $request['user_id'];
        $userObj =  User::find($userId);
        $streetLampApplication = new StreetLampsAds();
        $streetLampApplication->name_of_display = $streetLampsInput['name_of_display'];
        $streetLampApplication->material_for_deployment = $streetLampsInput['material_for_deployment'];
        $streetLampApplication->duration = $streetLampsInput['duration'];
        $streetLampApplication->source_of_electricity = $streetLampsInput['source_of_electricity'];
        $streetLampApplication->start_date = $streetLampsInput['start_date'];
        $streetLampApplication->location_of_generator = $streetLampsInput['location_of_generator'];
        $authorizationLetter = $streetLampsInput['authorization_letter_lseb'];

        if($authorizationLetter != null){
            $streetLampApplication->authorization_letter_lseb = $this->convertBase64toPdf($authorizationLetter);
        }

        $streetLampApplication->payment_id = $paymentId;
        $rmRole = [2,3];
        $getAssigned = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();

        $OfficerCounts = [];
        foreach ($getAssigned as $Officer) {
            // Count occurrences of each name in the database
            $counter = StreetLampsAds::where('assigned_officer', (string)$Officer)->count();
            // Store the count in the associative array
            $OfficerCounts[$Officer] = $counter;
        }

        // Find the name that appeared the least
        $leastAppearedOfficer = array_search(min($OfficerCounts), $OfficerCounts);

        $getAssignedOfficer = UserAdmin::where('id', (string)$leastAppearedOfficer)->first();
        // var_dump($OfficerCounts);die();
        // $getAssignedOfficer = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->inRandomOrder()->get();
        // var_dump($getAssignedOfficer[0]['id']); die();
        $streetLampApplication->assigned_officer = (string)$leastAppearedOfficer;
        $saveLamps   = $userObj->streetLamps()->save($streetLampApplication);
        $output [] = $saveLamps;

        $count = count($streetLampsInput['streetlampform']['streetlampinfo']) - 1;

        for ($i=0; $i <= $count ; $i++) {
            $price = 0;
            if ($streetLampsInput['type_of_sign'] == 'FLEX') {
                $p = $i +1;
                $price += 50000 * $p;
            }
            if ($streetLampsInput['type_of_sign'] == 'BACKLIT') {
                $p = $i +1;
                $price += 50000 * $p;
            }
            if ($streetLampsInput['type_of_sign'] == 'LED') {
                $p = $i +1;
                $price += 50000 * $p;
            }

            $streetInfo = new StreetLampInfo();
            $streetInfo->type_of_sign = $streetLampsInput['type_of_sign'];
            $streetInfo->height_sign = $streetLampsInput['height_sign'];
            $streetInfo->width_sign = $streetLampsInput['width_sign'];
            $streetInfo->weight_sign = $streetLampsInput['weight_sign'];
            $streetInfo->site_address = $streetLampsInput['streetlampform']['streetlampinfo'][$i]['site_address'];
            $pdfOwnerConsent = $streetLampsInput['streetlampform']['streetlampinfo'][$i]['owner_consent'];
            if($pdfOwnerConsent != null){
                $streetInfo->owner_consent = $this->convertBase64toPdf($pdfOwnerConsent);
            }
            $streetLamp64String = $streetLampsInput['photo_montage'];
            $streetInfo->photo_montage = $this->imageNamingSaving($streetLamp64String);
            $streetInfo->number_poles = $streetLampsInput['streetlampform']['streetlampinfo'][$i]['number_poles'];
            $streetLampId = StreetLampsAds::find($output[0]['id']);
            $streetLampId->streetLampInfo()->save($streetInfo);

        }

        $appHistoryStreet = new AppHistoryStreetLamp();
        $streetLampId = StreetLampsAds::find($output[0]['id']);
        $appHistoryStreet->purpose = $streetLampsInput['purpose'];
        $appHistoryStreet->ads_price = $price;
        $newAdd = $streetLampId->appHistoryStreetLamp()->save($appHistoryStreet);

        $getCurrentStep = AdminRole::where('id', $getAssignedOfficer->admin_role_id)->get();
        $premitStreetLamp = new  PermitStepStreetLamp();
        $premitStreetLamp->purpose = $streetLampsInput['purpose'];
        $premitStreetLamp->current_steps = $getCurrentStep['0']['role'];
        $newSteps = $streetLampId->permitStepStreetLamp()->save($premitStreetLamp);
        $reponses = StreetLampsAds::where('id',  $streetLampId->id)->with(['appHistoryStreetLamp', 'permitStepStreetLamp' ])->get();
        $user = Auth::user();
        $activityInfo = new AdminActivity();
        $fetchActivity = 'Created Street Lamp pole ads for' . $streetLampsInput['user_id'];
        $activityInfo->action = $fetchActivity;
        $activityInfo->user_admin_id = (string)$user->id;
        $activityInfo->save();
        $totalprice = AppHistoryStreetLamp::where('street_lamps_ads_id', $streetLampId->id)->sum('ads_price');
        return response()->json(['success'  => true, 'total_price' =>  $totalprice, 'additionalInfo' => env('STREETLAMPPOLES_BACK'),
            'paymentID' => $paymentId ], 200);
    }

//    public function  createExpressionofInterestforStreetLampUser(Request $request) {
//
//        $validate = Validator::make($request->all(), [
//            'user_id' => 'required|string',
//            'letter_interest' => 'required|string',
//        ]);
//
//        if($validate->fails()) {
//            return response()->json(['errors' => $validate->errors()->all()], 422);
//        }
//
//        $expressionStreetLamp = $request->all();
//        $userId = $request['user_id'];
//
//        $userObj = User::find($userId);
//        $expressionApplication = new ExpressionOfStreetLamps();
//        $letterInterest64String = $expressionStreetLamp['letter_interest'];
//        $expressionApplication->letter_interest = $this->convertBase64toPdf($letterInterest64String);
//        $saveInfo = $userObj->expressionOfStreetLamps()->save($expressionApplication);
//        $output [] =  $saveInfo;
//
//        $expressionInfo = ExpressionOfStreetLamps::where('id', $output[0]['id'])->get();
//        return response() ->json(['data' => $expressionInfo], 200);
//    }

    public function createOnpremiseforUser(Request $request) {

        $validate = Validator::make($request->all(), [
            'user_id' => 'required|string',
            'purpose' => 'required|string',
            'sign_address' => 'required|string',
            'name_of_owner' => 'required|string',
            'phone_number' => 'required|string',
            'email' => 'nullable|email',
            'property_type' => 'required|string',
            'lga' => 'required|string',
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.type_of_sign' => 'required|string',
            'onpremiseform.onpremiseinfo.*.number_of_sign' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.length_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.width_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.photo_montage' => 'required|string'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = $onpremiseInput['user_id'];
        $pid = $this->onpremisePaymentId();
        $userObj =User::find($userId);
        $onpremiseApplication  = new onpremise();
        $onpremiseApplication->sign_address = $onpremiseInput['sign_address'];
        $onpremiseApplication->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseApplication->name_of_owner = $onpremiseInput['name_of_owner'];
        $onpremiseApplication->phone_number = $onpremiseInput['phone_number'];
        $onpremiseApplication->email = $onpremiseInput['email'];
        $onpremiseApplication->property_type = $onpremiseInput['property_type'];
        $onpremiseApplication->lga = $onpremiseInput['lga'];
        $onpremiseApplication->payment_id = $pid;
        $user = $userObj->onpremise()->save($onpremiseApplication);
        $output []  = $user;
        $price = 0;

        for($i=0;  $i<=$count;  $i++) {
            $calculatePrice [] = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['type_of_sign'];
            $onpremiseInfo = new OnpremiseInfo();
            $onpremiseInfo->type_of_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['type_of_sign'];
            $onpremiseInfo->number_of_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['number_of_sign'];
            $onpremiseInfo->length_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['length_in_meter'];
            $onpremiseInfo->width_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['width_in_meter'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            $onpremiseInfo->photo_montage = $this->imageNamingSaving($image64String);
            $onpremiseId = onpremise::find($output[0]['id']);
            $onpremiseInfoSave = $onpremiseId->onpremiseInfo()->save($onpremiseInfo);
        }

        if($onpremiseInput['property_type'] == 'Single Business Unit'){
            if ($i > 1 && in_array('LED Sign', $calculatePrice)){
                $price  += 511000;
            }elseif($i == 1 && in_array('LED Sign', $calculatePrice)){
                $price  += 500000;
            }elseif ($i >1 && !in_array('LED Sign', $calculatePrice)){
                $price  += 11000;
            }elseif($i == 1 && !in_array('LED Sign', $calculatePrice)){
                $price  += 11000;
            }
        } elseif ($onpremiseInput['property_type'] == 'Multi-tenanted Business'){
            if($i > 1 && in_array('LED Sign', $calculatePrice)) {
                $price += 506000;
            } elseif ($i == 1 && in_array('LED Sign', $calculatePrice)) {
                $price += 500000;
            }elseif ($i >1 && !in_array('LED Sign', $calculatePrice)) {
                $price += 6000;
            } elseif($i == 1 && !in_array('LED Sign', $calculatePrice)) {
                $price += 6000;
            }
        }

        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($output[0]['id']);
        $appHistory->purpose = $onpremiseInput['purpose'];
        $appHistory->ads_price = $price;
        $newUser = $onpremiseId->appHistory()->save($appHistory);
        $permitOnpermise = new PermitStepOnpremise();
        $permitOnpermise->purpose = $onpremiseInput['purpose'];
        $newSteps = $onpremiseId->permitStepOnpremise()->save($permitOnpermise);
        $user = Auth::user();
        $activityInfo = new AdminActivity();
        $fetchActivity = 'Created On premise  ads for' . $onpremiseInput['user_id'];
        $activityInfo->action = $fetchActivity;
        $activityInfo->user_admin_id = (string)$user->id;
        $activityInfo->save();
        $totalprice [] = Apphistory::where('onpremise_id', $onpremiseId->id)->sum('ads_price');
        $totalSum = array_sum(array_map('intval', $totalprice));
        return response()->json(['success' => true, 'total_price' =>  $totalSum, 'additionalInfo' => env('ONPREMISE_BACK'), 'paymentID' => $pid], 200);

    }

    public function getWalletTransaction(Request $request) {

        if(Auth::user()->admin_role_id == 8 || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 10 ) {

            $keyword = $request->input('search');
            $items = $request->input('items');

            $getTransdetails = WalletTransaction::with(['userWallet','userWallet.user']); // Start a query builder instance

            if ($keyword) {
                $getTransdetails->where(function ($query) use ($keyword) {
                    $query->where('transaction_name', 'like', '%' . $keyword . '%')
                        ->orWhere('company_name', 'like', '%' . $keyword . '%')
                        ->orWhere('transaction_id', 'like', '%' . $keyword . '%')
                        ->orWhere('transaction_type', 'like', '%' . $keyword . '%');
                });
            }

            if ($items) {
                $getTransdetails->where(function ($query) use ($items) {
                    $query->where('transaction_name', 'like', '%' . $items . '%')
                        ->orWhere('company_name', 'like', '%' . $items . '%')
                        ->orWhere('transaction_id', 'like', '%' . $items . '%')
                        ->orWhere('transaction_type', 'like', '%' . $items . '%');
                });

                $getTransdetails->orWhereHas('userWallet.user', function ($query) use ($items) {
                    $query->where('id', $items);
                });
            }

            $item = $getTransdetails->orderBy('created_at', 'desc')->paginate(20);

            return response()->json(['data' => $item], 200);
        } else {
            return  response()->json(['data' => 'Can not view resource'], 422);
        }
    }

    public function updateUserWalletBalance(Request $request, $transactionId) {

        if(Auth::user()->admin_role_id == 8 || Auth::user()->admin_role_id == 6) {
            $validate =Validator::make($request->all(), [
                'status' => 'required|string',
                'comment' => 'nullable|string',
                'reference' => 'nullable|string'
            ]);


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

            $getWalletTransaction = WalletTransaction::where('transaction_id',  $transactionId)->get();
            $getTransactionStatus = $getWalletTransaction[0]['status'];

            if($getTransactionStatus == 'pending') {
                $updateTransaction = WalletTransaction::where('transaction_id', $transactionId)->update(['status' => $request['status'],
                    'comment' => $request['comment'], 'transaction_reference' => $request['reference']]);

                $getTransaction = WalletTransaction::where('transaction_id', $transactionId)->get();
                $getWalletId = $getTransaction[0]['user_wallet_id'];

                if ($getTransaction[0]['status'] == 'completed') {

                    $getCurrentBalance = UserWallet::where('id', $getWalletId)->get();
                    //var_dump($getCurrentBalance[0]['streetlamp_processing_balance']); die();
                    $userId = $getCurrentBalance[0]['user_id'];
                    $amountTransact = $getTransaction[0]['transaction_amount'];
                    $getTransactionType = $getTransaction[0]['transaction_type'];

                    if ($getTransactionType == 'Application Fee') {

                        $getApplicationBalance = $getCurrentBalance[0]['application_balance'];
                        $newBalance = $getApplicationBalance + $amountTransact;
                        UserWallet::where('id', $getWalletId)->update(['application_balance' => $newBalance]);
                        $mobileBalance = $getCurrentBalance[0]['mobile_balance'];
                        $pavBalance = $getCurrentBalance[0]['pav_balance'];
                        $streetLampprocessing = $getCurrentBalance[0]['streetlamp_processing_balance'];
                        $streetLampAdminBalance = $getCurrentBalance[0]['streetlamp_administrative_balance'];
                        $totalBalance = $mobileBalance + $pavBalance + $streetLampprocessing + $streetLampAdminBalance + $newBalance;
                        UserWallet::where('id', $getWalletId)->update(['balance' => $totalBalance]);
                    } elseif ($getTransactionType == 'Mobile Adverts') {

                        $getMobileBalance = $getCurrentBalance[0]['mobile_balance'];
                        $newBalance = $getMobileBalance + $amountTransact;
                        UserWallet::where('id', $getWalletId)->update(['mobile_balance' => $newBalance]);
                        $applicationBalance = $getCurrentBalance[0]['application_balance'];
                        $pavBalance = $getCurrentBalance[0]['pav_balance'];
                        $streetLampprocessing = $getCurrentBalance[0]['streetlamp_processing_balance'];
                        $streetLampAdminBalance = $getCurrentBalance[0]['streetlamp_administrative_balance'];
                        $totalBalance = $applicationBalance + $pavBalance + $streetLampprocessing + $streetLampAdminBalance + $newBalance;
                        UserWallet::where('id', $getWalletId)->update(['balance' => $totalBalance]);
                    } elseif ($getTransactionType == 'PAVs') {

                        $getPavBalance = $getCurrentBalance[0]['pav_balance'];
                        $newBalance = $getPavBalance + $amountTransact;
                        UserWallet::where('id', $getWalletId)->update(['pav_balance' => $newBalance]);
                        $applicationBalance = $getCurrentBalance[0]['application_balance'];
                        $mobileBalance = $getCurrentBalance[0]['mobile_balance'];
                        $streetLampprocessing = $getCurrentBalance[0]['streetlamp_processing_balance'];
                        $streetLampAdminBalance = $getCurrentBalance[0]['streetlamp_administrative_balance'];
                        $totalBalance = $applicationBalance + $mobileBalance + $streetLampprocessing + $streetLampAdminBalance + $newBalance;
                        UserWallet::where('id', $getWalletId)->update(['balance' => $totalBalance]);
                    } elseif ($getTransactionType == 'Street Lamp Processing Fee') {

                        // var_dump($getCurrentBalance[0]['streetlamp_processing_balance']); die();
                        $getStreetLampprocessing = $getCurrentBalance[0]['streetlamp_processing_balance'];
                        $newBalance = $getStreetLampprocessing + $amountTransact;
                        UserWallet::where('id', $getWalletId)->update(['streetlamp_processing_balance' => $newBalance]);
                        $applicationBalance = $getCurrentBalance[0]['application_balance'];
                        $mobileBalance = $getCurrentBalance[0]['mobile_balance'];
                        $pavBalance = $getCurrentBalance[0]['pav_balance'];
                        $streetLampAdminBalance = $getCurrentBalance[0]['streetlamp_administrative_balance'];
                        $totalBalance = $applicationBalance + $mobileBalance + $pavBalance + $streetLampAdminBalance + $newBalance;
                        UserWallet::where('id', $getWalletId)->update(['balance' => $totalBalance]);
                    } elseif ($getTransactionType == 'Street Lamp Administrative Fee') {

                        $streetLampAdminBalance = $getCurrentBalance[0]['streetlamp_administrative_balance'];
                        $newBalance = $streetLampAdminBalance + $amountTransact;
                        UserWallet::where('id', $getWalletId)->update(['streetlamp_administrative_balance' => $newBalance]);
                        $applicationBalance = $getCurrentBalance[0]['application_balance'];
                        $mobileBalance = $getCurrentBalance[0]['mobile_balance'];
                        $pavBalance = $getCurrentBalance[0]['pav_balance'];
                        $streetLampprocessing = $getCurrentBalance[0]['streetlamp_processing_balance'];
                        $totalBalance = $applicationBalance + $mobileBalance + $pavBalance + $streetLampprocessing + $newBalance;
                        UserWallet::where('id', $getWalletId)->update(['balance' => $totalBalance]);
                    }

                    $getApplicant = User::where('id', $userId)->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $templateData = [
                        'body' => "Your Wallet balance has been updated and your transaction approved.",
                        'name' => $getApplicant[0]['first_name'],

                    ];
                    $templateContent = view('emailtemplate', $templateData)->render();
                    $this->composeEmailV2("Transaction Update", $getApplicantEmail, $templateContent);
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Approval wallet transaction';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    $response = UserWallet::where('id', $getWalletId)->get();
                    return response()->json(['data' => $response], 200);
                } else {
                    return response()->json(['data' => 'Rejected transaction'], 200);
                }
            } else {
                return response()->json(['data' => 'This request has been treated!'], 422);
            }
        } else {
            return response()->json(['data' => "You do not have the required access"], 422);
        }
    }

    public function saveWalletTransactionforUser(Request $request) {

        if(Auth::user()->admin_role_id == 8 || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 10 ||
            Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3) {
            $validate = Validator::make($request->all(), [
                'user_id' => 'required|string',
                'transaction_amount' => 'required|numeric',
                'transaction_name' => 'required|string',
                'receipt' => 'required|string',
                'bank_name' => 'required|string',
                'account_number' => 'required|string',
                'account_name' => 'required|string',
                'transaction_purpose' => 'required|string',
                'transaction_date' => 'required|date'
            ]);

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

            $getUserWalletcheck = UserWallet::where('user_id', $request['user_id'])->exists();
            if($getUserWalletcheck) {
            }else{
                $getUserObj = User::find($request['user_id']);
                $wallet = new UserWallet();
                $getUserObj->userWallet()->save($wallet);
            }
            $getUserWallet = UserWallet::where('user_id', $request['user_id'])->get();
            $getUserDetails = User::where('id', $request['user_id'])->get();
            $getBusinessName = $getUserDetails[0]['business_name'];
            $walletId = $getUserWallet[0]['id'];
            $walletObj = UserWallet::find($walletId);

            $transId = $this->generateTransactionId();

            $walletTransaction = new WalletTransaction();
            $walletTransaction->transaction_amount = $request['transaction_amount'];
            $walletTransaction->transaction_name = $request['transaction_name'];
            $walletTransaction->company_name = $getBusinessName;
            $walletTransaction->transaction_id = $transId;
            $walletTransaction->bank_name = $request['bank_name'];
            $walletTransaction->account_name = $request['account_name'];
            $walletTransaction->account_number = $request['account_number'];
            $walletTransaction->transaction_type = $request['transaction_purpose'];
            $walletTransaction->transaction_date = $request['transaction_date'];
            $receiptBase64 = $request['receipt'];
            $walletTransaction->receipt = $this->receiptImage($receiptBase64);
            $walletObj->walletTransaction()->save($walletTransaction);
            $response = WalletTransaction::where('user_wallet_id', $walletId)->get()->last();
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Updated Wallet transaction for user' . $request['user_id'];
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $response], 200);

        } else {
            return response()->json(['data' => 'Unauthorized user'], 422);
        }

    }

    public function payMobileForUser($mobileId, $referenceId) {

        if (Auth::user()->admin_role_id == 10 ) {
            $getMobile = mobilead::where('id', $mobileId)->get();
            $total = AppHistoryMobile::where('mobilead_id', $mobileId)->get()->last();
            $appHistoryMobile = AppHistoryMobile::where('mobilead_id', $getMobile[0]['id'])->get();
            $applicationPurpose = $appHistoryMobile[0]['purpose'];
            $totalSum = $total->ads_price;

            $userId = $getMobile[0]['user_id'];
            $getwallet = UserWallet::where('user_id', $userId)->get();
            $getWalletBalance = $getwallet[0]['mobile_balance'];
            $getTotalBalance = $getwallet[0]['balance'];
            $paymentType = "Wallet";

            if ($getWalletBalance >= $totalSum) {

                $newWalletBalance = $getWalletBalance - $totalSum;
                $newTotalBalance = $getTotalBalance - $totalSum;
                $paymentStatus = 'Successful payment';
                $mobileObj = mobilead::find($mobileId);
                $paymentInfo = new MobilePayment();
                $paymentInfo->amount_paid = $totalSum;
                $paymentInfo->reference_id = $referenceId;
                $paymentInfo->payment_id = $getMobile[0]['payment_id'];
                $paymentInfo->status = $paymentStatus;
                $paymentInfo->application_purpose = $applicationPurpose;
                $paymentInfo->payment_type = $paymentType;
                $getUser = User::find($userId);
                $response = $getUser->mobilePayment()->save($paymentInfo);
                $setMobileads = mobilead::where('id', $mobileId)->update(['Application_pay_status' => 'paid',
                    'hod_permit_status' => 'approved', 'legal_status' => 'approved', 'final_status' => 'approved']);
                $this->sendDetailsforQrcode($mobileId);
                $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);
                $user = Auth::user();
                $activityInfo = new AdminActivity();
                $fetchActivity = 'Payment of mobile ads made on'.$mobileId;
                $activityInfo->action = $fetchActivity;
                $activityInfo->user_admin_id = (string)$user->id;
                $activityInfo->save();
                return response()->json(['data' => $response], 200);
            } else {
                return response()->json(['error' => 'Insufficient wallet balance'], 422);
            }
        } else {
            return response()->json(['error' => 'Unable to perform this action'], 422);
        }
    }

    public function payThirdpartyMobileForUser($mobileId, $referenceId) {

        if(Auth::user()->admin_role_id == 10) {

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

            $userId = $getThirdPartyMobile[0]['user_id'];
            $getwallet = UserWallet::where('user_id', $userId)->get();
            $getWalletBalance = $getwallet[0]['pav_balance'];
            $getTotalBalance = $getwallet[0]['balance'];
            $paymentType = "Wallet";

            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 = $referenceId;
                $paymentInfo->payment_id = $getThirdPartyMobile[0]['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', $getThirdPartyMobile[0]['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);
                $user = Auth::user();
                $activityInfo = new AdminActivity();
                $fetchActivity = 'Payment of PAV ads made on'.$mobileId;
                $activityInfo->action = $fetchActivity;
                $activityInfo->user_admin_id = (string)$user->id;
                $activityInfo->save();
                return response()->json(['data' => $response], 200);
            }  else {
                return response()->json(['error' => 'Insufficient wallet balance'], 422);
            }
        } else {
            return response()->json(['error' => 'Unable to perform this action'], 422);
        }
    }

    public function payStreetLampForUser($streetLampId, $referenceId) {

        if(Auth::user()->admin_role_id == 10) {

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

            $userId = $getSteetLamp[0]['user_id'];
            $getwallet = UserWallet::where('user_id', $userId)->get();
            $getTotalBalance = $getwallet[0]['balance'];
            $getWalletAdmin = $getwallet[0]['streetlamp_administrative_balance'];
            $getWalletProcess = $getwallet[0]['streetlamp_processing_balance'];
            $paymentType = "Wallet";

            //var_dump($getWalletProcess, $getWalletAdmin); die();
            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 = $referenceId;
                $paymentInfo->payment_id = $getSteetLamp[0]['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', $getSteetLamp[0]['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);
                $user = Auth::user();
                $activityInfo = new AdminActivity();
                $fetchActivity = 'Payment of Street Lamp ads made on' . $streetLampId;
                $activityInfo->action = $fetchActivity;
                $activityInfo->user_admin_id = (string)$user->id;
                $activityInfo->save();
                return response()->json(['data' => $response], 200);
            } else {
                return response()->json(['error' => 'Insufficient wallet balance'], 422);
            }
        } else {
            return response()->json(['error' => 'Unable to perform this action'], 422);
        }
    }

    public function payAppStreetLampForUser($streetLampId, $referenceId) {

        if(Auth::user()->admin_role_id == 10) {

            $getSteetLamp = StreetLampsAds::where('id', $streetLampId)->get();

            $getTotalSum = AppHistoryStreetLamp::where('street_lamps_ads_id', $streetLampId)->first();
            $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $streetLampId)->get();
            $applicationPurpose = $appHistoryLamp[0]['purpose'];
            $totalSum = $getTotalSum->ads_price;


            $userId = $getSteetLamp[0]['user_id'];
            $getwallet = UserWallet::where('user_id', $userId)->get();
            $getWalletBalance = $getwallet[0]['application_balance'];
            $getTotalBalance = $getwallet[0]['balance'];
            $paymentType = "Wallet";

            if($getWalletBalance >= $totalSum) {

                $newWalletBalance = $getWalletBalance - $totalSum;
                $newTotalbalance = $getTotalBalance - $totalSum;
                $paymentStatus = 'Successful payment';
                $paymentInfo = new PaymentStreetLamp();
                $paymentInfo->amount_paid = $totalSum;
                $paymentInfo->reference_id = $referenceId;
                $paymentInfo->payment_id = $getSteetLamp[0]['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',$getSteetLamp[0]['payment_id'])->update(['Application_pay_status' => 'paid',
                    'status' => 'pending']);
                $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalbalance,
                    'application_balance' => $newWalletBalance]);
                $user = Auth::user();
                $activityInfo = new AdminActivity();
                $fetchActivity = 'Payment of Street Lamp  Application Fee made on' . $streetLampId;
                $activityInfo->action = $fetchActivity;
                $activityInfo->user_admin_id = (string)$user->id;
                $activityInfo->save();
                return response()->json(['data' => $response], 200);
            } else {
                return response()->json(['data' => 'Insufficient wallet balance'], 422);
            }
        } else {
            return response()->json(['error' => 'Unable to perform this action'], 422);
        }
    }

    public static function generateUserId() {

        $prefix =  mt_rand(10, 99);
        $suffix =  mt_rand(10, 99);
        $current = Carbon::now()->format('Ymds');
        return $prefix . $current . $suffix;
    }

    public function generateEmailToken() {
        $emailToken = rand(100000, 999999);
        return $emailToken;
    }

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

        $mail = new PHPMailer(true);
        $mail->SMTPDebug = 0;
        $mail->isSMTP();
        $mail->Host = 'ssl://mail.supremecluster.com'; //ssl://smtp.gmail.com
        $mail->SMTPAuth = true;
        $mail->Username = 'NoReply@lasaa.com';
        $mail->Password = 'Hd1CuHd76=';
        $mail->SMTPSecure = 'ssl';
        $mail->Port = 465;
        $mail->setFrom('NoReply@lasaa.com', 'Lasaa');
        $mail->addAddress($userEmail);
        $mail->addReplyTo('NoReply@lasaa.com', 'Lasaa');

        $mail->isHTML(true);

        $mail->Subject = $subject;
        $mail->Body = "Verification code: " .$body;
        $mail->send();

    }

//    public function sendsms($receiver, $token)
//    {
//        $curl = curl_init();
//
//        curl_setopt_array($curl, [CURLOPT_URL => "https://api.sendchamp.com/api/v1/verification/create",
//            CURLOPT_RETURNTRANSFER => true,
//            CURLOPT_ENCODING => "",
//            CURLOPT_MAXREDIRS => 10,
//            CURLOPT_TIMEOUT => 30,
//            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//            CURLOPT_CUSTOMREQUEST => "POST",
//            CURLOPT_POSTFIELDS => json_encode(['meta_data' => ['first_name' => 'Paul'],
//                'channel' => 'sms',
//                'sender' => 'SendChamp',
//                'token_type' => 'numeric',
//                'token_length' => 6,
//                'expiration_time' => 3,
//                'customer_mobile_number' => $receiver,
//                'token' => $token,
//                'customer_email_address' => 'idemudiapaul@gmail.com']),
//            CURLOPT_HTTPHEADER => ["Authorization: Bearer sendchamp_live_".env('SENDCHAMP_KEY'),
//                "accept: application/json",
//                "content-type: application/json"],]);
//
//        $response = curl_exec($curl);
//        $err = curl_error($curl);
//
//        curl_close($curl);
//
//        if ($err) {
//            Log::error( "cURL Error #:" . $err);
//        } else {
//            Log::info( $response);
//        }
//    }

    public function sendsmsV2($receiver, $token) {

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

            $client = new Client();

            $response = $client->request('POST', 'https://api.sendchamp.com/api/v1/sms/send', [
                'body' => '{"to":["'.$receiver.'"],"message":"Welcome To Lasaa! Your OTP token is '.$token.', to activate your account. Exp in 3minutes. Thanks you lasaa.lg.gov.ng","sender_name":"Sendchamp","route":"dnd"}',
                'headers' => [
                    'Authorization' => 'Bearer sendchamp_live_$2a$10$9LVM02NWEZ0mV3Z9tMmbb.4jlXR/dGEfMDfEIxgh9aEidal7FclfO',
                    'accept' => 'application/json',
                    'content-type' => 'application/json',
                ],
            ]);

            // Check if the request was successful
            if ($response->getStatusCode() === 200) {
                return true; // Return true if SMS was sent successfully
            } else {
                // Log the error if the request was not successful
                Log::error('Failed to send SMS. HTTP status code: ' . $response->getStatusCode());
                return true; // Still return true to indicate that the function was executed successfully
            }
        } catch (\Exception $e) {
            // Log any exceptions that occur
            Log::error('Exception occurred while sending SMS: ' . $e->getMessage());
            return true; // Return true to indicate that the function was executed successfully
        }
    }

    public function sendsmsPassword($receiver, $token) {

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

            $client = new Client();

            $response = $client->request('POST', 'https://api.sendchamp.com/api/v1/sms/send', [
                'body' => '{"to":["'.$receiver.'"],"message":"Welcome To Lasaa! Your account has been created by your lasaa account officer, here is your password  '.$token.'. Thanks you lasaa.lg.gov.ng","sender_name":"Sendchamp","route":"dnd"}',
                'headers' => [
                    'Authorization' => 'Bearer sendchamp_live_$2a$10$9LVM02NWEZ0mV3Z9tMmbb.4jlXR/dGEfMDfEIxgh9aEidal7FclfO',
                    'accept' => 'application/json',
                    'content-type' => 'application/json',
                ],
            ]);

            // Check if the request was successful
            if ($response->getStatusCode() === 200) {
                return true; // Return true if SMS was sent successfully
            } else {
                // Log the error if the request was not successful
                Log::error('Failed to send SMS. HTTP status code: ' . $response->getStatusCode());
                return true; // Still return true to indicate that the function was executed successfully
            }
        } catch (\Exception $e) {
            // Log any exceptions that occur
            Log::error('Exception occurred while sending SMS: ' . $e->getMessage());
            return true; // Return true to indicate that the function was executed successfully
        }
    }

    protected function onpremisePaymentId() {
        $prefix = 'onprem';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    public function  mobileAdsPaymentId() {
        $prefix = 'mobileAds';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    public function thirdPartyMobilePaymentId() {
        $prefix = 'thirdparty';
        $batchKey = Carbon::now()->format('YmdHis');
        $suffix = rand(100,999);
        return $prefix.$batchKey.$suffix;
    }

    public function  streetLampPaymentId() {
        $prefix = 'streetLamps';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    protected function  imageNamingSaving($base64Image) {
        $image = explode('base64,',$base64Image);
        $image = end($image);
        $image = str_replace(' ', '+', $image);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/images/" . $uniqueid . '.png';

        Storage::disk('public')->put($file,base64_decode($image));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('images/' . $uniqueid . '.png'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    public function convertExcelToCSV($excelFile) {

        $getExcelFile = $excelFile;
        $newFileName = uniqid();
        $decodeFile =  '/excelfiles/'.$newFileName.'.xlsx';

        Storage::disk('public')->put($decodeFile,base64_decode($getExcelFile));

        $sourcePath = storage_path('app/public' . $decodeFile); // Get the source path in the storage directory
        $destinationPath = public_path( $decodeFile ); // Define the destination path in the public directory
        File::move($sourcePath, $destinationPath);

        $reader = IOFactory::createReader('Xlsx');
        $spreadsheet = $reader->load($destinationPath);

        $workSheet = $spreadsheet->getActiveSheet();
        $rows = $workSheet->getHighestRow();
        $data = [];

        for($row = 2; $row <= $rows; $row++ ) {
            $cellValue = $workSheet->getCell('A'.$row)->getValue();
            $data[] = $cellValue;
        }
        $data = array_filter($data);
        if(File::exists($destinationPath)) {
            File::delete($destinationPath);
        }
        if (File::exists($sourcePath)) {
            File::delete($sourcePath);
        }
        return $data;
    }

    protected function convertBase64toPdf($base64Doc) {

        $pdfFile = explode('base64,',$base64Doc);
        $pdfFile = end($pdfFile);
        $pdfFile = str_replace(' ', '+', $pdfFile);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/pdf/" . $uniqueid . '.pdf';

        Storage::disk('public')->put($file,base64_decode($pdfFile));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('pdf/' . $uniqueid . '.pdf'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    public static function generatePassword() {
        $length = 10;
        $character =  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=<>?';
        $batchKey = Str::random($length, $character);
        $prefix = Carbon::now()->format('YmdHis');
        return $batchKey.$prefix;
    }

    protected function generateTransactionId() {
        $prefix = 'TransId';
        $batchkey = Carbon::now()->format('YmdHis');
        $suffix = rand(100, 999);
        return $prefix.$batchkey.$suffix;
    }

    protected function receiptImage($base64Image) {

        $image = explode('base64,',$base64Image);
        $image = end($image);
        $image = str_replace(' ', '+', $image);
        $uniqueid = uniqid();
        $file =  "/images/" . $uniqueid . '.png';

        Storage::disk('public')->put($file,base64_decode($image));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('images/' . $uniqueid . '.png'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    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 composePasswordEmail($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 = 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 = "Generated Password: " .$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 = 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_TEST'),
            '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' => $getUserInfo[0]['business_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()));
    }
}
