<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Api\Util\CSVHelper;
use App\Http\Controllers\Controller;
use App\Imports\TestImport;
use App\Models\AdminRole;
use App\Models\Apphistory;
use App\Models\AppHistoryMobile;
use App\Models\AppHistoryStreetLamp;
use App\Models\AppHistoryThirdPartyOutdoor;
use App\Models\ExpressionOfStreetLamps;
use App\Models\FirstPartyTemporaryAds;
use App\Models\kycdetail;
use App\Models\KycThirdParty;
use App\Models\KycThirdPartyPayment;
use App\Models\mobilead;
use App\Models\MobileAdsVehicleLicense;
use App\Models\onpremise;
use App\Models\OnpremiseInfo;
use App\Models\OnPremiseRemoval;
use App\Models\OnPremiseAdditional;
use App\Models\OnPremiseChange;
use App\Models\PaymentFirstPartyTemporaryAds;
use App\Models\PaymentOnPremise;
use App\Models\PaymentSmallFormatAds;
use App\Models\PaymentStreetLamp;
use App\Models\PaymentThirdPartyOutdoorSignage;
use App\Models\PermitStepOnpremise;
use App\Models\PermitStepStreetLamp;
use App\Models\SmallFormatAds;
use App\Models\SmallFormatDetails;
use App\Models\StreetLampInfo;
use App\Models\StreetLampsAds;
use App\Models\ThirdPartyMobile;
use App\Models\ThirdPartyMobilePermitStep;
use App\Models\ThirdPartyMobileVehicleLicense;
use App\Models\ThirdPartyOutdoor;
use App\Models\ThirdPartyUpgradeAndDowngrade;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\UserWallet;
use App\Models\VehicleMobileAds;
use App\Models\PermitStepMobile;
use App\Models\VehicleThirdPartyMobile;
use App\Models\OnPremiseMultiple;
use App\Models\OnpremiseApplicationPricingRule;
use App\Models\TemporaryAdsApplicationPricing;
use App\Models\SmallFornatAdsApplicationPricing;
use App\Models\StreetLampsAdsApplicationPricing;
use App\Models\KycThirdPartyPricing;
use App\Models\MobileAdsApplicationPricing;
use App\Models\MobilePayment;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Maatwebsite\Excel\Excel;
use PhpOffice\PhpSpreadsheet\IOFactory;


class AdsApplicationController extends Controller
{
    //

    public function __construct() {
        $this->middleware('auth:api', ['except' => ['setPaymentReferencePaystackApplication']]);
    }

    public function mobileAds(Request $request) {
        $validate = Validator::make($request->all(), [
            '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;
        if(isset($mobileInput['applicationForm']['vehicleInfo'][0]['image_montage'])){
            
        }else{
            return response()->json(['errors' => ['Upload at least one image montage']], 422);
        }

        $userId = Auth::user()->id;
        $userIdd =User::find($userId);
        $pid = $this->mobileAdsPaymentId();
        $mobileApplication = new mobilead();
        $mobileApplication->payment_id  = $pid;
        //$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;
//        $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;
//        }
//
//        // Find the name that appeared the least
//        $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 = $userIdd->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();
        $countall = $count + 1;
        $app_price = MobileAdsApplicationPricing::where(function ($query) use ($countall) {
                                  $query->where(function ($q) use ($countall) {
                                      // Case for range pricing: min <= squareMeter <= max
                                      $q->whereNotNull('min_number')
                                        ->whereNotNull('max_number')
                                        ->where('min_number', '<=', $countall)
                                        ->where('max_number', '>=', $countall);
                                  })->orWhere(function ($q) use ($countall) {
                                      // Case for "< X" pricing: only max_number is set
                                      $q->whereNull('min_number')
                                        ->whereNotNull('max_number')
                                        ->where('max_number', '>', $countall); // Note: Assuming max is exclusive for '< X' logic, adjust if inclusive.
                                  })->orWhere(function ($q) use ($countall) {
                                      // Case for "> X" pricing: only min_number is set
                                      $q->whereNotNull('min_number')
                                        ->whereNull('max_number')
                                        ->where('min_number', '<=', $countall); // Note: Assuming min is inclusive for '> X' logic.
                                  });
                              })
                              ->first();
        $totalSum = ceil($app_price->app_price);
        
        $chargeFee = ($totalSum <= 133333.33) ? ceil((2 / 100) * $totalSum) : 2000;
    
        return response()->json([
            'success' => true, 
            'total_price' => $totalSum, 
            'ChargeFee' => $chargeFee,
            'additionalInfo' => env('APPLICATION_BACK'), 
            'paymentID' => $pid,
            'data' => $responses
        ], 200);
    }

    public function thirdPartyMobileAds(Request $request) {
        if(Auth::user()->user_type = 'third_party') {
            $validate = Validator::make($request->all(), [
                '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 = Auth::user()->id;
            $userIdd =User::find($userId);
            $thirdPartyMobileApplication = new ThirdPartyMobile();
            $thirdPartyMobileApplication->payment_id  = $this->thirdPartyMobilePaymentId();
            $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 = [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();
            return  response()->json(['data' => $responses], 200);
        }
    }
    
    public function onPremiseBulk(Request $request) {
        $validate = Validator::make($request->all(), [
            'purpose' => 'required|string',
            'business_name' => 'required|string',
            'email' => 'nullable|email',
            'excel_file' =>'required|string',
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }
        
        $onpremiseInput = $request->all();
        
        
        
        $getExcelFile = $onpremiseInput['excel_file'];
 
        $siteData = $this->convertExcelToCSVBulkCount($getExcelFile);
        
        // Group data by Site Location
        // $groupedData = collect($siteData)->groupBy('site_location')->map(function ($entries) {
        //     return $entries->map(function ($entry) {
        //         return [
        //             'lga' => $entry['lga'],
        //             'tenant_type' => $entry['tenant_type'],
        //             'owner_name' => $entry['owner_name'],
        //             'owner_number' => $entry['owner_number'],
        //             'sign_type' => $entry['sign_type'],
        //             'product_on_sign' => $entry['product_on_sign'],
        //             'photo_montage' => $entry['photo_montage'],
        //             'length' => $entry['length'],
        //             'width' => $entry['width'],
        //             'number_of_sign' => $entry['number_of_sign'],
        //         ];
        //     });
        // });
        $groupedData = collect($siteData)
        ->filter(function ($entry) {
            return !empty($entry['site_location']); // Filter out empty site locations
        })
        ->groupBy('site_location')
        ->map(function ($entries) {
            return $entries->map(function ($entry) {
                return [
                    'lga' => $entry['lga'],
                    'tenant_type' => $entry['tenant_type'],
                    'owner_name' => $entry['owner_name'],
                    'owner_number' => $entry['owner_number'],
                    'sign_type' => $entry['sign_type'],
                    'product_on_sign' => $entry['product_on_sign'],
                    'photo_montage' => $entry['photo_montage'],
                    'length' => $entry['length'],
                    'width' => $entry['width'],
                    'number_of_sign' => $entry['number_of_sign'],
                ];
            });
        });

        $countLocation = count($groupedData) - 1;
        // $totalprice = [];
        $pidk = [];
        
        $createMultiple = new OnPremiseMultiple();
        $createMultiple->save();

        // for ($k = 0; $k <= $countLocation; $k++) {
        
        $locacount = 0;
        $appcounti = 0;
        foreach ($groupedData as $location => $data) {
        $locacount++;
        $appcounti += count($data);
        
        
        
        
        

        // var_dump($location);die();
        $count = count($data) - 1;
        $userId  = Auth::user()->id;
        $pid = $this->onpremisePaymentId();
        $userIdd = User::find($userId);
        $onpremiseApplication  = new onpremise();
        $onpremiseApplication->sign_address = (string)$location;
        $onpremiseApplication->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseApplication->name_of_owner = (string)$data[0]['owner_name'];
        $onpremiseApplication->business_name = $onpremiseInput['business_name'];
        $onpremiseApplication->phone_number = (string)$data[0]['owner_number'];
        $onpremiseApplication->email = $onpremiseInput['email'];
        $onpremiseApplication->property_type = (string)$data[0]['tenant_type'];
        $onpremiseApplication->onpremise_multiple_id = $createMultiple->id;
        $onpremiseApplication->lga = (string)$data[0]['lga'];
        $onpremiseApplication->payment_id = $pid;
        $onpremiseApplication->permit_year = Carbon::now()->format('Y');
        $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($userIdd->is_institution == 1){
            $zone = "Lagos Central";
        }else{
            
            if (in_array($data[0]['lga'], $lcenLGAs)) {
                // The value of $mobileInput['lga'] is one of the allowed LGAs
                $zone = "Lagos Central";
            }elseif(in_array($data[0]['lga'], $leastLGAs)){
                $zone = "Lagos East";
            }elseif(in_array($data[0]['lga'], $lwest1LGAs)){
                $zone = "Lagos West 1";
            }elseif(in_array($data[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;
            }
            
        }
        $onpremiseApplication->zone = $zone;
        $user = $userIdd->onpremise()->save($onpremiseApplication);
        $output []  = $user;
        // var_dump($output);die();
//        $calculatePrice [] = [];
        $price = 0;
        $pidk[] = $pid;
        $signTypes = [];
        for($i=0;  $i<=$count;  $i++) {
            $signType = $data[$i]['sign_type'];
            $signTypes[] = $signType;

            $calculatePrice [] = $data[$i]['sign_type'];
            $onpremiseInfo = new OnpremiseInfo();
            $onpremiseInfo->type_of_sign = (string)$data[$i]['sign_type'];
            $onpremiseInfo->number_of_sign = (string)$data[$i]['number_of_sign'];
            $onpremiseInfo->length_in_meter = (string)$data[$i]['length'];
            $onpremiseInfo->width_in_meter = (string)$data[$i]['width'];
            if((string)$data[$i]['product_on_sign'] == "Yes"){
                $pprod = 1;
            }elseif((string)$data[$i]['product_on_sign'] == "No"){
                $pprod = 0;
            }
            $onpremiseInfo->product_on_sign = $pprod;
            // $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            // $onpremiseInfo->photo_montage = $this->imageNamingSaving($image64String);
            $onpremiseInfo->photo_montage = (string)$data[$i]['photo_montage'];
            $onpremiseId = onpremise::find($user->id);
            $onpremiseInfoSave = $onpremiseId->onpremiseInfo()->save($onpremiseInfo);


        }

        // if($data[0]['tenant_type'] == 'Single Business Unit'){
        //     if ($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 525500;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 515500;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 521000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 25500;
        //         }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 511000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 15500;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 21000;
        //         }
        //     }elseif($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 500000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 4500;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 10000;
        //         }
        //     }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         $price  += 11000;
        //     }elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         $price  += 11000;
        //     }
        // } elseif ($data[0]['tenant_type'] == 'Multi-tenanted Business'){
        //       if($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 520500;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 510500;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 516000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 20500;
        //         }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 506000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 10500;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 16000;
        //         }
        //     } elseif ($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 500000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 4500;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 10000;
        //         }
        //     }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
        //         $price += 6000;
        //     } elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
        //         $price += 6000;
        //     }
        // }
        
        $price = $this->calculateOnPremisePrice((string)$data[0]['tenant_type'], $signTypes, $count + 1);


        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($user->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);
        //$reponses [] = onpremise::where('id',  $onpremiseId->id)->with(['appHistory', 'permitStepOnpremise' ])->get();
        $totalprice [] = Apphistory::where('onpremise_id', $onpremiseId->id)->sum('ads_price');
        }
        
        $updatemult = OnPremiseMultiple::where('id', $createMultiple->id)->update(['total' => $locacount]);
        $totalSum = array_sum(array_map('intval', $totalprice));
        $totalSum = ceil($totalSum);
        if($totalSum <= 133333.33) {
            $chargeFee = (2 / 100) * $totalSum;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        // var_dump($pidk);die();
        return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee, 'location' => $locacount, 'application' => $appcounti,
            'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $pidk], 200);
    }
    
    
    public function convertExcelToCSVBulkCount($excelFile) {

        $getExcelFile = $excelFile;
        $newFileName = uniqid();
        $decodeFile = '/excelfiles/'.$newFileName.'.xlsx';
    
        Storage::disk('public')->put($decodeFile, base64_decode($getExcelFile));
    
        $sourcePath = storage_path('app/public' . $decodeFile);
        $destinationPath = public_path($decodeFile);
        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++) {
            $siteLocation = $workSheet->getCell('E'.$row)->getValue(); // Assuming 'C' is the Site Location column
            $lga = $workSheet->getCell('A'.$row)->getValue();         // LGA
            $tenantType = $workSheet->getCell('B'.$row)->getValue();  // Tenant Type
            $ownerName = $workSheet->getCell('C'.$row)->getValue();
            $ownerNumber = $workSheet->getCell('D'.$row)->getValue();
            $signType = $workSheet->getCell('F'.$row)->getValue();
            $prodOnSign = $workSheet->getCell('G'.$row)->getValue();
            $photoMontage = $workSheet->getCell('H'.$row)->getValue();
            $lenth = $workSheet->getCell('I'.$row)->getValue();
            $width = $workSheet->getCell('J'.$row)->getValue();
            $numberSign = $workSheet->getCell('K'.$row)->getValue();
    
            // Store all relevant data
            $data[] = [
                'site_location' => $siteLocation,
                'lga' => $lga,
                'tenant_type' => $tenantType,
                'owner_name' => $ownerName,
                'owner_number' => $ownerNumber,
                'sign_type' => $signType,
                'product_on_sign' => $prodOnSign,
                'photo_montage' => $photoMontage,
                'length' => $lenth,
                'width' => $width,
                'number_of_sign' => $numberSign,
            ];
        }
    
        $data = array_filter($data); // Remove empty values
    
        if (File::exists($destinationPath)) {
            File::delete($destinationPath);
        }
        if (File::exists($sourcePath)) {
            File::delete($sourcePath);
        }
    
        return $data; // Return the extracted Site Location data
    }
    
    
    
    public function forbulkupload(Request $request){
        $validate = Validator::make($request->all(), [
            'photo_montage' => 'required|string'
        ]);

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

        $onpremiseInput = $request->all();
        $image64String = $onpremiseInput['photo_montage'];
        $data = $this->imageNamingSaving($image64String);
        
        return response()->json(['success' => true, 'Url' =>  $data], 200);
    }

    
    public function forbulkApplicationFeepayment(Request $request, $id){
        $userId  = Auth::user()->id;
        $getonPremise = onpremise::where('onpremise_multiple_id', $id)->pluck('payment_id')->toArray();
        // $permitsteponp = PaymentOnPremise::whereIn('payment_id', $getonPremise)->pluck('payment_id')->toArray();
        // $missingPayments = array_diff($getonPremise, $permitsteponp);
        // if(!empty($missingPayments)){

            $missingOnpremise = onpremise::whereIn('payment_id', $getonPremise)->pluck('id')->toArray();
            $totalprice [] = Apphistory::whereIn('onpremise_id', $missingOnpremise)->sum('ads_price');
            $totalSum = array_sum(array_map('intval', $totalprice));
            $totalSum = ceil($totalSum);
            if($totalSum <= 133333.33) {
                $chargeFee = (2 / 100) * $totalSum;
                $chargeFee = ceil($chargeFee);
            } else {
                $chargeFee = 2000;
            }
            
            return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $getonPremise], 200);
        // }else{
        //     return response()->json(['errors' => "No Application Fees Found"], 422);
        // }
    }
    

//     public function onPremise(Request $request) {
//         $validate = Validator::make($request->all(), [
//             'purpose' => 'required|string',
//             'sign_address' => 'required|string',
//             'name_of_owner' => 'required|string',
//             'business_name' => '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',
//             'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
//         ]);

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

//         $onpremiseInput = $request->all();
//         $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
//         $userId  = Auth::user()->id;
//         $pid = $this->onpremisePaymentId();
//         $userIdd =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->business_name = $onpremiseInput['business_name'];
//         $onpremiseApplication->phone_number = $onpremiseInput['phone_number'];
//         $onpremiseApplication->email = $onpremiseInput['email'];
//         $onpremiseApplication->property_type = $onpremiseInput['property_type'];
//         $onpremiseApplication->lga = $onpremiseInput['lga'];
//         $onpremiseApplication->payment_id = $pid;
//         $onpremiseApplication->permit_year = Carbon::now()->format('Y');
//         $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($userIdd->is_institution == 1){
//             $zone = "Lagos Central";
//         }else{
            
//             if (in_array($onpremiseInput['lga'], $lcenLGAs)) {
//                 // The value of $mobileInput['lga'] is one of the allowed LGAs
//                 $zone = "Lagos Central";
//             }elseif(in_array($onpremiseInput['lga'], $leastLGAs)){
//                 $zone = "Lagos East";
//             }elseif(in_array($onpremiseInput['lga'], $lwest1LGAs)){
//                 $zone = "Lagos West 1";
//             }elseif(in_array($onpremiseInput['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;
//             }
            
//         }
//         $onpremiseApplication->zone = $zone;
//         $user = $userIdd->onpremise()->save($onpremiseApplication);
//         $output []  = $user;
// //        $calculatePrice [] = [];
//         $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'];
//             $onpremiseInfo->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
//             $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) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 if((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 525500;
//                 }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 515500;
//                 }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 521000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 25500;
//                 }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
//                     $price  += 511000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 15500;
//                 }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 21000;
//                 }
//             }elseif($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
//                     $price  += 500000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 4500;
//                 }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 10000;
//                 }
//             }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 $price  += 11000;
//             }elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 $price  += 11000;
//             }
//         } elseif ($onpremiseInput['property_type'] == 'Multi-tenanted Business'){
//               if($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 if(in_array('Led Sign', $calculatePrice) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 520500;
//                 }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 510500;
//                 }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 516000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 20500;
//                 }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
//                     $price  += 506000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 10500;
//                 }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 16000;
//                 }
//             } elseif ($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
//                 if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
//                     $price  += 500000;
//                 }elseif(in_array('Street Directional Sign', $calculatePrice)){
//                     $price  += 4500;
//                 }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
//                     $price  += 10000;
//                 }
//             }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
//                 $price += 6000;
//             } elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional 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);
//         //$reponses [] = onpremise::where('id',  $onpremiseId->id)->with(['appHistory', 'permitStepOnpremise' ])->get();
//         $totalprice [] = Apphistory::where('onpremise_id', $onpremiseId->id)->sum('ads_price');
//         $totalSum = array_sum(array_map('intval', $totalprice));
//         $totalSum = ceil($totalSum);
//         if($totalSum <= 133333.33) {
//             $chargeFee = (2 / 100) * $totalSum;
//             $chargeFee = ceil($chargeFee);
//         } else {
//             $chargeFee = 2000;
//         }
//         //var_dump($price);die();
//         return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
//             'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $pid], 200);
//     }

    public function onPremise(Request $request) {
        $validate = Validator::make($request->all(), [
            'purpose' => 'required|string',
            'sign_address' => 'required|string',
            'name_of_owner' => 'required|string',
            'business_name' => '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',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);
    
        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], 422);
        }
    
        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId = Auth::user()->id;
        $pid = $this->onpremisePaymentId();
        $userIdd = User::find($userId);
    
        // Create the main onpremise application
        $onpremiseApplication = new onpremise();
        $onpremiseApplication->sign_address = $onpremiseInput['sign_address'];
        $onpremiseApplication->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseApplication->name_of_owner = $onpremiseInput['name_of_owner'];
        $onpremiseApplication->business_name = $onpremiseInput['business_name'];
        $onpremiseApplication->phone_number = $onpremiseInput['phone_number'];
        $onpremiseApplication->email = $onpremiseInput['email'];
        $onpremiseApplication->property_type = $onpremiseInput['property_type'];
        $onpremiseApplication->lga = $onpremiseInput['lga'];
        $onpremiseApplication->payment_id = $pid;
        $onpremiseApplication->permit_year = Carbon::now()->format('Y');
    
        // Determine zone
        $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($userIdd->is_institution == 1) {
            $zone = "Lagos Central";
        } else {
            if (in_array($onpremiseInput['lga'], $lcenLGAs)) {
                $zone = "Lagos Central";
            } elseif(in_array($onpremiseInput['lga'], $leastLGAs)) {
                $zone = "Lagos East";
            } elseif(in_array($onpremiseInput['lga'], $lwest1LGAs)) {
                $zone = "Lagos West 1";
            } elseif(in_array($onpremiseInput['lga'], $lwest2LGAs)) {
                $zone = "Lagos West 2";
            } else {
                $listArray = ["Lagos Central", "Lagos East", "Lagos West 1", "Lagos West 2"];
                $selectedKey = array_rand($listArray);
                $zone = $listArray[$selectedKey];
            }
        }
    
        $onpremiseApplication->zone = $zone;
        $user = $userIdd->onpremise()->save($onpremiseApplication);
        $output[] = $user;
    
        // Process each sign info
        $signTypes = [];
        for($i = 0; $i <= $count; $i++) {
            $signType = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['type_of_sign'];
            $signTypes[] = $signType;
    
            $onpremiseInfo = new OnpremiseInfo();
            $onpremiseInfo->type_of_sign = $signType;
            $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'];
            $onpremiseInfo->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            $onpremiseInfo->photo_montage = $this->imageNamingSaving($image64String);
            
            $onpremiseId = onpremise::find($output[0]['id']);
            $onpremiseInfoSave = $onpremiseId->onpremiseInfo()->save($onpremiseInfo);
        }
    
        // Calculate price using database-driven pricing
        $price = $this->calculateOnPremisePrice($onpremiseInput['property_type'], $signTypes, $count + 1);
    
        // Save application history
        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($output[0]['id']);
        $appHistory->purpose = $onpremiseInput['purpose'];
        $appHistory->ads_price = $price;
        $newUser = $onpremiseId->appHistory()->save($appHistory);
    
        // Save permit steps
        $permitOnpermise = new PermitStepOnpremise();
        $permitOnpermise->purpose = $onpremiseInput['purpose'];
        $newSteps = $onpremiseId->permitStepOnpremise()->save($permitOnpermise);
    
        // Calculate total price and charge fee
        $totalprice = Apphistory::where('onpremise_id', $onpremiseId->id)->sum('ads_price');
        $totalSum = ceil($totalprice);
        
        $chargeFee = ($totalSum <= 133333.33) ? ceil((2 / 100) * $totalSum) : 2000;
    
        return response()->json([
            'success' => true, 
            'total_price' => $totalSum, 
            'ChargeFee' => $chargeFee,
            'additionalInfo' => env('APPLICATION_BACK'), 
            'paymentID' => $pid
        ], 200);
    }

    protected function calculateOnPremisePrice($propertyType, array $signTypes, int $signCount){
        $rules = OnpremiseApplicationPricingRule::getRulesForPropertyType($propertyType);
        $price = 0;
        
        // Check for special combinations first
        $ledSigns = ['Led Sign', 'Led Screens At Filling Stations'];
        $hasLedSign = count(array_intersect($ledSigns, $signTypes)) > 0;
        $hasStreetDirectional = in_array('Street Directional Sign', $signTypes);
        $hasStreetLightPole = in_array('Street Light Pole Directional Sign', $signTypes);
        
        // Apply combination pricing if applicable
        if ($hasLedSign && $hasStreetDirectional && $hasStreetLightPole) {
            $comboPrice = $rules['Led Sign']->combination_rules['all_three'] ?? null;
            if ($comboPrice) return $comboPrice;
        } elseif ($hasLedSign && $hasStreetDirectional) {
            $comboPrice = $rules['Led Sign']->combination_rules['led_and_street_directional'] ?? null;
            if ($comboPrice) return $comboPrice;
        } elseif ($hasLedSign && $hasStreetLightPole) {
            $comboPrice = $rules['Led Sign']->combination_rules['led_and_street_light'] ?? null;
            if ($comboPrice) return $comboPrice;
        } elseif ($hasStreetDirectional && $hasStreetLightPole) {
            $comboPrice = $rules['Street Directional Sign']->combination_rules['street_and_light_pole'] ?? null;
            if ($comboPrice) return $comboPrice;
        }
        
        // Calculate price for each sign type
        foreach ($signTypes as $signType) {
            if (isset($rules[$signType])) {
                if ($signCount > 1 && $rules[$signType]->additional_sign_price !== null) {
                    $price += $rules[$signType]->additional_sign_price;
                } else {
                    $price += $rules[$signType]->base_price;
                }
            }
        }
        
        return $price;
    }
    
    public function removeOnpremiseSign($onPremiseId, Request $request) {
        $validate = Validator::make($request->all(), [
            'purpose' => 'required|string',
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.onpremiseinfo_id' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.sign_to_remove' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.photo_montage' => 'nullable|string'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        // $user = $userIdd->onpremise()->save($onpremiseApplication);
        $output  = onpremise::find($onPremiseId);
//        $calculatePrice [] = [];
        $price = 0;
        for($i=0;  $i<=$count;  $i++) {
            
            $signID = OnpremiseInfo::find($onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['onpremiseinfo_id']);
            $no_of_sign = $signID->number_of_sign;
            $sign_to_remove = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['sign_to_remove'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            // if($sign_to_remove > 0 && isset($image64String)){
                // $calculatePrice [] = $signID->type_of_sign;
                $signID->number_of_sign -= $sign_to_remove;
                $signID->sign_to_remove += $sign_to_remove;
                if($sign_to_remove > 0 && isset($image64String)){
                $signID->photo_montage_remove = $this->imageNamingSaving($image64String);
                }
                $signID->save();  
            // }else{
            //     return response()->json(['errors' => ['']], 422);
            // }
            


        }
        
        $historyforward = Apphistory::where('onpremise_id', $onPremiseId)->get()->last();


        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($onPremiseId);
        $onpremiseId->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseId->save();
        $appHistory->purpose = $onpremiseInput['purpose'];
        $appHistory->previous_ads_price = $historyforward['previous_ads_price'];
        $appHistory->current_ads_price = $historyforward['current_ads_price'];
        $appHistory->balance = $historyforward['balance'];
        $appHistory->ads_price = $historyforward['ads_price'];
        $appHistory->bank_and_others = $historyforward['bank_and_others'];
        $appHistory->product_on_sign = $historyforward['product_on_sign'];
        $newUser = $onpremiseId->appHistory()->save($appHistory);
        $permitOnpermise = new PermitStepOnpremise();
        $permitOnpermise->purpose = $onpremiseInput['purpose'];
        $newSteps = $onpremiseId->permitStepOnpremise()->save($permitOnpermise);
        $Opremoval = new OnPremiseRemoval();
        $Opremoval->status = 'pending';
        $tosave = $onpremiseId->OnPremiseRemoval()->save($Opremoval);
        // //$reponses [] = onpremise::where('id',  $onpremiseId->id)->with(['appHistory', 'permitStepOnpremise' ])->get();
        // $totalprice [] = Apphistory::where('onpremise_id', $onpremiseId->id)->sum('ads_price');
        // $totalSum = array_sum(array_map('intval', $totalprice));
        // $totalSum = ceil($totalSum);
        // if($totalSum <= 133333.33) {
        //     $chargeFee = (2 / 100) * $totalSum;
        //     $chargeFee = ceil($chargeFee);
        // } else {
        //     $chargeFee = 2000;
        // }
        // //var_dump($price);die();
        // return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
        //     'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $pid], 200);
        return response()->json(['success' => true], 200);
    }
    
    public function AddOnPremise($onPremiseId, Request $request) {
        $validate = Validator::make($request->all(), [
            'purpose' => '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',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd =User::find($userId);
        $output  = onpremise::find($onPremiseId);
        $pid = $output->payment_id;
//        $calculatePrice [] = [];
        $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 = "0";
            $onpremiseInfo->sign_to_add = $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'];
            $onpremiseInfo->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            $onpremiseInfo->photo_montage = $this->imageNamingSaving($image64String);
            $onpremiseId = onpremise::find($onPremiseId);
            $onpremiseInfoSave = $onpremiseId->onpremiseInfo()->save($onpremiseInfo);


        }

        if($output->property_type == 'Single Business Unit'){
            if ($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                if((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 512750;
                }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 507750;
                }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 510500;
                }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 12750;
                }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
                    $price  += 505500;
                }elseif(in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 7750;
                }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 10500;
                }
            }elseif($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
                    $price  += 500000;
                }elseif(in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 2250;
                }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 5000;
                }
            }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                $price  += 5500;
            }elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                $price  += 5500;
            }
        } elseif ($output->property_type == 'Multi-tenanted Business'){
              if($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                if(in_array('Led Sign', $calculatePrice) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 510250;
                }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 505250;
                }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 508000;
                }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 10250;
                }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
                    $price  += 503000;
                }elseif(in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 5250;
                }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 8000;
                }
            } elseif ($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
                if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
                    $price  += 500000;
                }elseif(in_array('Street Directional Sign', $calculatePrice)){
                    $price  += 2250;
                }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
                    $price  += 5000;
                }
            }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
                $price += 3000;
            } elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
                $price += 3000;
            }
        }


        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($onPremiseId);
        $onpremiseId->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseId->save();
        $oldhistory = Apphistory::where('onpremise_id', $onpremiseId->id)->latest('id')->first();
        $appHistory->purpose = $onpremiseInput['purpose'];
        $appHistory->ads_price = $price;
        $appHistory->balance = $oldhistory->balance;
        $newUser = $onpremiseId->appHistory()->save($appHistory);
        $permitOnpermise = new PermitStepOnpremise();
        $permitOnpermise->purpose = $onpremiseInput['purpose'];
        $newSteps = $onpremiseId->permitStepOnpremise()->save($permitOnpermise);
        $OpAdditional = new OnPremiseAdditional();
        $OpAdditional->status = null;
        $tosave = $onpremiseId->OnPremiseAdditional()->save($OpAdditional);
        //$reponses [] = onpremise::where('id',  $onpremiseId->id)->with(['appHistory', 'permitStepOnpremise' ])->get();
        // $totalprice = Apphistory::where('onpremise_id', $onpremiseId->id)->latest('id')->first();
        $totalSum = $newUser->ads_price;
        $totalSum = ceil($totalSum);
        if($totalSum <= 133333.33) {
            $chargeFee = (2 / 100) * $totalSum;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        //var_dump($price);die();
        return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $pid], 200);
    }
    
    public function ChangeOnPremise($onPremiseId, Request $request) {
        $validate = Validator::make($request->all(), [
            'purpose' => 'required|string',
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.id' => 'required|integer',
            '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',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd =User::find($userId);
        $output  = onpremise::find($onPremiseId);
        $pid = $output->payment_id;
//        $calculatePrice [] = [];
        $price = 0;
        for($i=0;  $i<=$count;  $i++) {

            $calculatePrice [] = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['type_of_sign'];
            $onpremiseInfo = new OnPremiseChange();
            $onpremiseInfo->onpremise_info_id = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['id'];
            $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'];
            $onpremiseInfo->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            $onpremiseInfo->photo_montage = $this->imageNamingSaving($image64String);
            $onpremiseId = onpremise::find($onPremiseId);
            $onpremiseInfoSave = $onpremiseId->onpremiseInfo()->save($onpremiseInfo);


        }

        // if($output->property_type == 'Single Business Unit'){
        //     if ($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 512750;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 507750;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 510500;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 12750;
        //         }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 505500;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 7750;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 10500;
        //         }
        //     }elseif($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 500000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 2250;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 5000;
        //         }
        //     }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         $price  += 5500;
        //     }elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         $price  += 5500;
        //     }
        // } elseif ($output->property_type == 'Multi-tenanted Business'){
        //       if($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) && in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 510250;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 505250;
        //         }elseif((in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 508000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice) && in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 10250;
        //         }elseif(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 503000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 5250;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 8000;
        //         }
        //     } elseif ($i == 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))){
        //         if(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice)){
        //             $price  += 500000;
        //         }elseif(in_array('Street Directional Sign', $calculatePrice)){
        //             $price  += 2250;
        //         }elseif(in_array('Street Light Pole Directional Sign', $calculatePrice)){
        //             $price  += 5000;
        //         }
        //     }elseif ($i >1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
        //         $price += 3000;
        //     } elseif($i == 1 && !(in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice) || in_array('Street Directional Sign', $calculatePrice) || in_array('Street Light Pole Directional Sign', $calculatePrice))) {
        //         $price += 3000;
        //     }
        // }
        
        if($i = 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice))){
            $price += 500000;
        }elseif($i > 1 && (in_array('Led Sign', $calculatePrice) || in_array('Led Screens At Filling Stations', $calculatePrice))){
            $price += 501000;
        }else{
            $price += 1000;
        }

        
        $appHistory = new appHistory();
        $onpremiseId = onpremise::find($onPremiseId);
        $onpremiseId->purpose_of_application = $onpremiseInput['purpose'];
        $onpremiseId->save();
        $oldhistory = Apphistory::where('onpremise_id', $onpremiseId->id)->latest('id')->first();
        $appHistory->purpose = $onpremiseInput['purpose'];
        $appHistory->ads_price = $price;
        $appHistory->balance = $oldhistory->balance;
        $newUser = $onpremiseId->appHistory()->save($appHistory);
        $permitOnpermise = new PermitStepOnpremise();
        $permitOnpermise->purpose = $onpremiseInput['purpose'];
        $newSteps = $onpremiseId->permitStepOnpremise()->save($permitOnpermise);
        // $OpAdditional = new OnPremiseAdditional();
        // $OpAdditional->status = null;
        // $tosave = $onpremiseId->OnPremiseAdditional()->save($OpAdditional);
        //$reponses [] = onpremise::where('id',  $onpremiseId->id)->with(['appHistory', 'permitStepOnpremise' ])->get();
        // $totalprice = Apphistory::where('onpremise_id', $onpremiseId->id)->latest('id')->first();
        $totalSum = $newUser->ads_price;
        $totalSum = ceil($totalSum);
        if($totalSum <= 133333.33) {
            $chargeFee = (2 / 100) * $totalSum;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        //var_dump($price);die();
        return response()->json(['success' => true, 'total_price' =>  $totalSum, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $pid], 200);
    }
    
    public function EditOnPremise($onPremiseId, Request $request) {
        $validate = Validator::make($request->all(), [
            'sign_address' => 'required|string',
            'name_of_owner' => 'required|string',
            'business_name' => 'required|string',
            'phone_number' => 'required|string',
            'email' => 'nullable|email',
            'lga' => 'required|string'
        ]);

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

        $onpremiseInput = $request->all();
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        $output  = onpremise::find($onPremiseId);
        $output->sign_address = $onpremiseInput['sign_address'];
        $output->name_of_owner = $onpremiseInput['name_of_owner'];
        $output->business_name = $onpremiseInput['business_name'];
        $output->phone_number = $onpremiseInput['phone_number'];
        $output->email = $onpremiseInput['email'];
        $output->lga = $onpremiseInput['lga'];
        $output->save();
//        $calculatePrice [] = [];

        
        
        return response()->json(['success' => true], 200);
    }
    
    public function DeleteBulkOnPremise($id) {
        
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        $pluckIds = onpremise::where('onpremise_multiple_id', $id)->where('Application_pay_status', 'not_paid')->pluck('id');
        Apphistory::whereIn('onpremise_id', $pluckIds)->delete();
        $check = onpremise::where('onpremise_multiple_id', $id)->where('Application_pay_status', 'not_paid')->delete();
        
        return response()->json(['success' => true], 200);
    }
    
    public function DeleteOnPremise($id) {
        
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        
        $check = onpremise::where('id', $id)->where('Application_pay_status', 'not_paid')->exists();
        
        if($check){
          Apphistory::where('onpremise_id', $id)->delete();
          onpremise::where('id', $id)->where('Application_pay_status', 'not_paid')->delete();  
          
          return response()->json(['success' => true], 200);
        }else{
            return response()->json(['success' => false, 'info' => "Error: Can't be deleted"], 422);
        }
        
        
        
        
    }
    
    public function EditInfoOnPremise(Request $request) {
        $validate = Validator::make($request->all(), [
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.id' => 'required|integer',
            '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' => 'nullable|string',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd =User::find($userId);
//        $calculatePrice [] = [];
        for($i=0;  $i<=$count;  $i++) {

            $output  = OnpremiseInfo::find($onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['id']);
            $output->number_of_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['number_of_sign'];
            $output->length_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['length_in_meter'];
            $output->width_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['width_in_meter'];
            $output->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            if(!empty($image64String)){
            $output->photo_montage = $this->imageNamingSaving($image64String);
            }
            $output->save();


        }
        
        return response()->json(['success' => true], 200);
    }
    
    public function EditChangeOnPremise(Request $request) {
        $validate = Validator::make($request->all(), [
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.id' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.length_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.width_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.photo_montage' => 'nullable|string',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd =User::find($userId);
//        $calculatePrice [] = [];
        for($i=0;  $i<=$count;  $i++) {

            $output  = OnPremiseChange::find($onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['id']);
            $output->length_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['length_in_meter'];
            $output->width_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['width_in_meter'];
            $output->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            if(!empty($image64String)){
            $output->photo_montage = $this->imageNamingSaving($image64String);
            }
            $output->status = null;
            $output->rm_status = null;
            $output->cp_status = null;
            $output->hod_status = null;
            $output->billing_status = null;
            $output->audit_status = null;
            $output->save();


        }
        
        return response()->json(['success' => true], 200);
    }
    
    public function EditSubmitOnPremise($onPremiseId) {
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        $output  = onpremise::find($onPremiseId);
        $output->status = 'pending';
        $output->rm_status = null;
        $output->hod_status = null;
        $output->billing_status = null;
        $output->account_status = null;
        $output->audit_status = null;
        $output->save();
        
        return response()->json(['success' => true], 200);
    }
    
    public function EditAdditionalSubmitOnPremise($onPremiseId) {
        $userId  = Auth::user()->id;
        $userIdd = User::find($userId);
        $output  = OnPremiseAdditional::find($onPremiseId);
        $output->status = 'pending';
        $output->rm_status = null;
        $output->cp_status = null;
        $output->hod_status = null;
        $output->billing_status = null;
        $output->account_status = null;
        $output->audit_status = null;
        $output->save();
        
        return response()->json(['success' => true], 200);
    }
    
    public function EditAdditionalInfoOnPremise(Request $request) {
        $validate = Validator::make($request->all(), [
            'onpremiseform' => 'present|array',
            'onpremiseform.onpremiseinfo.*.id' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.sign_to_add' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.length_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.width_in_meter' => 'required|integer',
            'onpremiseform.onpremiseinfo.*.photo_montage' => 'nullable|string',
            'onpremiseform.onpremiseinfo.*.product_on_sign' => 'required|boolean'
        ]);

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

        $onpremiseInput = $request->all();
        $count = count($onpremiseInput['onpremiseform']['onpremiseinfo']) - 1;
        $userId  = Auth::user()->id;
        $userIdd =User::find($userId);
//        $calculatePrice [] = [];
        for($i=0;  $i<=$count;  $i++) {

            $output  = OnpremiseInfo::find($onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['id']);
            $output->sign_to_add = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['sign_to_add'];
            $output->length_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['length_in_meter'];
            $output->width_in_meter = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['width_in_meter'];
            $output->product_on_sign = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['product_on_sign'];
            $image64String = $onpremiseInput['onpremiseform']['onpremiseinfo'][$i]['photo_montage'];
            if(!empty($image64String)){
            $output->photo_montage = $this->imageNamingSaving($image64String);
            }
            $output->save();
            
            $input = OnPremiseAdditional::where('onpremise_id', $output->onpremise_id)
                    ->latest('id')
                    ->first();
            $input->status = 'pending';
            $input->rm_status = null;
            $input->cp_status = null;
            $input->hod_status = null;
            $input->billing_status = null;
            $input->account_status = null;
            $input->audit_status = null;
            $input->save();


        }
        
        return response()->json(['success' => true], 200);
    }

    public function streetLampAds(Request $request) {
        $validate = Validator::make($request->all(), [
            'name_of_display' => 'required|string',
            'purpose' => 'required|string',
            'material_for_deployment' => 'nullable|string',
            'source_of_electricity' => 'nullable|string',
            'start_date' => 'required|string',
            'end_date' => 'required|string',
            'type_of_sign' => 'required|string|in:LED,FLEX,BACKLIT',
            'location_of_generator' => 'nullable|string',
            'authorization_letter_lseb' => 'nullable|string',
             'duration' => 'nullable|string',
            'height_sign' => 'nullable|integer',
            'width_sign' => 'nullable|integer',
            'weight_sign' => 'nullable|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 = Auth::user()->id;
        $useridd =  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->due_date = $streetLampsInput['end_date'];
        $streetLampApplication->location_of_generator = $streetLampsInput['location_of_generator'];
        $authorizationLetter = $streetLampsInput['authorization_letter_lseb'];
        // var_dump($authorizationLetter);die();
        if($authorizationLetter != null){
            $streetLampApplication->authorization_letter_lseb = $this->convertBase64toPdf($authorizationLetter);
        }
        $streetLampApplication->payment_id = $paymentId;
        $rmRole = [2];
        $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   = $useridd->streetLamps()->save($streetLampApplication);
        $output [] = $saveLamps;

        $count = count($streetLampsInput['streetlampform']['streetlampinfo']) - 1;
        $addPrice = StreetLampsAdsApplicationPricing::where('type_of_sign', $streetLampsInput['type_of_sign'])->first();


        for ($i=0; $i <= $count ; $i++) {
            $price = 0;
            // var_dump($i); die();
            if ($streetLampsInput['type_of_sign'] == 'FLEX') {
                    $p = $i +1;
                    $price += $addPrice->app_price * $p;
            }
            if ($streetLampsInput['type_of_sign'] == 'BACKLIT') {
                $p = $i +1;
                $price += $addPrice->app_price * $p;
            }
            if ($streetLampsInput['type_of_sign'] == 'LED') {
                $p = $i +1;
                $price += $addPrice->app_price * $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();
        $totalprice = AppHistoryStreetLamp::where('street_lamps_ads_id', $streetLampId->id)->sum('ads_price');
        $totalprice = ceil($totalprice);
        if($totalprice <= 133333.33) {
            $chargeFee = (2 / 100) * $totalprice;
            $chargeFee = ceil($chargeFee);
        } else {
            $chargeFee = 2000;
        }
        return response()->json(['success'  => true, 'total_price' =>  $totalprice, 'ChargeFee' => $chargeFee,
            'additionalInfo' => env('STREETLAMPPOLES_BACK'),
            'paymentID' => $paymentId ], 200);
    }

    public function getPaymentInfo(Request $request) {
        $validate = Validator::make($request->all(), [
            'type_ads' => 'required|string|in:StreetLamp,Onpremise,OutdoorSite,Practitioner Application,OutdoorRequest,Firstparty TemporaryAds,SmallFormat Application,SmallFormat Inspection,MobileAds',
            'paymentId' => 'nullable|string'
        ]);

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

        $getPaymentInfo = $request->all();

        if($getPaymentInfo['type_ads'] == 'Onpremise') {
            $getOnpremise = onpremise::where('payment_id', $getPaymentInfo['paymentId'])->first();
                //   var_dump($getOnpremise);die();
            $totalprice = Apphistory::where('onpremise_id', $getOnpremise->id)->latest('id')->first();
            //  var_dump($totalprice->ads_price);die();
            // $totalSum = array_sum(array_map('intval', $totalprice));
            $totalprice = ceil($totalprice->ads_price);
            if($totalprice <= 133333.33) {
                $chargeFee = (2 / 100) * $totalprice;
                $chargeFee = ceil($chargeFee);
            } else {
                $chargeFee = 2000;
            }
            return response()->json(['success' => true, 'total_price' =>  $totalprice, 'ChargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $getPaymentInfo['paymentId']], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'StreetLamp') {
            $getStreetLamp  = StreetLampsAds::where('payment_id', $getPaymentInfo['paymentId'])->first();
            $totalprice = AppHistoryStreetLamp::where('street_lamps_ads_id', $getStreetLamp->id)->first();
            // $totalSum = array_sum(array_map('intval', $totalprice));
            $totalprice = ceil($totalprice->ads_price);
            if($totalprice <= 133333.33) {
                $chargeFee = (2 / 100) * $totalprice;
                $chargeFee = ceil($chargeFee);
            } else {
                $chargeFee = 2000;
            }
            return response()->json(['success' => true, 'total_price' =>  $totalprice, 'ChargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $getPaymentInfo['paymentId']], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'OutdoorSite') {
          $getOutdoorSite = ThirdPartyOutdoor::where('payment_id', $getPaymentInfo['paymentId'])->get();
          $totalPrice = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $getOutdoorSite[0]['id'])->get();

           $getPrice  = intval($totalPrice[0]['application_price']);
           $chargeFee = 2000;
           return response()->json(['success' => true, 'total_price' => $getPrice, 'chargeFee' => $chargeFee,
               'additionalInfo' =>  env('APPLICATION_BACK'), 'paymentID' => $getPaymentInfo['paymentId']], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'Practitioner Application') {
            $appprice = KycThirdPartyPricing::find(1);
            $totalPrice = $appprice->eoi_price;
            $chargeFee = 2000;
            return response()->json(['success' => true, 'total_price' => $totalPrice, 'chargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK')], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'OutdoorRequest') {
            $getOutdoorRequest = ThirdPartyUpgradeAndDowngrade::where('payment_id', $getPaymentInfo['paymentId'])->get();
            $getRequestSignage = $getOutdoorRequest[0]['request_outdoor_signage'];
            $getRequestSignage = strtolower($getRequestSignage);
            $getRequestGrade = $getOutdoorRequest[0]['type_charges'];
            $totalPrice = 0;
            $chargeFee = 0;
            $pricingapp = OutdoorSignagePricingApplication::where('fee_type', 'Upgrade_Downgrade_fee')->first();

            if($getRequestGrade == 'downgrade') {
                if(str_contains($getRequestSignage, 'led')) {
                    $totalPrice = $pricingapp->led_price + $pricingapp->inspection_fee;
                    $chargeFee = 2000;
                } elseif (!str_contains($getRequestSignage, 'led')) {
                    $totalPrice = $pricingapp->normal_price + $pricingapp->inspection_fee;
                    $chargeFee = (2/100) * $totalPrice;
                }
            } elseif ($getRequestGrade == 'upgrade') {
                if(str_contains($getRequestSignage, 'led')) {
                    $totalPrice = $pricingapp->led_price + $pricingapp->inspection_fee;
                    $chargeFee = 2000;
                } elseif (!str_contains($getRequestSignage, 'led')) {
                    $totalPrice = $pricingapp->normal_price + $pricingapp->inspection_fee;
                    $chargeFee = (2/100) * $totalPrice;
                }
            }
            return response()->json(['success' => true, 'total_price' => $totalPrice, 'chargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK'), 'paymentID' => $getPaymentInfo['paymentId']], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'Firstparty TemporaryAds') {
            $getTemporaryAds = FirstPartyTemporaryAds::where('payment_id', $getPaymentInfo['paymentId'])->get();
            $targetDate = $getTemporaryAds[0]['start_date'];
            $appPrice = TemporaryAdsApplicationPricing::find(1);

            if($this->getThreeWorkingDay($targetDate)) {
                $applicationFee = $appPrice->app_price;
                if($applicationFee > 133333.33){
                    $chargeFee = 2000;
                }else{
                    $chargeFee = (2/100) * $applicationFee;  
                }
            } elseif (!$this->getThreeWorkingDay($targetDate)) {
                $tentyper = $appPrice->app_price;
                $tentyper += $tentyper * ($appPrice->not_three_working_days_percentage/100);
                $applicationFee = $tentyper;
                if($applicationFee > 133333.33){
                    $chargeFee = 2000;
                }else{
                    $chargeFee = (2/100) * $applicationFee;  
                }
            }
            return response()->json(['success' => true, 'total_price' => $applicationFee, 'chargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK')], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'SmallFormat Application') {
            $smallFormatAds = SmallFormatAds::where('payment_id', $getPaymentInfo['paymentId'])->get();
            $getCount = SmallFormatDetails::where('small_format_ads_id', $smallFormatAds[0]['id'])->count();
            $appPrice = SmallFornatAdsApplicationPricing::find(1);

            $applicationFee = ($appPrice->app_price * $getCount);
            if($applicationFee <= 133333.33) {
                $chargeFee = (2/100) * $applicationFee;
            } else {
                $chargeFee = 2000;
            }
            return response()->json(['success' => true, 'total_price' => $applicationFee, 'chargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK')], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'SmallFormat Inspection') {
            $smallFormatAds = SmallFormatAds::where('payment_id', $getPaymentInfo['paymentId'])->get();
            $getInspectionFee = intval($smallFormatAds[0]['inspection_fee']);

            if($getInspectionFee <= 133333.33) {
                $chargeFee = (2/100) * $getInspectionFee;
            } else {
                $chargeFee = 2000;
            }
            return response()->json(['success' => true, 'total_price' => $getInspectionFee, 'chargeFee' => $chargeFee,
                'additionalInfo' => env('APPLICATION_BACK')], 200);
        } elseif ($getPaymentInfo['type_ads'] == 'MobileAds') {
            $mobileads = $mobileObj = mobilead::where('payment_id', $getPaymentInfo['paymentId'])->first();
            $countall = MobileAdsVehicleLicense::where('mobilead_id', $mobileads->id)->count();
            $app_price = MobileAdsApplicationPricing::where(function ($query) use ($countall) {
                                      $query->where(function ($q) use ($countall) {
                                          // Case for range pricing: min <= squareMeter <= max
                                          $q->whereNotNull('min_number')
                                            ->whereNotNull('max_number')
                                            ->where('min_number', '<=', $countall)
                                            ->where('max_number', '>=', $countall);
                                      })->orWhere(function ($q) use ($countall) {
                                          // Case for "< X" pricing: only max_number is set
                                          $q->whereNull('min_number')
                                            ->whereNotNull('max_number')
                                            ->where('max_number', '>', $countall); // Note: Assuming max is exclusive for '< X' logic, adjust if inclusive.
                                      })->orWhere(function ($q) use ($countall) {
                                          // Case for "> X" pricing: only min_number is set
                                          $q->whereNotNull('min_number')
                                            ->whereNull('max_number')
                                            ->where('min_number', '<=', $countall); // Note: Assuming min is inclusive for '> X' logic.
                                      });
                                  })
                                  ->first();
            $totalSum = ceil($app_price->app_price);
            
            $chargeFee = ($totalSum <= 133333.33) ? ceil((2 / 100) * $totalSum) : 2000;
           return response()->json(['success' => true, 'total_price' => $totalSum, 'chargeFee' => $chargeFee,
               'additionalInfo' =>  env('APPLICATION_BACK'), 'paymentID' => $getPaymentInfo['paymentId']], 200);
        }
    }

    public function expressionStreetLamps(Request $request) {
        $validate = Validator::make($request->all(), [
            'letter_interest' => 'required|string',
        ]);

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

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

        $getUser = User::find($userId);
        $expressionApplication = new ExpressionOfStreetLamps();
        $letterInterest64String = $expressionStreetLamp['letter_interest'];
        $expressionApplication->letter_interest = $this->convertBase64toPdf($letterInterest64String);
        $saveInfo = $getUser->expressionOfStreetLamps()->save($expressionApplication);
        $output [] =  $saveInfo;

        $expressionInfo = ExpressionOfStreetLamps::where('id', $output[0]['id'])->get();
        return response() ->json(['data' => $expressionInfo], 200);
}

    public function setPaymentReference(Request $request) {

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


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


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

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

            if($setPaymentForm['form_type'] == 'StreetLamp') {
                $getSteetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->get();
                $getTotalSum = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->first();
                $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->get();
                $applicationPurpose = $appHistoryLamp[0]['purpose'];
                $totalSum = $getTotalSum->ads_price;

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

                if($getWalletBalance >= $totalSum) {

                    $newWalletBalance = $getWalletBalance - $totalSum;
                    $newTotalbalance = $getTotalBalance - $totalSum;
                    $paymentStatus = 'Successful payment';
                    $paymentInfo = new PaymentStreetLamp();
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $paymentInfo->payment_type = $paymentType;
                    $getUser = User::find($userId);
                    $response = $getUser->payment()->save($paymentInfo);
                    $setStreetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'status' => 'pending']);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalbalance,
                        'application_balance' => $newWalletBalance]);
                    return response()->json(['data' => $response], 200);
                } else {
                    return response()->json(['data' => 'Insufficient wallet balance'], 422);
                }
            } elseif ($setPaymentForm['form_type'] == 'Onpremise') {
                $getOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->get();
                $getOnpremise1 = onpremise::where('payment_id', $setPaymentForm['payment_id'])->count();

                $count = $getOnpremise1 - 1;

                $getAppHistory = Apphistory::where('onpremise_id', $getOnpremise[0]['id'])->first();
                $totalSum = $getAppHistory->ads_price;
                $applicationPurpose = $getAppHistory->purpose;

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

                if($getWalletBalance  >= $totalSum) {

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

                    $paymentInfo = new PaymentOnPremise();
                    $paymentInfo->amount_paid = $totalSum;
                    $paymentInfo->reference_id = $setPaymentForm['reference_id'];
                    $paymentInfo->payment_id = $setPaymentForm['payment_id'];
                    $paymentInfo->status = $paymentStatus;
                    $paymentInfo->application_purpose = $applicationPurpose;
                    $paymentInfo->payment_type = $paymentType;
                    $getUser = User::find($userId);
                    $response = $getUser->paymentOnpremise()->save($paymentInfo);
                    $setOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
                        'status' => 'pending']);
                    $updateWallet = UserWallet::where('user_id', $userId)->update(['balance' => $newTotalbalance,
                        'application_balance' => $newWalletBalance ]);
                    return response()->json(['data' => $response], 200);
                }  else {
                    return response()->json(['data' => 'Insufficient wallet balance'], 422);
                }
            }
        }

//        elseif($setPaymentForm['payment_type'] == 'Paystack') {
//            if ($setPaymentForm['form_type'] == 'StreetLamp') {
//                $getSteetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->get();
//                $totalSum = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->first();
//                $appHistoryLamp = AppHistoryStreetLamp::where('street_lamps_ads_id', $getSteetLamp[0]['id'])->get();
//                $applicationPurpose = $appHistoryLamp[0]['purpose'];
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum->ads_price) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('STREETLAMPPOLES_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
////                          var_dump($data); die();
//                    //$newamount = $totalSum->ads_price * 100;
//                    $totalSum = ceil($totalSum->ads_price);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $refcheck = paymentStreetLamp::where('reference_id', $reference)->exists();
//
//                    if ($refcheck) {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//
//                $paymentType = Str::lower($setPaymentForm['payment_type']);
//                $paymentInfo = new PaymentStreetLamp();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $paymentInfo->payment_type = $paymentType;
//                $getUser = User::find($userId);
//                $response = $getUser->payment()->save($paymentInfo);
//                $setStreetLamp = StreetLampsAds::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                    'status' => 'pending']);
//                return response()->json(['data' => $response], 200);
//
//
//            } elseif ($setPaymentForm['form_type'] == 'Onpremise') {
//                $getOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->get();
//                $getOnpremise1 = onpremise::where('payment_id', $setPaymentForm['payment_id'])->count();
//
//                $count = $getOnpremise1 - 1;
//
//                $getAppHistory = Apphistory::where('onpremise_id', $getOnpremise[0]['id'])->first();
//                $totalSum = $getAppHistory->ads_price;
//                $applicationPurpose = $getAppHistory->purpose;
//
//
//                if (!empty($setPaymentForm['reference_id']) && !empty($totalSum) &&
//                    !empty($userEmail) && !empty($setPaymentForm['payment_id'])) {
//
//                    $curl = curl_init();
//
//                    $reference = $setPaymentForm['reference_id'];
//
//                    curl_setopt_array($curl, array(
//                        CURLOPT_URL => "https://api.paystack.co/transaction/verify/$reference",
//                        CURLOPT_RETURNTRANSFER => true,
//                        CURLOPT_ENCODING => "",
//                        CURLOPT_MAXREDIRS => 10,
//                        CURLOPT_TIMEOUT => 30,
//                        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
//                        CURLOPT_CUSTOMREQUEST => "GET",
//                        CURLOPT_HTTPHEADER => array(
//                            "Authorization: Bearer " . env('ONPREMISE_BACKSTREET'),
//                            "Cache-Control: no-cache",
//                        ),
//                    ));
//
//                    $response = curl_exec($curl);
//                    $err = curl_error($curl);
//
//                    curl_close($curl);
//
//                    $responseArray = json_decode($response, true);  // 'true' makes it return an associative array
//
//                    $data = $responseArray['data'];
////                          var_dump($data); die();
//                    //$newamount = $totalSum * 100;
//                    $totalSum = ceil($totalSum);
//                    if($totalSum <= 133333.33) {
//                        $chargeFee = (2 / 100) * $totalSum;
//                        $chargeFee = ceil($chargeFee);
//                    } else {
//                        $chargeFee = 2000;
//                    }
//                    $newamount =  ($totalSum + $chargeFee) * 100;
//                    //var_dump($data['customer']['email'] , $userEmail, $newamount, $data['amount'] ); die();
//                    if ($data['customer']['email'] == $userEmail && $data['amount'] == $newamount) {
//                        // Do nothing
//                    } else {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $refcheck = PaymentOnPremise::where('reference_id', $reference)->exists();
//                    //var_dump($refcheck); die();
//                    if ($refcheck) {
//                        return response()->json(["success" => false, 'info' => "Error: amount or email address does not match with the transaction"], 422);
//                    }
//
//                    $amountpaid = $newamount / 100;
//                    $ref = $data['reference'];
//
//                } else {
//                    $amountpaid = 0;
//                    $ref = "";
//                }
//
//                $paymentType = Str::lower($setPaymentForm['payment_type']);
//                $paymentInfo = new PaymentOnPremise();
//                $paymentInfo->amount_paid = $amountpaid;
//                $paymentInfo->reference_id = $ref;
//                $paymentInfo->payment_id = $setPaymentForm['payment_id'];
//                $paymentInfo->status = $data['status'];
//                $paymentInfo->application_purpose = $applicationPurpose;
//                $paymentInfo->payment_type = $paymentType;
//                $getUser = User::find($userId);
//                $response = $getUser->paymentOnpremise()->save($paymentInfo);
//                $setOnpremise = onpremise::where('payment_id', $setPaymentForm['payment_id'])->update(['Application_pay_status' => 'paid',
//                    'status' => 'pending']);
//                return response()->json(['data' => $response], 200);
//            }
//        }
    }

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

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

        $input = @file_get_contents("php://input");
//        //define('PAYSTACK_SECRET_KEY', getenv('STREETLAMPPOLES_BACKSTREET'));
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
        Log::info("Application webhook");
        http_response_code(200);
        $event = json_decode($input);
        Log::info(json_encode($event));
        if($event->data->status == "success") {
            if ($event->data->metadata->paymentFor == 'Application Fee') {
                // Log::info('Application Fee');
                    if($event->data->metadata->appType == 'StreetLamp') {
                        // Log::info('StreetLamp');
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;

                        $getStreet = StreetLampsAds::where('payment_id', $paymentId)->get();
                        $paymentInfo = new PaymentStreetLamp();
                        $paymentInfo->amount_paid = $amount;
                        $paymentInfo->reference_id = $reference;
                        $paymentInfo->payment_id = $paymentId;
                        $paymentInfo->status = $event->data->status;
                        $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
                        $paymentInfo->payment_type = 'Paystack';
                        $getUser = User::find($getStreet[0]['user_id']);
                        $response = $getUser->payment()->save($paymentInfo);
                        $setStreetLamp = StreetLampsAds::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
                            'status' => 'pending']);
                        return response()->json(['data' => $response], 200);
                    } elseif ($event->data->metadata->appType == 'Onpremise') {
                        // Log::info('Onpremise');
                        if ($event->data->metadata->appPurpose == 'Application for New Sign') {
                            Log::info('Onpremise New Application');
                            $reference = $event->data->reference;
                            $amount = ($event->data->amount) / 100;
                            $paymentId = $event->data->metadata->paymentId;
                            if (is_array($paymentId)) {
                                // $paymentId is an array
                                Log::info($paymentId);
                                $count = count($paymentId) - 1;
                                // Log::info($count);
                                for($i=0;  $i<=$count;  $i++) {
                                    $getOnpremise = onpremise::where('payment_id', $paymentId[$i])->get();
                                    $totalprice = Apphistory::where('onpremise_id', $getOnpremise[0]['id'])->sum('ads_price');
                                    $paymentInfo = new PaymentOnPremise();
                                    $paymentInfo->amount_paid = $totalprice;
                                    $paymentInfo->reference_id = $reference;
                                    $paymentInfo->payment_id = $paymentId[$i];
                                    $paymentInfo->status = $event->data->status;
                                    $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
                                    $paymentInfo->payment_type = "Paystack";
                                    $getUser = User::find($getOnpremise[0]['user_id']);
                                    $response = $getUser->paymentOnpremise()->save($paymentInfo);
                                    $setOnpremise = onpremise::where('payment_id', $paymentId[$i])->update(['Application_pay_status' => 'paid',
                                        'status' => 'pending']);
                                }
                                    return response()->json(['data' => $response], 200);
                                
                            } else {
                                // $paymentId is NOT an array
                                
                            
                                $getOnpremise = onpremise::where('payment_id', $paymentId)->get();
        
                                $paymentInfo = new PaymentOnPremise();
                                $paymentInfo->amount_paid = $amount;
                                $paymentInfo->reference_id = $reference;
                                $paymentInfo->payment_id = $paymentId;
                                $paymentInfo->status = $event->data->status;
                                $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
                                $paymentInfo->payment_type = "Paystack";
                                $getUser = User::find($getOnpremise[0]['user_id']);
                                $response = $getUser->paymentOnpremise()->save($paymentInfo);
                                $setOnpremise = onpremise::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
                                    'status' => 'pending']);
                                return response()->json(['data' => $response], 200);
                            }
                        } elseif ($event->data->metadata->appPurpose == 'Additional Sign') {
                            // Log::info('Onpremise Additional Sign');
                            $reference = $event->data->reference;
                            $amount = ($event->data->amount) / 100;
                            $paymentId = $event->data->metadata->paymentId;
                            $getOnpremise = onpremise::where('payment_id', $paymentId)->get();
    
                            $paymentInfo = new PaymentOnPremise();
                            $paymentInfo->amount_paid = $amount;
                            $paymentInfo->reference_id = $reference;
                            $paymentInfo->payment_id = $paymentId;
                            $paymentInfo->status = $event->data->status;
                            $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
                            $paymentInfo->payment_type = "Paystack";
                            $getUser = User::find($getOnpremise[0]['user_id']);
                            $response = $getUser->paymentOnpremise()->save($paymentInfo);
                            // $setOnpremise = onpremise::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
                            //     'status' => 'pending']);
                            $onpremise = OnPremiseAdditional::where('onpremise_id', $getOnpremise[0]['id'])->latest('id')->first()->update(['status' => 'pending', 'Application_pay_status' => 'paid']);
                            // Log::info($onpremise);
                            return response()->json(['data' => $response], 200);
                        }elseif ($event->data->metadata->appPurpose == 'Change of Sign') {
                            // Log::info('Onpremise Additional Sign');
                            $reference = $event->data->reference;
                            $amount = ($event->data->amount) / 100;
                            $paymentId = $event->data->metadata->paymentId;
                            $getOnpremise = onpremise::where('payment_id', $paymentId)->get();
    
                            $paymentInfo = new PaymentOnPremise();
                            $paymentInfo->amount_paid = $amount;
                            $paymentInfo->reference_id = $reference;
                            $paymentInfo->payment_id = $paymentId;
                            $paymentInfo->status = $event->data->status;
                            $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
                            $paymentInfo->payment_type = "Paystack";
                            $getUser = User::find($getOnpremise[0]['user_id']);
                            $response = $getUser->paymentOnpremise()->save($paymentInfo);
                            // $setOnpremise = onpremise::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
                            //     'status' => 'pending']);
                            $allnewchanges = OnPremiseChange::where('onpremise_id', $getOnpremise[0]['id'])
                            ->whereNull('status')  // Use `whereNull` to check for NULL values
                            ->pluck('onpremise_info_id')  // Pluck the `onpremise_info_id` column
                            ->toArray();
                            // $onpremiseinfo = OnpremiseInfo::whereIn('id', $allnewchanges)->get();
                            $updateinfo = OnPremiseChange::whereIn('onpremise_info_id', $allnewchanges)->get();
                            $count = count($updateinfo) - 1;
                            for($i=0;$i<=$count;$i++){
                                $onpremiseinfo = OnpremiseInfo::where('id', $updateinfo[$i]['onpremise_info_id'])->first();
                                if($onpremiseinfo->type_of_sign == $updateinfo[$i]['type_of_sign']){
                                    $calcall = $onpremiseinfo->number_of_sign - $updateinfo[$i]['number_of_sign'];
                                    $onpremiseinfo->update(['number_of_sign' => $calcall]);
                                }else{
                                    $calcall = $onpremiseinfo->number_of_sign - $updateinfo[$i]['number_of_sign'];
                                    $onpremiseinfo->update(['number_of_sign' => $calcall]);
                                }
                            }
                            
                            $onpremise = OnPremiseChange::whereIn('onpremise_info_id', $allnewchanges)->update(['status' => 'pending', 'Application_pay_status' => 'paid']);
                            
                            
                            
                            return response()->json(['data' => $response], 200);
                        }
                    } elseif ($event->data->metadata->appType == 'OutdoorSite') {
                        Log::info('OutdoorSite');
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;
                        $purpose = $event->data->metadata->appPurpose;
                        Log::info($event->data->metadata->appPurpose);
                        $paymentInfo = new PaymentThirdPartyOutdoorSignage();
                        $paymentInfo->amount_paid = $amount;
                        $paymentInfo->reference_id = $reference;
                        $paymentInfo->payment_id = $paymentId;
                        $paymentInfo->status = $event->data->status;
                        $paymentInfo->payment_type = "Paystack";
                        if($event->data->metadata->appPurpose == 'Application for New Sign') {
                            $paymentInfo->application_purpose = $purpose;

                            $getOutdoor = ThirdPartyOutdoor::where('payment_id', $paymentId)->get();
                            if ($getOutdoor->isEmpty()) {
                                Log::error('No outdoor signage found for payment ID: ' . $paymentId);
                                return response()->json(['error' => 'No outdoor signage found'], 422);
                            }

                            $getUser = User::find($getOutdoor[0]['user_id']);
                            $response = $getUser->paymentThirdPartyOutdoorSignage()->save($paymentInfo);

                            ThirdPartyOutdoor::where('payment_id', $paymentId)->update(['application_pay_status' => 'paid']);
                            return response()->json(['data' => $response], 200);
                        } elseif ($event->data->metadata->appPurpose == 'upgrade/downgrade') {
                            $paymentInfo->application_purpose = $purpose;

                            $getUpgradeDowngrade = ThirdPartyUpgradeAndDowngrade::where('payment_id', $paymentId)->get();
                            if ($getUpgradeDowngrade->isEmpty()) {
                                Log::error('No upgrade/downgrade found for payment ID: ' . $paymentId);
                                return response()->json(['error' => 'No upgrade/downgrade found'], 422);
                            }

                            $thirdPartyOutdoor = ThirdPartyOutdoor::find($getUpgradeDowngrade[0]['third_party_outdoor_id']);
                            if (is_null($thirdPartyOutdoor)) {
                                Log::error('No user found for third party outdoor ID: ' . $getUpgradeDowngrade[0]['third_party_outdoor_id']);
                                return response()->json(['error' => 'No user found for third party outdoor ID'], 422);
                            }
                            $getUser = User::find($thirdPartyOutdoor->user_id);
                            if (is_null($getUser)) {
                                Log::error('No user found for user ID: ' . $thirdPartyOutdoor->user_id);
                                return response()->json(['error' => 'No user found'], 422);
                            }
                            $response = $getUser->paymentThirdPartyOutdoorSignage()->save($paymentInfo);
                            ThirdPartyUpgradeAndDowngrade::where('payment_id', $paymentId)->update(['application_status' => 'paid']);
                            return response()->json(['data' => $response], 200);
                        }elseif($event->data->metadata->appPurpose == 'Appeal Application') {
                            $paymentInfo->application_purpose = $purpose;

                            $getOutdoor = ThirdPartyOutdoor::where('payment_id', $paymentId)->get();
                            if ($getOutdoor->isEmpty()) {
                                Log::error('No outdoor signage found for payment ID: ' . $paymentId);
                                return response()->json(['error' => 'No outdoor signage found'], 422);
                            }

                            $getUser = User::find($getOutdoor[0]['user_id']);
                            $response = $getUser->paymentThirdPartyOutdoorSignage()->save($paymentInfo);

                            ThirdPartyOutdoor::where('payment_id', $paymentId)->update(['purpose_application' => $purpose]);
                            
                            
                            
                            // Retrieve the columns and default values for the table
                            $columns = Schema::getColumnListing('thirdparty_outdoor');
                            $defaultValues = [];
                            
                            // List columns to exclude from resetting
                            $excludeColumns = ['payment_id', 'purpose_application', 'user_id', 'id', 'type_sign', 'application_id', 
                            'application_pay_status', 'permit_pay_status', 'address_proposed_site', 'lga', 'latitude', 'longitude', 
                            'north', 'east', 'property_owner_name', 'property_owner_signature', 'property_owner_phone', 'property_owner_email', 
                            'property_owner_consent', 'assigned_officer', 'permit_year', 'created_at', 'updated_at'];
                            
                            foreach ($columns as $column) {
                                // Skip excluded columns
                                if (in_array($column, $excludeColumns)) {
                                    continue;
                                }
                            
                                // Retrieve the default value for the column from the database
                                $default = DB::selectOne("SHOW COLUMNS FROM thirdparty_outdoor WHERE Field = ?", [$column])->Default;
                            
                                // Use DB::raw('DEFAULT') for non-nullable columns with defaults; otherwise, specify null
                                $defaultValues[$column] = $default !== null ? DB::raw('DEFAULT') : null;
                            }
                            
                            // Apply the update with dynamically generated defaults
                            ThirdPartyOutdoor::where('payment_id', $paymentId)->update($defaultValues);
                            
                            
                            
                            return response()->json(['data' => $response], 200);
                        }
                    } elseif ($event->data->metadata->appType == 'Firstparty TemporaryAds') {
                        Log::info('Firstparty TemporaryAds');
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;
                        $applicationPayment = new PaymentFirstPartyTemporaryAds();
                        $applicationPayment->application_purpose = 'Application fee for Temporary Ads';
                        $applicationPayment->amount_paid = $amount;
                        $applicationPayment->status = $event->data->status;
                        $applicationPayment->reference_id = $reference;
                        $applicationPayment->payment_id = $paymentId;
                        $applicationPayment->payment_type = 'paystack';
                        $temporaryAds = FirstPartyTemporaryAds::where('payment_id', $paymentId)->get();
                        if ($temporaryAds->isEmpty()) {
                            Log::error('No First Party Temporary Ads found for payment ID: ' . $paymentId);
                            return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                        }
                        $userObj = User::find($temporaryAds[0]['user_id']);
                        if(is_null($userObj)) {
                            Log::error('No user found for user ID: ' . $temporaryAds->user_id);
                            return response()->json(['error' => 'No user found'], 422);
                        }
                        $response = $userObj->paymentFirstPartyTemporaryAds()->save($applicationPayment);
                        FirstPartyTemporaryAds::where('payment_id', $paymentId)->update(['application_pay_status' => 'paid', 'rm_recommendation' => 'pending']);
                        return response()->json(['data' => $response], 200);
                    } elseif ($event->data->metadata->appType == 'MobileAds') {
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;
                        $mobileObj = mobilead::where('payment_id', $paymentId)->first();
                        $paymentInfo = new MobilePayment();
                        $paymentInfo->amount_paid = $amount;
                        $paymentInfo->reference_id = $reference;
                        $paymentInfo->payment_id = $paymentId;
                        $paymentInfo->status = $event->data->status;
                        $paymentInfo->application_purpose = 'Application fee for Mobile Ads';
                        $paymentInfo->payment_type = 'paystack';
                        $getUser = User::find($mobileObj->user_id);
                        $response = $getUser->mobilePayment()->save($paymentInfo);
                        mobilead::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid']);
                        return response()->json(['data' => $response], 200);
                    } elseif ($event->data->metadata->appType == 'SmallFormat Application') {
                        Log::info('SmallFormat Application');
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;
                        $smallFormatAds = SmallFormatAds::where('payment_id', $paymentId)->get();
                        $purpose = $smallFormatAds[0]['purpose_application'];
                        $applicationPayment = new PaymentSmallFormatAds();
                        $applicationPayment->application_purpose = $purpose;
                        $applicationPayment->amount_paid = $amount;
                        $applicationPayment->status = $event->data->status;
                        $applicationPayment->reference_id = $reference;
                        $applicationPayment->payment_id = $paymentId;
                        $applicationPayment->payment_type = 'paystack';
                        if ($smallFormatAds->isEmpty()) {
                            Log::error('No Small Format Ads found for payment ID: ' . $paymentId);
                            return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                        }
                        $userObj = User::find($smallFormatAds[0]['user_id']);
                        if(is_null($userObj)) {
                            Log::error('No user found for user ID: ' . $smallFormatAds->user_id);
                            return response()->json(['error' => 'No user found'], 422);
                        }
                        $response = $userObj->paymentSmallFormatAds()->save($applicationPayment);
                        SmallFormatAds::where('id', $smallFormatAds[0]['id'])->update(['application_pay_status' => 'paid']);
                        return response()->json(['data' => $response], 200);
                    } elseif ($event->data->metadata->appType == 'SmallFormat Inspection') {
                        Log::info('SmallFormat Inspection');
                        $reference = $event->data->reference;
                        $amount = ($event->data->amount) / 100;
                        $paymentId = $event->data->metadata->paymentId;
                        $smallFormatAds = SmallFormatAds::where('payment_id', $paymentId)->get();
                        $purpose = $smallFormatAds[0]['purpose_application'];
                        $applicationPayment = new PaymentSmallFormatAds();
                        $applicationPayment->application_purpose = $purpose;
                        $applicationPayment->amount_paid = $amount;
                        $applicationPayment->status = $event->data->status;
                        $applicationPayment->reference_id = $reference;
                        $applicationPayment->payment_id = $paymentId;
                        $applicationPayment->payment_type = 'paystack';
                        if ($smallFormatAds->isEmpty()) {
                            Log::error('No Small Format Ads found for payment ID: ' . $paymentId);
                            return response()->json(['error' => 'No First Party Temporary Ads found'], 422);
                        }
                        $userObj = User::find($smallFormatAds[0]['user_id']);
                        if(is_null($userObj)) {
                            Log::error('No user found for user ID: ' . $smallFormatAds->user_id);
                            return response()->json(['error' => 'No user found'], 422);
                        }
                        $response = $userObj->paymentSmallFormatAds()->save($applicationPayment);
                        SmallFormatAds::where('id', $smallFormatAds[0]['id'])->update(['application_site_inspection_status' => 'paid']);
                        return response()->json(['data' => $response], 200);
                    }
            } elseif ($event->data->metadata->paymentFor == 'Practitioner Application') {
                Log::info('Practitioner Application');
                $reference = $event->data->reference;
                $amount = ($event->data->amount) / 100;
                $userId = $event->data->metadata->userId;
                $getKyc = KycThirdParty::where('user_id', $userId)->get();

                $paymentInfo = new KycThirdPartyPayment();
                $paymentInfo->amount_paid = $amount;
                $paymentInfo->reference_id = $reference;
                $paymentInfo->payment_id = $this->kycThirdpartyPaymentId();
                $paymentInfo->status = $event->data->status;
                $paymentInfo->payment_purpose = $event->data->metadata->paymentFor;
                $paymentInfo->payment_type = "Paystack";
                $getKycObj = KycThirdParty::find($getKyc[0]['id']);
                $response = $getKycObj->kycThirdPartyPayment()->save($paymentInfo);
                KycThirdParty::where('user_id', $userId)->update(['application_payment_status' => 'paid', 'operation_status' => 'pending']);
                return response()->json(['data' => $response], 200);
            }
        }
    }

//    public function setPaymentReferencePaystackforStreetLamp() {
//        Log::info("This is to check Paystack");
//
//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();
//
//        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('STREETLAMPPOLES_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('STREETLAMPPOLES_FORWARDSTREET'));
//
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == "success") {
//                if($event->data->metadata->paymentFor == 'Application Fee') {
//                    $reference = $event->data->reference;
//                    $amount = ($event->data->amount) / 100;
//
//                    $paymentId = $event->data->metadata->paymentId;
//                    $paymentInfo = new PaymentStreetLamp();
//                    $paymentInfo->amount_paid = $amount;
//                    $paymentInfo->reference_id = $reference;
//                    $paymentInfo->payment_id = $paymentId;
//                    $paymentInfo->status = $event->data->status;
//                    $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
//                    $paymentInfo->payment_type = 'Paystack';
//                    $getUser = User::find($event->data->metadata->userid);
//                    $response = $getUser->payment()->save($paymentInfo);
//                    $setStreetLamp = StreetLampsAds::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
//                        'status' => 'pending']);
//                    return response()->json(['data' => $response], 200);
//                }
//        }
//    }
//
//    public function setPaymentReferencePaystackforOnpremise() {
//
//        Log::info("This is to check Paystack");
//
//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();
//
//        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('ONPREMISE_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('ONPREMISE_FORWARDSTREET'));
//
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == "success") {
//            if($event->data->metadata->paymentFor == 'Application Fee') {
//                $reference = $event->data->reference;
//                $amount = ($event->data->amount) / 100;
//                $paymentId = $event->data->metadata->paymentId;
//
//                $paymentInfo = new PaymentOnPremise();
//                $paymentInfo->amount_paid = $amount;
//                $paymentInfo->reference_id = $reference;
//                $paymentInfo->payment_id = $paymentId;
//                $paymentInfo->status = $event->data->status;
//                $paymentInfo->application_purpose = $event->data->metadata->paymentFor;
//                $paymentInfo->payment_type = "Paystack";
//                $getUser = User::find($event->data->metadata->userid);
//                $response = $getUser->paymentOnpremise()->save($paymentInfo);
//                $setOnpremise = onpremise::where('payment_id', $paymentId)->update(['Application_pay_status' => 'paid',
//                    'status' => 'pending']);
//                return response()->json(['data' => $response], 200);
//            }
//        }
//
//    }
//
//    public function setPaymentReferencePaystackforOutdoorSite() {
//
//        Log::info("This is to check Paystack");
//
//        if ((strtoupper($_SERVER['REQUEST_METHOD']) != 'POST' ) || !array_key_exists('HTTP_X_PAYSTACK_SIGNATURE', $_SERVER) )
//            exit();
//
//        $input = @file_get_contents("php://input");
//        define('PAYSTACK_SECRET_KEY', getenv('ONPREMISE_BACKSTREET'));
//        //define('PAYSTACK_SCRET_KEY', getenv('ONPREMISE_FORWARDSTREET'));
//
//        if($_SERVER['HTTP_X_PAYSTACK_SIGNATURE'] !== hash_hmac('sha512', $input, PAYSTACK_SECRET_KEY))
//            exit();
//
//        http_response_code(200);
//        $event = json_decode($input);
//
//        if($event->data->status == "success") {
//            if($event->data->metadata->paymentFor == 'Application Fee') {
//                $reference = $event->data->reference;
//                $amount = ($event->data->amount) / 100;
//
//
//
//            }
//        }
//    }

    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;
}

    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;
    }

    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;
    }

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

    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 getThreeWorkingDay($targetDate) {

        $startDate = Carbon::now();
        $targetDate = Carbon::parse($targetDate);

        if($targetDate->lessThan($startDate)) {
            return false;
        }

        $period = CarbonPeriod::create($startDate, $targetDate);

        $weekCount = 0;
        foreach ($period as $date) {
            if($date->isWeekday()) {
                $weekCount++;
                if($weekCount >= 3) {
                    return  true;
                }
            }
        }
         return  false;
    }
}
