<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\AdminApprovalController;
use App\Models\AdminActivity;
use App\Models\AdminRole;
use App\Models\KycThirdParty;
use App\Models\mobilead;
use App\Models\onpremise;
use App\Models\OnpremiseInfo;
use App\Models\OnPremiseRemoval;
use App\Models\OnPremiseAdditional;
use App\Models\OnPremiseChange;
use App\Models\StreetLampsAds;
use App\Models\ThirdPartyMobile;
use App\Models\ThirdPartyOffchargeAndExpunction;
use App\Models\ThirdPartyOutdoor;
use App\Models\ThirdPartyUpgradeAndDowngrade;
use App\Models\ThirdPartyOutdoorTransfer;
use App\Models\SmallFormatAds;
use App\Models\SmallFormatDetails;
use App\Models\FirstPartyTemporaryAds;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\EmailContent;
use App\Http\Controllers\Api\AdminThirdPartySignageController;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Str;
use Laravel\Passport\Passport;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class AdminController extends Controller
{

    private $successStatusCode = 200;
    private $errorStatusCode = 422;

    public function adminRegister(Request $request) {
        $validate = Validator::make($request->all(), [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'email' => 'required|email',
            'phone_number' => 'required||min:11',
            'admin_role' => 'required|string',
            'line_manager' => 'required|numeric',
            'lga' => 'nullable|string',
            'zone' => 'nullable|string',
            'zone2' => 'nullable|string',
            'department' => 'nullable|string'
        ]);


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

        $adminInput = $request->all();
        $adminId = self::generateAdminId();
        $adminPassword = self::generatePassword();

        $adminUser = new UserAdmin();
        $adminUser->id = $adminId;
        $adminUser->first_name = $adminInput['first_name'];
        $adminUser->last_name = $adminInput['last_name'];
        $adminUser->email = $adminInput['email'];
        $adminUser->phone_number = $adminInput['phone_number'];
        $adminUser->password = Hash::make($adminPassword);
        $adminUser->line_manager = (string)$request['line_manager'];
        $adminUser->lga = $request['lga'];
        $adminUser->zone = $request['zone'];
        $adminUser->zone2 = $request['zone2'];
        $adminUser->department = $request['department'];
        $adminrole = $request['admin_role'];
        $adminrole = Str::upper($adminrole);
        $admin = AdminRole::where('role', $adminrole)->first();
        $adminer = AdminRole::find($admin->id);
        $adminer->userAdmin()->save($adminUser);
        $adminCreateAccount = new AdminActivity();
        $registerActivity = "Just create an admin account";
        $adminCreateAccount->action = $registerActivity;
        $adminCreateAccount->user_admin_id = (string)Auth::user()->id;
        $adminCreateAccount->save();
        // $user = Auth::user();
        // $savedActivity = $user->adminActivity()->save($adminCreateAccount);
        // $savedActivity = $user->adminActivity()->save($adminCreateAccount);
//        $newlyCreateAccount = new AdminActivity();
//        $newaccount = "New account created";
//        $newlyCreateAccount->action = $newaccount;
//        $newUser = UserAdmin::where('id', $adminId);
//        var_dump($newUser);die();
//        $createdUser = $newUser->adminActivity()->save($newlyCreateAccount);

        $templateData = [
            'body' => $adminPassword,
            'name' => $adminInput['first_name'],
        ];
        $templateContent = view('emailtemplate', $templateData)->render();
        $this->composeEmailV2('Password', $adminInput['email'],  $templateContent);
        //$this->composeEmail('Password', $adminPassword, $adminInput['email']);
        return response()->json(['message' => 'Admin Registered successfully'], 200);
    }

    public function adminLogin()
    {

        if(Auth::guard('adminweb')->attempt(['email' => request('email'), 'password' => request('password')])) {

            $user = Auth::guard('adminweb')->user();

            $expiresAt = Passport::personalAccessTokensExpireIn(now()->addDays(7));
            $success['token' ] = $user->createToken('lasaa-admin', ['*'], ['expires_at' => $expiresAt])->accessToken;
            $activityInfo = new AdminActivity();
            $loginActivity = 'Admin login at the created time';
            $activityInfo->action = $loginActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['success' => $success], 200);
        }else{
            return  response()->json(['error' => 'Invalid email/password'], 422);
        }
    }

    public function getCurrentAdmin() {

        $user = Auth::user();
        $userInfo = UserAdmin::where('id',  (string)$user->id)->with('adminRole')->get();
        $data = StreetLampsAds::where('date_hod_approval', '<=', Carbon::now()->subDays(7))
            ->where('permit_payment_status', null)
            ->update(['status' => 'declined', 'eoi_status' => 'declined',
                'hod_permit_status' => 'declined', 'final_status' => 'declined']);
                
                
                
                
        $getalloffcharge = ThirdPartyOutdoor::where('active_status', 'off_charge')->get()->toArray();
        if(!empty($getalloffcharge)){
            $getOutDoorObjcount = count($getalloffcharge) - 1;
            for ($i = 0; $i <= $getOutDoorObjcount; $i++) {
              $offcharge = ThirdPartyOffchargeAndExpunction::where('third_party_outdoor_id', $getalloffcharge[$i]['id'])->first();
              if(Carbon::now() > $offcharge->off_charge_end ){
                  ThirdPartyOutdoor::where('id', $getalloffcharge[$i]['id'])->update(['active_status' => null]);
              }
            }
        }
        if($userInfo == null) {
            return response()->json(['data' => 'User does not exist'],422);
        } else {
            return response()->json(['data' => $userInfo], 200);
        }
    }

    public function getAllAdmin(Request $request) {

        $page = $request->input('per_page', 10);
        $getAllAdmin = UserAdmin::with(['adminRole', 'adminActivity']);
        if(count($getAllAdmin->get()) == 0) {
            return  response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('admin_role_id')) {
                $status = $request->input('admin_role_id');
                $getAllAdmin->where(function ($getAllAdmin) use($status) {
                    $getAllAdmin->where('admin_role_id', $status);
                });
            }
            if($request->input('search')) {
                $searchTerm = $request->input('search');
                $getAllAdmin->where(function ($getAllAdmin) use ($searchTerm) {
                    $getAllAdmin->where('first_name', 'like', '%' .  $searchTerm . '%')
                                    ->orWhere('last_name',  'like',  '%' . $searchTerm . '%');
                }) ;
            }

            $items = $getAllAdmin->paginate($page);
            if($request->input('admin_role_id')) {
                $items->appends(['admin_role_id' => $request->input('admin_role_id')]);
            }
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all active admin';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $items], 200);
        }

    }
    
    public function getRMRegistry(Request $request) {

        $page = $request->input('per_page', 10);
        $getAllAdmin = UserAdmin::whereIn('admin_role_id', [2,3])->with(['adminRole', 'adminActivity']);
        if(count($getAllAdmin->get()) == 0) {
            return  response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('admin_role_id')) {
                $status = $request->input('admin_role_id');
                $getAllAdmin->where(function ($getAllAdmin) use($status) {
                    $getAllAdmin->where('admin_role_id', $status);
                });
            }
            if($request->input('search')) {
                $searchTerm = $request->input('search');
                $getAllAdmin->where(function ($getAllAdmin) use ($searchTerm) {
                    $getAllAdmin->where('first_name', 'like', '%' .  $searchTerm . '%')
                                    ->orWhere('last_name',  'like',  '%' . $searchTerm . '%');
                }) ;
            }

            $items = $getAllAdmin->get()->toArray();
            // if($request->input('admin_role_id')) {
            //     $items->appends(['admin_role_id' => $request->input('admin_role_id')]);
            // }
            return response()->json(['data' => $items], 200);
        }

    }

    public function getHodAndGm(Request $request) {

        $getAllAssignableAdmin = UserAdmin::where('admin_role_id', 5)->orWhere('admin_role_id', 6)
                ->with('adminRole')->get();
        if(count($getAllAssignableAdmin) == 0) {
            return response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all assignable  admin';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return  response()->json(['data' => $getAllAssignableAdmin], 200);
        }
    }

    public function getAllOnpremiseApps(Request $request) {

        $page = $request->input('per_page', 10);
        $premise = onpremise::where('Application_pay_status', 'paid')->with(['user', 'appHistory']);
        if(count($premise->get()) == 0) {
            return response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('status')) {
                $status = $request->input('status');
                $premise->where(function ($premise) use($status) {
                    $premise->where('status', $status);
                });
            }
            $items = $premise->paginate($page);
            if($request->input('status')) {
                $items->appends(['status' => $request->input('status')]);
            }
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all onpremise ads';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $items], 200);
        }
    }

    public function getFirstPartyOnpremiseForBM(Request $request)  {
        AdminApprovalController::annualOnpremise();
        if(Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 1 ||
        Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 4 || Auth::user()->admin_role_id == 5) {
            $zones = [Auth::user()->zone, Auth::user()->zone2];
            $page = $request->input('per_page', 10);
            $lgacheck = Onpremise::where('lga', Auth::user()->lga)->exists();
            if (Auth::user()->admin_role_id == 1){
                if($lgacheck){
                $getAllFirstPartyOnpremise = Onpremise::where('lga', Auth::user()->lga);
                }else{
                $getAllFirstPartyOnpremise = Onpremise::whereIn('zone', $zones); 
                }
            }else{
            $getAllFirstPartyOnpremise = Onpremise::query(); // Assuming your model is named Onpremise
            }

            if ($getAllFirstPartyOnpremise->count() === 0) {
                return response()->json(['data' => 'No resultset available'], 422);
            } else {
                $user = Auth::user();
                $activityInfo = new AdminActivity();
                $fetchActivity = 'Fetched all onpremise ads for first party users';
                $activityInfo->action = $fetchActivity;
                $activityInfo->user_admin_id = (string)$user->id;
                $activityInfo->save();

                if ($request->has('status')) {
                    $status = $request->input('status');
                    $getAllFirstPartyOnpremise->where('status', $status);
                }

                if ($request->has('search') && $request->input('search') !="") {
                    $search = $request->input('search');
                    $getAllFirstPartyOnpremise->where('name_of_owner', 'like', '%' . $search . '%')
                    ->orWhere('payment_id', 'like', '%' . $search . '%')
                    ->orWhere('sign_address', 'like', '%' . $search . '%')
                    ->orWhereHas('user', function ($q) use ($search) {
                          $q->where('id', 'like', '%' . $search . '%');
                      });
                }
                
                if ($request->has('lga') && $request->input('lga') !="") {
                    $search = $request->input('lga');
                    $getAllFirstPartyOnpremise->where('lga', $search);
                }
                
                
                if ($request->has('start_date') && $request->input('start_date') !="") {
                    $startDate = Carbon::parse($request->input('start_date'));
                    $endDate = Carbon::parse($request->input('end_date'));
                    $getAllFirstPartyOnpremise->whereBetween('created_at', [$startDate, $endDate]);
                }

                // Add the orderBy method here
                $getAllFirstPartyOnpremise->orderBy('updated_at', 'desc');

                $items = $getAllFirstPartyOnpremise->paginate($page);
                if($request->input('status')) {
                    $items->appends(['status' => $request->input('status')]);
                }
                if($request->input('search') !="") {
                    $items->appends(['search' => $request->input('search')]);
                }
                return response()->json(['data' => $items], 200);
            }
        } else {
            return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
        }
    }

    public function getAllMobileApps(Request $request) {
         if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6 ||
             Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 10) {


        if(Auth::user()->department == "Mobile_advert" || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 10){

        $page = $request->input('per_page', 10);
        if(Auth::user()->department == "Mobile_advert"){
            $mobile = mobilead::with(['user',  'appHistoryMobile', 'vehicleMobile', 'permitStepMobile',
                                                    'mobileAdsVehicleLicense']);
        }else{
            $mobile = mobilead::with(['user',  'appHistoryMobile', 'vehicleMobile', 'permitStepMobile', 'mobileAdsVehicleLicense']);
        }
        if(count($mobile->get()) == 0) {
            return response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('status')) {
                $status = $request->input('status');
                $mobile->where(function ($mobile) use($status) {
                    $mobile->where('status', $status);
                });
            }

            if ($request->has('search') && $request->input('search') !="") {
                    $search = $request->input('search');
                    $mobile->where('brand_name', 'like', '%' . $search . '%')
                                ->orWhere('payment_id', 'like', '%' . $search . '%');
                $mobile->orWhereHas('mobileAdsVehicleLicense', function ($query) use ($search) {
                    $query->where('vehicle_license', $search);
                });
                $mobile->orWhereHas('user', function ($query) use ($search) {
                    $query->where('first_name', 'like', '%'. $search . '%')
                        ->orWhere('last_name', 'like', '%' . $search . '%')
                        ->orWhere('id', 'like', '%' . $search . '%');
                });
            }
            
            if ($request->has('lga') && $request->input('lga') !="") {
                $search = $request->input('lga');
                $mobile->where('lga', $search);
            }
                
                
            if ($request->has('start_date') && $request->input('start_date') !="") {
                $startDate = Carbon::parse($request->input('start_date'));
                $endDate = Carbon::parse($request->input('end_date'));
                $mobile->whereBetween('created_at', [$startDate, $endDate]);
            }

            // Add the orderBy method here
            $mobile->orderBy('updated_at', 'desc');

            $items = $mobile->paginate($page);
            if($request->input('status')) {
                $items->appends(['status' => $request->input('status')]);
            }
            if($request->input('search') !="") {
                    $items->appends(['search' => $request->input('search')]);
                }
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all mobile ads';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $items], 200);
        }

        }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
         }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
    }

    public function getAllStreetLampApps(Request $request) {
        if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6 ||
            Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 10) {


        if(Auth::user()->department == "Registry" || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 10){

        $page = $request->input('per_page', 10);
        // $streetlamp = StreetLampsAds::where('eoi_status','pending')->orWhere('status','not_started')->with(['user', 'appHistoryStreetLamp']);
        $streetlamp = StreetLampsAds::with(['user', 'streetLampInfo', 'appHistoryStreetLamp']);
        if(count($streetlamp->get()) == 0 ) {
            return response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('status')) {
                $status = $request->input('status');
                $streetlamp->where(function ($streetlamp) use($status) {
                    $streetlamp->where('status', $status)->orWhere('eoi_status', $status);
                });
            }

            if ($request->has('search') && $request->input('search') !="") {
                    $search = $request->input('search');
                    $streetlamp->where('name_of_display', 'like', '%' . $search . '%')
                        ->orWhere('payment_id', 'like', '%' . $search . '%')
                        ->orWhere('ref_no',  'like', '%'. $search . '%');
                $streetlamp->orWhereHas('streetLampInfo', function ($query) use ($search) {
                    $query->where('type_of_sign', 'like', '%' . $search . '%')
                            ->orWhere('site_address', 'like', '%' . $search . '%');
                });
                $streetlamp->orWhereHas('user', function ($query) use ($search) {
                    $query->where('first_name', 'like', '%'. $search . '%')
                        ->orWhere('last_name', 'like', '%' . $search . '%')
                        ->orWhere('id', 'like', '%' . $search . '%');
                });

            }
            
            if ($request->has('lga') && $request->input('lga') !="") {
                $search = $request->input('lga');
                $streetlamp->where('lga', $search);
            }
                
                
            if ($request->has('start_date') && $request->input('start_date') !="") {
                $startDate = Carbon::parse($request->input('start_date'));
                $endDate = Carbon::parse($request->input('end_date'));
                $streetlamp->whereBetween('created_at', [$startDate, $endDate]);
            }

            // Add the orderBy method here
            $streetlamp->orderBy('updated_at', 'desc');
            $items = $streetlamp->paginate($page);
            if($request->input('status')) {
                $items->appends(['status' => $request->input('status')]);
            }
            if($request->input('search') !="") {
                    $items->appends(['search' => $request->input('search')]);
                }
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all street lamps ads';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $items], 200);
        }
        }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
         }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
    }

    public function getAllThirdPartyMobileApps(Request $request) {
        if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6
            || Auth::user()->admin_role_id == 5 || Auth::user()->admin_role_id == 10) {


        if(Auth::user()->department == "Registry" || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 10){

        $page = $request->input('per_page', 10);
        $thirdPartyMobile = ThirdPartyMobile::with(['user', 'vehicleThirdPartyMobile','thirdPartyMobileVehicleLincense',
                                                                                        'thirdPartyMobilePermitStep']);
        if(count($thirdPartyMobile->get()) == 0) {
            return response()->json(['data' => 'Empty Resultset'], 422);
        } else {
            if ($request->input('status')) {
                $status = $request->input('status');
                $thirdPartyMobile->where(function ($thirdPartyMobile) use($status) {
                    $thirdPartyMobile->where('status', $status);
                });
            }
            if ($request->has('search') && $request->input('search') !="") {
                    $search = $request->input('search');
                    $thirdPartyMobile->where('brand_name', 'like', '%' . $search . '%')
                        ->orWhere('payment_id', 'like', '%' . $search . '%')
                        ->orWhere('ref_no',  'like', '%'. $search . '%');
                $thirdPartyMobile->orWhereHas('thirdPartyMobileVehicleLincense', function ($query) use ($search) {
                    $query->where('vehicle_license', $search);
                });
                $thirdPartyMobile->orWhereHas('user', function ($query) use ($search) {
                            $query->where('first_name', 'like', '%'. $search . '%')
                                            ->orWhere('last_name', 'like', '%' . $search . '%')
                                            ->orWhere('id', 'like', '%' . $search . '%');
                });
            }
                
                
            if ($request->has('start_date') && $request->input('start_date') !="") {
                $startDate = Carbon::parse($request->input('start_date'));
                $endDate = Carbon::parse($request->input('end_date'));
                $thirdPartyMobile->whereBetween('created_at', [$startDate, $endDate]);
            }

            // Add the orderBy method here
            $thirdPartyMobile->orderBy('updated_at', 'desc');
            $items = $thirdPartyMobile->paginate($page);
            if($request->input('status')) {
                $items->appends(['status' => $request->input('status')]);
            }
            if($request->input('search') !="") {
                    $items->appends(['search' => $request->input('search')]);
                }
            $user = Auth::user();
            $activityInfo = new AdminActivity();
            $fetchActivity = 'Fetched all Third Party mobile ads';
            $activityInfo->action = $fetchActivity;
            $activityInfo->user_admin_id = (string)$user->id;
            $activityInfo->save();
            return response()->json(['data' => $items], 200);
        }
        }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
         }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
    }

    public function getAllMobileAppsMytask(Request $request) {

         if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 5
             || Auth::user()->admin_role_id == 9) {


                     if(Auth::user()->department == "Mobile_advert" && Auth::user()->admin_role_id == 2 || Auth::user()->department == "Mobile_advert" &&
                         Auth::user()->admin_role_id == 3){

//                                    $mobile = mobilead::where('assigned_officer', (string)Auth::user()->id)->where('status', 'pending')->
//                                                                                where('hod_permit_status', null)
//                                                                                ->with(['user',  'appHistoryMobile', 'vehicleMobile'])->paginate(20);
                         $zones = [Auth::user()->zone, Auth::user()->zone2];
                         $mobile = mobilead::whereIn('zone', $zones)->where('status', 'pending')
                                                                                ->where('hod_permit_status', null)
                                                                                ->with(['user',  'appHistoryMobile', 'vehicleMobile'])->paginate(20);
                                    // var_dump($mobile);die();
                                    if(count($mobile) == 0) {
                                                return response()->json(['data' => 'Empty Resultset'], 422);
                                    } else {
                                            $user = Auth::user();
                                            $activityInfo = new AdminActivity();
                                            $fetchActivity = 'Fetched all mobile ads';
                                            $activityInfo->action = $fetchActivity;
                                            $activityInfo->user_admin_id = (string)$user->id;
                                            $activityInfo->save();
                                            return response()->json(['data' => $mobile], 200);
                                    }

                     }elseif(Auth::user()->department == "Mobile_advert" && Auth::user()->admin_role_id == 5){
                                $line_ids = UserAdmin::where('line_manager', (string)Auth::user()->id)->pluck('id')->toArray();
                                // Convert each element to a string
                                $line_ids_as_strings = array_map('strval', $line_ids);
//                                $mobile = mobilead::whereIn('assigned_officer', $line_ids_as_strings)
//                                                                            ->where('hod_permit_status', 'pending')
//                                                                            ->with(['user', 'appHistoryMobile', 'vehicleMobile'])
//                                                                            ->paginate(20);
                                                                        // var_dump($mobile);die();

                         $mobile = mobilead::where('hod_permit_status', 'pending')
                                                        ->with(['user', 'appHistoryMobile', 'vehicleMobile'])
                                                        ->paginate(20);
                                if(count($mobile) == 0) {
                                        return response()->json(['data' => 'Empty Resultset'], 422);
                                } else {
                                        $user = Auth::user();
                                        $activityInfo = new AdminActivity();
                                        $fetchActivity = 'Fetched all mobile ads';
                                        $activityInfo->action = $fetchActivity;
                                        $activityInfo->user_admin_id = (string)$user->id;
                                        $activityInfo->save();
                                         return response()->json(['data' => $mobile], 200);
                                }

                    }elseif(Auth::user()->admin_role_id == 6){
                                $line_ids = UserAdmin::where('line_manager', (string)Auth::user()->id)->pluck('id')->toArray();
                                // Convert each element to a string
                                $line_ids_as_strings = array_map('strval', $line_ids);
                                $mobile = mobilead::where('final_status', 'pending')->with(['user',  'appHistoryMobile', 'vehicleMobile'])->paginate(20);
                                // var_dump($line_ids_as_strings);die();
                                if(count($mobile) == 0) {
                                        return response()->json(['data' => 'Empty Resultset'], 422);
                                } else {
                                        $user = Auth::user();
                                        $activityInfo = new AdminActivity();
                                        $fetchActivity = 'Fetched all mobile ads';
                                        $activityInfo->action = $fetchActivity;
                                        $activityInfo->user_admin_id = (string)$user->id;
                                        $activityInfo->save();
                                        return response()->json(['data' => $mobile], 200);
                                }

                     } elseif (Auth::user()->admin_role_id == 9) {
                         $mobileTask = mobilead::where('Application_pay_status', 'paid')->where('legal_status', 'pending')
                                                                                        ->with(['user', 'appHistoryMobile', 'vehicleMobile' ])->paginate(20);
                         if(count($mobileTask) == 0) {
                             return response()->json(['data' => 'Empty Resultset'], 422);
                         } else {
                             $user = Auth::user();
                             $activityInfo = new AdminActivity();
                             $fetchActivity = 'Fetched all mobile ads';
                             $activityInfo->action = $fetchActivity;
                             $activityInfo->user_admin_id = (string)$user->id;
                             $activityInfo->save();
                             return response()->json(['data' => $mobileTask], 200);
                         }
                     } else{
                             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
                    }
            }else{
                    return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
            }
    }

    public function getAllThirdPartyMobileAppsMytask(Request $request) {

                if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6 ||
                    Auth::user()->admin_role_id == 5 || Auth::user()->admin_role_id == 9) {


                    if(Auth::user()->department == "Registry" && Auth::user()->admin_role_id == 2 ||
                        Auth::user()->department == "Registry" && Auth::user()->admin_role_id == 3){

                                 $mobile = ThirdPartyMobile::where('assigned_officer', (string)Auth::user()->id)->where('status', 'pending')
                                                                                            ->where('hod_permit_status', null)
                                                                                            ->with(['user', 'vehicleThirdPartyMobile'])->paginate(20);
        // var_dump($mobile);die();
                        if(count($mobile) == 0) {
                                return response()->json(['data' => 'Empty Resultset'], 422);
                        } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Third Party mobile ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                        }

                     }elseif(Auth::user()->department == "Registry" && Auth::user()->admin_role_id == 5){
                            $line_ids = UserAdmin::where('line_manager', (string)Auth::user()->id)->pluck('id')->toArray();
                            // Convert each element to a string
                            $line_ids_as_strings = array_map('strval', $line_ids);
                            $mobile = ThirdPartyMobile::whereIn('assigned_officer', $line_ids_as_strings)
                                                                                        ->where('hod_permit_status', 'pending')
                                                                                        ->with(['user', 'vehicleThirdPartyMobile'])->paginate(20);
                            // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                    return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Third Party mobile ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                            }
                    }elseif(Auth::user()->admin_role_id == 6){
                            $line_id  = UserAdmin::where('line_manager', (string)Auth::user()->id)->first();
                             // var_dump($line_id);die();
                            $mobile = ThirdPartyMobile::where('final_status', 'pending')->with(['user', 'vehicleThirdPartyMobile'])->paginate(20);
                            // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                     return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Third Party mobile ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                             }
                    } elseif (Auth::user()->admin_role_id == 9) {
                        $thirdPartyMobile = ThirdPartyMobile::where('Application_pay_status' , 'paid')->where('legal_status' , 'pending')
                                                                                                            ->with(['user', 'vehicleThirdPartyMobile'])->paginate(20);

                        if(count($thirdPartyMobile) == 0) {
                            return response()->json(['data' => 'Empty Resultset'], 422);
                        } else {
                            $user = Auth::user();
                            $activityInfo = new AdminActivity();
                            $fetchActivity = 'Fetched all Third Party mobile ads';
                            $activityInfo->action = $fetchActivity;
                            $activityInfo->user_admin_id = (string)$user->id;
                            $activityInfo->save();
                            return response()->json(['data' => $thirdPartyMobile], 200);
                        }
                    }
                    else{
                            return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
                     }
                }else{
                    return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
                }
    }

    public function getAllStreetLampAppsMytask(Request $request) {

            if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 6
                || Auth::user()->admin_role_id == 5 || Auth::user()->admin_role_id == 9) {


                if(Auth::user()->department == "Registry" && Auth::user()->admin_role_id == 2 || Auth::user()->department == "Registry" &&
                        Auth::user()->admin_role_id == 3){
                        $eoicheck = StreetLampsAds::where('assigned_officer', (string)Auth::user()->id)->where('eoi_status', 'pending')->exists();
                        $arrayStatus = ['pending', 'approved'];
                        if($eoicheck){
                            $mobile = StreetLampsAds::where('assigned_officer', (string)Auth::user()->id)->whereIn('eoi_status', $arrayStatus)
                                                                    ->where('hod_permit_status', null)->with(['user', 'appHistoryStreetLamp'])->paginate(20);
                        }else{
                            $mobile = StreetLampsAds::where('assigned_officer', (string)Auth::user()->id)->where('status', 'pending')
                                                                            ->where('hod_permit_status', null)->with(['user', 'appHistoryStreetLamp'])->paginate(20);
                        }

                        // var_dump($mobile);die();
                        if(count($mobile) == 0) {
                                 return response()->json(['data' => 'Empty Resultset'], 422);
                        } else {
                            $user = Auth::user();
                            $activityInfo = new AdminActivity();
                            $fetchActivity = 'Fetched all StreetLamp ads';
                            $activityInfo->action = $fetchActivity;
                            $activityInfo->user_admin_id = (string)$user->id;
                            $activityInfo->save();
                            return response()->json(['data' => $mobile], 200);
                        }

                }elseif(Auth::user()->department == "Registry" && Auth::user()->admin_role_id == 5){
                        $line_ids = UserAdmin::where('line_manager', (string)Auth::user()->id)->pluck('id')->toArray();
                         // Convert each element to a string
                        $line_ids_as_strings = array_map('strval', $line_ids);
                        $mobile = StreetLampsAds::whereIn('assigned_officer', $line_ids_as_strings)->where('hod_permit_status', 'pending')->with(['user', 'appHistoryStreetLamp'])->paginate(20);
                        // var_dump($mobile);die();
                        if(count($mobile) == 0) {
                                return response()->json(['data' => 'Empty Resultset'], 422);
                        } else {
                            $user = Auth::user();
                            $activityInfo = new AdminActivity();
                            $fetchActivity = 'Fetched all StreetLamp ads';
                            $activityInfo->action = $fetchActivity;
                            $activityInfo->user_admin_id = (string)$user->id;
                            $activityInfo->save();
                            return response()->json(['data' => $mobile], 200);
                        }
                }elseif(Auth::user()->admin_role_id == 6){
                        $line_id  = UserAdmin::where('line_manager', (string)Auth::user()->id)->first();
                         // var_dump($line_id);die();
                        $mobile = StreetLampsAds::where('final_status', 'pending')->with(['user', 'appHistoryStreetLamp'])->paginate(20);
                        // var_dump($mobile);die();
                        if(count($mobile) == 0) {
                            return response()->json(['data' => 'Empty Resultset'], 422);
                        } else {
                            $user = Auth::user();
                            $activityInfo = new AdminActivity();
                            $fetchActivity = 'Fetched all StreetLamp ads';
                            $activityInfo->action = $fetchActivity;
                            $activityInfo->user_admin_id = (string)$user->id;
                            $activityInfo->save();
                            return response()->json(['data' => $mobile], 200);
                        }
                }elseif (Auth::user()->admin_role_id == 9) {
                    $streetLamps = StreetLampsAds::where('Application_pay_status', 'paid')->where('legal_status', 'pending')
                                                                                        ->with(['user', 'streetLampInfo', 'appHistoryStreetLamp' ])->paginate(20);
                    if(count($streetLamps) == 0) {
                        return response()->json(['data' => 'Empty Resultset'], 422);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all StreetLamp ads';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['data' => $streetLamps], 200);
                    }
                } else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
         }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
    }

    public function getAllOnpremiseAppsMytask(Request $request) {
         $zones = [Auth::user()->zone, Auth::user()->zone2];
         if(Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 1 || Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 11 || 
         Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 5 || Auth::user()->admin_role_id == 8 || Auth::user()->admin_role_id == 4) {


                $lgacheck = Onpremise::where('lga', Auth::user()->lga)->exists();
                // $instituitioncheck = User::find($lgacheck->user_id);
                // var_dump($lgacheck);die();
                        if (Auth::user()->department == "M_I" && Auth::user()->admin_role_id == 1){
                            
                            // if(Auth::user()->lga == $lgacheck->lga){
                            //     $mobile = Onpremise::where('lga', Auth::user()->lga)->where('status', 'pending')
                            //                         ->orwhereHas('OnPremiseAdditional', function($query) {
                            //                         $query->where('status', 'pending')->latest('created_at')->limit(1);})
                            //                         ->orwhereHas('OnPremiseChange', function($query) {
                            //                         $query->where('status', 'pending')->latest('created_at')->limit(1);})
                            //                         ->orwhereHas('OnPremiseRemoval', function($query) {
                            //                         $query->where('status', 'pending')->latest('created_at')->limit(1);})
                            //                         ->paginate(20);
                            //      // var_dump($mobile);die();
                            //     if(count($mobile) == 0) {
                            //          return response()->json(['data' => 'Empty Resultset'], 422);
                            //     } else {
                            //         $user = Auth::user();
                            //         $activityInfo = new AdminActivity();
                            //         $fetchActivity = 'Fetched all Onpremise ads';
                            //         $activityInfo->action = $fetchActivity;
                            //         $activityInfo->user_admin_id = (string)$user->id;
                            //         $activityInfo->save();
                            //         return response()->json(['data' => $mobile], 200);
                            //     }
                            // }
                            
                            
                                // $mobile = Onpremise::where('status', 'pending') // Always filter by 'pending' first
                                //     ->where(function ($query) use ($zones) {
                                //         // Condition 1: Institution users in specific zones
                                //         $query->whereHas('user', function ($subQuery) {
                                //             $subQuery->where('is_institution', 1);
                                //         })
                                //         ->when(!empty($zones), function ($query) use ($zones) {
                                //             $query->whereIn('zone', $zones);
                                //         });
                                //     })
                                //     ->orWhere(function ($query) {
                                //         // Condition 2: Non-institution users in the same LGA
                                //         $query->whereHas('user', function ($subQuery) {
                                //             $subQuery->where('is_institution', 0);
                                //         })
                                //         ->where('lga', Auth::user()->lga);
                                //     })
                                //     ->orWhere(function ($query) {
                                //         // Condition 3: Related models with pending status
                                //         $query->whereHas('OnPremiseAdditional', function ($subQuery) {
                                //             $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                //         })
                                //         ->orWhereHas('OnPremiseChange', function ($subQuery) {
                                //             $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                //         })
                                //         ->orWhereHas('OnPremiseRemoval', function ($subQuery) {
                                //             $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                //         });
                                //     })
                                //     ->paginate(20);
                                
                                if($lgacheck){
                                    $mobile = Onpremise::whereHas('user', function ($subQuery) {
                                        $subQuery->whereNot('is_institution', 1); // Filter by is_institution = 0
                                    })
                                    ->where('lga', Auth::user()->lga) // Filter by lga
                                    ->where('status', 'pending') // Filter by status = 'pending'
                                    ->orWhere(function ($query) {
                                        // Include records with related OnPremiseChange, OnPremiseAdditional, or OnPremiseRemoval
                                        $query->whereHas('user', function ($subQuery) {
                                            $subQuery->whereNot('is_institution', 1); // Filter by is_institution = 0
                                        })
                                        ->where('lga', Auth::user()->lga) // Filter by lga
                                        ->where(function ($query) {
                                            // Check for related records with status = 'pending'
                                            $query->whereHas('OnPremiseChange', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            })
                                            ->orWhereHas('OnPremiseAdditional', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            })
                                            ->orWhereHas('OnPremiseRemoval', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            });
                                        });
                                    })
                                    ->paginate(20);
                                }else{
                                    $mobile = Onpremise::whereHas('user', function ($subQuery) {
                                        $subQuery->where('is_institution', 1); // Filter by is_institution = 0
                                    })
                                    ->whereIn('zone', $zones) // Filter by lga
                                    ->where('status', 'pending') // Filter by status = 'pending'
                                    ->orWhere(function ($query) use ($zones) {
                                        // Include records with related OnPremiseChange, OnPremiseAdditional, or OnPremiseRemoval
                                        $query->whereHas('user', function ($subQuery) {
                                            $subQuery->where('is_institution', 1); // Filter by is_institution = 0
                                        })
                                        ->whereIn('zone', $zones) // Filter by lga
                                        ->where(function ($query) {
                                            // Check for related records with status = 'pending'
                                            $query->whereHas('OnPremiseChange', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            })
                                            ->orWhereHas('OnPremiseAdditional', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            })
                                            ->orWhereHas('OnPremiseRemoval', function ($subQuery) {
                                                $subQuery->where('status', 'pending')->latest('created_at')->limit(1);
                                            });
                                        });
                                    })
                                    ->paginate(20);
                                }
                                
                                if(count($mobile) == 0) {
                                     return response()->json(['data' => 'Empty Resultset'], 422);
                                } else {
                                    $user = Auth::user();
                                    $activityInfo = new AdminActivity();
                                    $fetchActivity = 'Fetched all Onpremise ads';
                                    $activityInfo->action = $fetchActivity;
                                    $activityInfo->user_admin_id = (string)$user->id;
                                    $activityInfo->save();
                                    return response()->json(['data' => $mobile], 200);
                                }


                        }elseif (Auth::user()->admin_role_id == 11){

                            $mobile = Onpremise::whereHas('OnPremiseAdditional', function($query) {
                                                $query->where('cp_status', 'pending')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseChange', function($query) {
                                                $query->where('cp_status', 'pending')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseRemoval', function($query) {
                                                $query->where('cp_status', 'pending')->latest('created_at')->limit(1);})
                                                ->paginate(20);
                             // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                 return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                            }

                        }elseif((Auth::user()->department == "M_I" && Auth::user()->admin_role_id == 2) || (Auth::user()->department == "M_I" &&
                        Auth::user()->admin_role_id == 3)){
                            $zones = [Auth::user()->zone, Auth::user()->zone2];
                            $mobile = Onpremise::whereIn('zone', $zones)->where('rm_status', 'pending')
                                                ->orwhereHas('OnPremiseAdditional', function($query) {
                                                $query->where('rm_status', 'pending')->where('cp_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseChange', function($query) {
                                                $query->where('rm_status', 'pending')->where('cp_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseRemoval', function($query) {
                                                $query->where('rm_status', 'pending')->where('cp_status', 'approved')->latest('created_at')->limit(1);})
                                                ->paginate(20);
                             // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                 return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                            }
                        }elseif(Auth::user()->department == "M_I" && Auth::user()->admin_role_id == 5){
                            $zones = [Auth::user()->zone, Auth::user()->zone2];
                            $mobile = Onpremise::whereIn('zone', $zones)->where('hod_status', 'pending')
                                                ->orwhereHas('OnPremiseAdditional', function($query) {
                                                $query->where('hod_status', 'pending')->where('rm_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseChange', function($query) {
                                                $query->where('hod_status', 'pending')->where('rm_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseRemoval', function($query) {
                                                $query->where('hod_status', 'pending')->where('rm_status', 'approved')->latest('created_at')->limit(1);})
                                                ->paginate(20);
                             // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                 return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                            }
                        }elseif((Auth::user()->department == "Billings" && Auth::user()->admin_role_id == 2) || (Auth::user()->department == "Billings" &&
                        Auth::user()->admin_role_id == 3) || (Auth::user()->department == "Billings" &&
                        Auth::user()->admin_role_id == 5)){
                            // $zones = [Auth::user()->zone, Auth::user()->zone2];
                            $mobile = Onpremise::where('billing_status', 'pending')
                                                ->orwhereHas('OnPremiseAdditional', function($query) {
                                                $query->where('billing_status', 'pending')->where('hod_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseChange', function($query) {
                                                $query->where('billing_status', 'pending')->where('hod_status', 'approved')->latest('created_at')->limit(1);})
                                                ->orwhereHas('OnPremiseRemoval', function($query) {
                                                $query->where('billing_status', 'pending')->where('hod_status', 'approved')->latest('created_at')->limit(1);})
                                                ->paginate(20);
                             // var_dump($mobile);die();
                            if(count($mobile) == 0) {
                                 return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $mobile], 200);
                            }
                        }elseif(Auth::user()->admin_role_id == 6){
                                $line_id  = UserAdmin::where('line_manager', (string)Auth::user()->id)->first();
                                // var_dump($line_id);die();
                                $mobile = Onpremise::where('final_status', 'pending')->paginate(20);
                                // var_dump($mobile);die();
                                 if(count($mobile) == 0) {
                                        return response()->json(['data' => 'Empty Resultset'], 422);
                                 } else {
                                        $user = Auth::user();
                                        $activityInfo = new AdminActivity();
                                        $fetchActivity = 'Fetched all Onpremise ads';
                                        $activityInfo->action = $fetchActivity;
                                        $activityInfo->user_admin_id = (string)$user->id;
                                        $activityInfo->save();
                                        return response()->json(['data' => $mobile], 200);
                                }
                        }elseif (Auth::user()->admin_role_id == 9) {
                            $onpremise = onpremise::where('Application_pay_status', 'paid')->where('legal_status', 'pending')
                                                                                ->with(['user','onpremiseInfo'])->paginate(20);
                            if(count($onpremise) == 0) {
                                return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $onpremise], 200);
                            }
                        }elseif(Auth::user()->admin_role_id == 8){
                            $onpremise = onpremise::where('account_status', 'pending')
                                                ->orwhereHas('OnPremiseAdditional', function($query) {
                                                $query->where('account_status', 'pending')->latest('created_at')->limit(1);})
                                                ->with(['user','onpremiseInfo'])->paginate(20);
                            if(count($onpremise) == 0) {
                                return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $onpremise], 200);
                            }
                        }elseif(Auth::user()->admin_role_id == 4){
                            $onpremise = onpremise::where('audit_status', 'pending')
                                                    ->orwhereHas('OnPremiseAdditional', function($query) {
                                                    $query->where('audit_status', 'pending')->latest('created_at')->limit(1);})
                                                    ->orwhereHas('OnPremiseChange', function($query) {
                                                    $query->where('audit_status', 'pending')->latest('created_at')->limit(1);})
                                                    ->orwhereHas('OnPremiseRemoval', function($query) {
                                                    $query->where('audit_status', 'pending')->latest('created_at')->limit(1);})
                                                    ->with(['user','onpremiseInfo'])->paginate(20);
                            if(count($onpremise) == 0) {
                                return response()->json(['data' => 'Empty Resultset'], 422);
                            } else {
                                $user = Auth::user();
                                $activityInfo = new AdminActivity();
                                $fetchActivity = 'Fetched all Onpremise ads';
                                $activityInfo->action = $fetchActivity;
                                $activityInfo->user_admin_id = (string)$user->id;
                                $activityInfo->save();
                                return response()->json(['data' => $onpremise], 200);
                            }
                        }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
         }else{
             return response()->json(['data' => "Your Admin priviledge can not view this result set"], 422);
         }
    }

    public function getAllThirdPartyKycMytask() {

        if(Auth::user()->department == 'Operations' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 8 || Auth::user()->department == 'Registry'
            || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6) {
                

            if (Auth::user()->department == 'Operations' && Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3) {
                if(Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3) {
                    $getOperationTasks = KycThirdParty::where('operation_status', 'pending')
                        ->with(['user', 'kycThirdPartyScore'])->paginate(20);
                    if (count($getOperationTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'Empty resultset for operation task'], $this->errorStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party expression of interest for operations';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getOperationTasks], $this->successStatusCode);
                    }
                } else {
                    return response()->json(['success' => false, 'data' => 'you can not view this resource'], $this->errorStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 8 || (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                if(Auth::user()->admin_role_id == 9){
                    $getLegalTasks = KycThirdParty::where('operation_status', 'approved')->where('legal_status', 'pending')
                                                                    ->with(['user', 'kycThirdPartyScore'])->paginate(20);
                    if(count($getLegalTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'Empty resultset for legal task'], $this->errorStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party expression of interest for legal';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getLegalTasks], $this->successStatusCode);
                    }
                }
                if(Auth::user()->admin_role_id == 8){
                    $getAccountTasks = KycThirdParty::where('operation_status', 'approved')->where('account_status', 'pending')
                                                    ->with(['user', 'kycThirdPartyScore'])->paginate(20);
                    if(count($getAccountTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'Empty resultset for account task'], $this->errorStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party expression of interest for account';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getAccountTasks], $this->successStatusCode);
                    }
                }
                if(Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3){
                    $getRegistryTasks = KycThirdParty::where('operation_status', 'approved')->where('registry_status', 'pending')
                                                            ->with(['user', 'kycThirdPartyScore'])->paginate(20);

                    if(count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'Empty resultset for registry task'], $this->errorStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party expression of interest for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }  
                }
                
            // } elseif (Auth::user()->admin_role_id == 8) {
            //     $getAccountTasks = KycThirdParty::where('operation_status', 'approved')->where('account_status', 'pending')
            //                                         ->with(['user', 'kycThirdPartyScore'])->paginate(20);
            //     if(count($getAccountTasks) == 0) {
            //         return response()->json(['success' => false, 'data' => 'Empty resultset for account task'], $this->errorStatusCode);
            //     } else {
            //         $user = Auth::user();
            //         $activityInfo = new AdminActivity();
            //         $fetchActivity = 'Fetched all third party expression of interest for account';
            //         $activityInfo->action = $fetchActivity;
            //         $activityInfo->user_admin_id = (string)$user->id;
            //         $activityInfo->save();
            //         return response()->json(['success' => true, 'data' => $getAccountTasks], $this->successStatusCode);
            //     }
            // } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3) {
            //     $getRegistryTasks = KycThirdParty::where('operation_status', 'approved')->where('registry_status', 'pending')
            //                                                 ->with(['user', 'kycThirdPartyScore'])->paginate(20);

            //     if(count($getRegistryTasks) == 0) {
            //         return response()->json(['success' => false, 'data' => 'Empty resultset for registry task'], $this->errorStatusCode);
            //     } else {
            //         $user = Auth::user();
            //         $activityInfo = new AdminActivity();
            //         $fetchActivity = 'Fetched all third party expression of interest for registry';
            //         $activityInfo->action = $fetchActivity;
            //         $activityInfo->user_admin_id = (string)$user->id;
            //         $activityInfo->save();
            //         return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
            //     }
            } elseif (Auth::user()->department == 'Operations' && Auth::user()->admin_role_id == 5) {
                $getHodtasks = KycThirdParty::where('legal_status', 'approved')->where('account_status', 'approved')->where('registry_status', 'approved')
                                                     ->where('hod_status', 'pending')->with(['user', 'kycThirdPartyScore'])->paginate(20);
                if(count($getHodtasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'Empty resultset'], $this->errorStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party expression of interest for hod';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getHodtasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 6) {
                $getMdTasks = KycThirdParty::where('hod_status', 'approved')->where('md_status', 'pending')->with(['user', 'kycThirdPartyScore'])
                                                        ->paginate(20);
                if(count($getMdTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'Empty resultset'], $this->errorStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party expression of interest for md';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getMdTasks], $this->successStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'you do not qualify to view this task'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'you can not access this resource'], $this->errorStatusCode);
        }
    }

    public function getAllThirdPartyOutdoorSignageTask() {

        if(Auth::user()->department == 'Registry' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 8 || Auth::user()->department == 'Billings'
            || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 11) {
                if(Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                    $AdminThirdPartySignageController = new AdminThirdPartySignageController();
                    $runresult = $AdminThirdPartySignageController->annualOutdoorBills();
                        $getRegistryTasks = ThirdPartyOutdoor::where(function($query) {
                        $query->where('application_certify_status', 'pending')
                              ->orWhere(function($query) {
                                  $query->where('application_certify_status', 'approved')
                                        ->whereNull('report_file');
                                  })
                                  ->orWhere('rm_second_recommendation', 'pending');
                        })
                        ->where('assigned_officer', (string)Auth::user()->id)
                        ->orWhere(function($query) {
                            $query->whereIn('ongoing_request', ['offcharge','expunction'])
                                  ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                            $query->where('rm_recommedation', 'pending');
                        });
                        })
                        ->orWhere(function($query) {
                            $query->whereIn('ongoing_request', ['upgrade','downgrade'])
                                  ->whereHas('ThirdPartyUpgradeAndDowngrade', function($query) {
                            $query->where('application_status', 'paid')
                                  ->where('site_inspection_status', 'pending')
                                  ->orWhere(function($query) {
                                      $query->where('site_inspection_status', 'done')
                                            ->whereNull('first_assesment');
                                  })
                                  ->orWhere(function($query) {
                                      $query->where('hod_billngs', 'approved')
                                            ->where('hod_registry', 'approved');
                                  });
                        });
                        })
                        ->orWhere(function($query) {
                            $query->whereIn('ongoing_request', ['transfer'])
                                  ->whereHas('ThirdPartyOutdoorTransfer', function($query) {
                            $query->whereNull('rm_recommendation');
                        });
                        })
                        ->with([
                            'thirdPartyOutdoorSignDetails', 
                            'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                             $query->where('application_status', 'paid')
                                  ->where('site_inspection_status', 'pending')
                                  ->orWhere(function($query) {
                                      $query->where('site_inspection_status', 'done')
                                            ->whereNull('first_assesment');
                                  })
                                  ->orWhere(function($query) {
                                      $query->where('hod_billngs', 'approved')
                                            ->where('hod_registry', 'approved');
                                  })
                                  ->latest('created_at')   // Ensure we only get the latest record
                                  ->limit(1);              // Limit the result to the latest one
                                         }, 
                            'ThirdPartyOutdoorTransfer' => function ($query) {
                                             $query->whereNull('rm_recommendation')
                                                   ->latest('created_at')   // Ensure we only get the latest record
                                                   ->limit(1);              // Limit the result to the latest one
                                         },
                            'ThirdPartyOffchargeAndExpunction' => function ($query) {
                                             $query->whereNull('complaince_confirm_status')
                                                  ->orWhere(function($query) {
                                                      $query->where('complaince_confirm_status', 'approved')
                                                            ->whereNull('site_submission')
                                                            ->whereNull('compliance_report');
                                                  })
                                                   ->latest('created_at')   // Ensure we only get the latest record
                                                   ->limit(1);              // Limit the result to the latest one
                                         }
                        ])
                        ->paginate(20);
                        
                        
                        // $getRegistryTasks = ThirdPartyOutdoor::where(function($query) {
                        // $query->where('application_certify_status', 'pending')
                        //       ->orWhere(function($query) {
                        //           $query->where('application_certify_status', 'approved')
                        //                 ->whereNull('report_file');
                        //           })
                        //           ->orWhere('rm_second_recommendation', 'pending');
                        // })
                        // ->where('assigned_officer', (string)Auth::user()->id)
                        // ->orWhereIn('ongoing_request', ['offcharge','expunction'])
                        // ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                        //     $query->whereNull('complaince_confirm_status')
                        //           ->orWhere(function($query) {
                        //               $query->where('complaince_confirm_status', 'approved')
                        //                     ->whereNull('site_submission');
                        //           });
                        // })
                        // ->with([
                        //     'thirdPartyOutdoorSignDetails', 
                        //     'thirdPartyUpgradeAndDowngrade', 
                        //     'thirdPartyOutdoorTransfer',
                        //     'ThirdPartyOffchargeAndExpunction'
                        // ])
                        // ->paginate(20);
                        
                        
                        
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->admin_role_id == 11) {
                    $getRegistryTasks = ThirdPartyOutdoor::where(function($query) {
                                                            $query->whereIn('ongoing_request', ['offcharge','expunction'])
                                                                  ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                                                            $query->where('complaince_confirm_status', 'pending')
                                                                    ->where('rm_recommedation', 'approved');
                                                        });
                                                        })
                                                         ->with([
                                                             'thirdPartyOutdoorSignDetails',
                                                             'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                                                 $query->where('bill_status', 'generated')
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('first_assesment')
                                                                            ->whereNull('second_assessment');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('second_assessment')
                                                                            ->where('hod_recommendation', 'pending');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNull('hod_registry')
                                                                            ->where('hod_billngs', 'approved');
                                                                  })
                                                                  ->latest('created_at')   // Ensure we only get the latest record
                                                                  ->limit(1);              // Limit the result to the latest one
                                                             },
                                                             'thirdPartyOutdoorTransfer'
                                                             ])
                                                         ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5) {
                    $getRegistryTasks = ThirdPartyOutdoor::where('hod_recommedation', 'pending')
                                                         ->orWhere('hod_second_recommendation', 'pending')
                                                         ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['upgrade','downgrade'])
                                                                  ->whereHas('ThirdPartyUpgradeAndDowngrade', function($query) {
                                                            $query->where('bill_status', 'generated')
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('first_assesment')
                                                                            ->whereNull('second_assessment');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('second_assessment')
                                                                            ->where('hod_recommendation', 'pending');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNull('hod_registry')
                                                                            ->where('hod_billngs', 'approved');
                                                                  });
                                                        });
                                                        })
                                                        ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['offcharge','expunction'])
                                                                  ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                                                            $query->where('hod_recommedation', 'pending');
                                                        });
                                                        })
                                                        ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['transfer'])
                                                                  ->whereHas('ThirdPartyOutdoorTransfer', function($query) {
                                                            $query->where('hod_recommendation', 'pending');
                                                        });
                                                        })
                                                         ->with([
                                                             'thirdPartyOutdoorSignDetails',
                                                             'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                                                 $query->where('bill_status', 'generated')
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('first_assesment')
                                                                            ->whereNull('second_assessment');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNotNull('second_assessment')
                                                                            ->where('hod_recommendation', 'pending');
                                                                  })
                                                                  ->orWhere(function($query) {
                                                                      $query->whereNull('hod_registry')
                                                                            ->where('hod_billngs', 'approved');
                                                                  })
                                                                  ->latest('created_at')   // Ensure we only get the latest record
                                                                  ->limit(1);              // Limit the result to the latest one
                                                             },
                                                             'thirdPartyOutdoorTransfer'
                                                             ])
                                                         ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->admin_role_id == 6) {
                    $getRegistryTasks = ThirdPartyOutdoor::where('md_first_approval', 'pending')
                                                         ->orWhere('md_second_approval', 'pending')
                                                         ->orWhere(function($query) {
                                                             $query->whereIn('ongoing_request', ['offcharge','expunction'])
                                                                   ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                                                             $query->where('md_approval', 'pending');
                                                         });
                                                         })
                                                         ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['upgrade','downgrade'])
                                                                  ->whereHas('ThirdPartyUpgradeAndDowngrade', function($query) {
                                                            $query->where('md_approval', 'pending');
                                                        });
                                                        })
                                                        ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['transfer'])
                                                                  ->whereHas('ThirdPartyOutdoorTransfer', function($query) {
                                                            $query->where('md_approval', 'pending');
                                                        });
                                                        })
                                                         ->with([
                                                             'thirdPartyOutdoorSignDetails',
                                                             'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                                                 $query->where('md_approval', 'pending')
                                                                       ->latest('created_at')   // Ensure we only get the latest record
                                                                       ->limit(1);              // Limit the result to the latest one
                                                             },
                                                             'thirdPartyOutdoorTransfer' => function ($query) {
                                                                 $query->where('md_approval', 'pending')
                                                                       ->latest('created_at')   // Ensure we only get the latest record
                                                                       ->limit(1);              // Limit the result to the latest one
                                                             },
                                                             'ThirdPartyOffchargeAndExpunction' => function ($query) {
                                                                 $query->where('complaince_confirm_status', 'approved')
                                                                       ->whereNotNull('site_submission')
                                                                       ->whereNull('md_approval')
                                                                       ->latest('created_at')   // Ensure we only get the latest record
                                                                       ->limit(1);              // Limit the result to the latest one
                                                             }
                                                             ])
                                                         ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->admin_role_id == 9) {
                    $getRegistryTasks = ThirdPartyOutdoor::where('legal_recommendation', 'pending')->with(['thirdPartyOutdoorSignDetails',
                        'thirdPartyUpgradeAndDowngrade', 'thirdPartyOutdoorTransfer'])->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->department == 'Billings' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                    $getRegistryTasks = ThirdPartyOutdoor::whereNull('bill_generated')
                                     ->where('md_second_approval', 'approved')
                                     ->orWhere(function($query) {
                                         $query->whereIn('active_status', ['off_charge', 'expunction'])
                                               ->whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                                                   $query->where('offcharge_expunction_bill', false)
                                                         ->where('md_approval', 'approved')
                                                         ->latest('created_at');  // Assuming `created_at` is the timestamp column
                                               });
                                     })
                                     ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['upgrade','downgrade'])
                                                                  ->whereHas('ThirdPartyUpgradeAndDowngrade', function($query) {
                                                            $query->where('md_approval', 'approved')
                                                                  ->whereNull('bill_status');
                                                        });
                                                        })
                                     ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['transfer'])
                                                                  ->whereHas('ThirdPartyOutdoorTransfer', function($query) {
                                                            $query->where('md_approval', 'approved')
                                                                  ->whereNull('transfer_bill');
                                                        });
                                                        })
                                     ->with([
                                         'thirdPartyOutdoorSignDetails',
                                         'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                                                 $query->where('md_approval', 'approved')
                                                                       ->whereNull('bill_status')
                                                                       ->latest('created_at')   // Ensure we only get the latest record
                                                                       ->limit(1);              // Limit the result to the latest one
                                                             },
                                         'thirdPartyOutdoorTransfer' => function ($query) {
                                                                 $query->where('md_approval', 'approved')
                                                                       ->latest('created_at')   // Ensure we only get the latest record
                                                                       ->limit(1);              // Limit the result to the latest one
                                                             },
                                         'ThirdPartyOffchargeAndExpunction' => function ($query) {
                                             $query->where('offcharge_expunction_bill', false)
                                                   ->where('md_approval', 'approved')
                                                   ->latest('created_at')   // Ensure we only get the latest record
                                                   ->limit(1);              // Limit the result to the latest one
                                         }
                                     ])
                                     ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                } elseif (Auth::user()->department == 'Billings' && Auth::user()->admin_role_id == 5) {
                    $getRegistryTasks = ThirdPartyOutdoor::where('hod_bill_generate', 'pending')
                                     ->where('bill_generated', true)
                                     ->orWhere(function($query) {
                                                            $query->whereIn('ongoing_request', ['upgrade','downgrade'])
                                                                  ->whereHas('ThirdPartyUpgradeAndDowngrade', function($query) {
                                                            $query->whereNull('hod_billngs')
                                                                  ->where('bill_status', 'generated');
                                                        });
                                                        })
                                     ->with([
                                         'thirdPartyOutdoorSignDetails',
                                         'thirdPartyUpgradeAndDowngrade' => function ($query) {
                                             $query->whereNull('hod_billngs')
                                                   ->where('bill_status', 'generated')
                                                   ->latest('created_at')   // Ensure we only get the latest record
                                                   ->limit(1);              // Limit the result to the latest one
                                         },
                                         'thirdPartyOutdoorTransfer',
                                         'ThirdPartyOffchargeAndExpunction'
                                     ])
                                     ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                }elseif (Auth::user()->admin_role_id == 8){
                    $getRegistryTasks = ThirdPartyOutdoor::where('account_status', 'pending')
                                                         ->paginate(20);
                    if (count($getRegistryTasks) == 0) {
                        return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                    } else {
                        $user = Auth::user();
                        $activityInfo = new AdminActivity();
                        $fetchActivity = 'Fetched all third party outdoor signage application for registry';
                        $activityInfo->action = $fetchActivity;
                        $activityInfo->user_admin_id = (string)$user->id;
                        $activityInfo->save();
                        return response()->json(['success' => true, 'data' => $getRegistryTasks], $this->successStatusCode);
                    }
                }
        } else {
            return response()->json(['success' => false, 'data' => 'you do not have the privilege to view the resource'], $this->errorStatusCode);
        }
    }

    public function getAllThirdPartyOffchargeandExpunctionTask() {
        if(Auth::user()->department == 'Registry' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 8 || Auth::user()->department == 'Billings'
            || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6 || Auth::user()->admin_role_id == 12) {
            if(Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                // $getOffchargeandExpunctionTask = ThirdPartyOffchargeAndExpunction::where('complaince_confirm_status', null)->paginate(20);
                $getOffchargeandExpunctionTask = ThirdPartyOutdoor::whereHas('ThirdPartyOffchargeAndExpunction', function($query) {
                            $query->whereNull('complaince_confirm_status')
                                  ->orWhere(function($query) {
                                      $query->where('complaince_confirm_status', 'approved')
                                            ->whereNull('site_submission');
                                  });
                        })
                        ->where('assigned_officer', (string)Auth::user()->id)
                        ->with(['ThirdPartyOffchargeAndExpunction'])
                        ->paginate(20);
                // $getAllSmallFormatMyTask = SmallFormatAds::whereHas('SmallFormatDetails', function($q) {
                //                                 $q->where('hod_recommendation', 'pending');
                //                             })
                //                             ->with(['SmallFormatDetails'])
                //                             ->paginate(20);
                if (count($getOffchargeandExpunctionTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage offcharge and expunction application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getOffchargeandExpunctionTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                $getOffchargeandExpunctionTask = ThirdPartyOffchargeAndExpunction::where('compliance_report', null)
                    ->where('site_submission', null)
                    ->paginate(20);
                if (count($getOffchargeandExpunctionTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage offcharge and expunction application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getOffchargeandExpunctionTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 6) {
                $getOffchargeandExpunctionTask = ThirdPartyOffchargeAndExpunction::where('md_approval', null)->paginate(20);
                if(count($getOffchargeandExpunctionTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage offcharge and expunction application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getOffchargeandExpunctionTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 12) {
                $getOffchargeandExpunctionTask = ThirdPartyOffchargeAndExpunction::where('md_approval', 'approved')->paginate(20);
                if(count($getOffchargeandExpunctionTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage offcharge and expunction application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getOffchargeandExpunctionTask], $this->successStatusCode);
                }
            }
        } else {
            return response()->json(['success' => false, 'data' => 'you do not have the privilege to view the resource'], $this->errorStatusCode);
        }
    }

    public function getAllThirdPartyUpgradeAndDowngradeTask() {
        if(Auth::user()->department == 'Registry' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->admin_role_id == 9 || Auth::user()->admin_role_id == 8 || Auth::user()->department == 'Billings'
            || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6) {
            if (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('site_inspection_status', 'pending')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('first_assesment', null)->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('second_assessment', null)->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('hod_recommendation', 'pending')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 6) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('md_approval', 'pending')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 12) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('md_approval', 'approved')
                                    ->where('bill_status', null)->orWhere('bill_status', 'pending')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Billings' && Auth::user()->admin_role_id == 5) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('hod_billngs', null)->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('hod_registry', null)->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id ==3)) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('bill_status', 'generated')
                    ->where('hod_billngs', 'approved')->where('hod_registry', 'approved')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id ==3)) {
                $getThirdPartyUpgradeandDowngradeTasks = ThirdPartyUpgradeAndDowngrade::where('bill_payment_status', 'paid')->paginate(20);
                if (count($getThirdPartyUpgradeandDowngradeTasks) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getThirdPartyUpgradeandDowngradeTasks], $this->successStatusCode);
                }
            }
        } else {
            return response()->json(['success' => false, 'data' => 'you do not have the privilege to view the resource'], $this->errorStatusCode);
        }
    }
    
    public function getAllSmallFormatMyTask() {
        if(Auth::user()->department == 'Registry' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->department == 'Billings' || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6) {
            if (Auth::user()->department == 'Registry' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                $getAllSmallFormatMyTask = SmallFormatAds::where(function($query) {
                            $query->where('application_pay_status', 'paid')
                                  ->whereNull('inspection_fee')
                                  ->orWhere(function($query) {
                                      $query->where('application_site_inspection_status', 'paid')
                                            ->whereHas('SmallFormatDetails', function($q) {
                                                $q->where('certify_application', 'pending');
                                            });
                                  });
                        })
                        ->where('assigned_officer', (string)Auth::user()->id)
                        ->with(['SmallFormatDetails'])
                        ->paginate(20);
                
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5) {
                $getAllSmallFormatMyTask = SmallFormatAds::whereHas('SmallFormatDetails', function($q) {
                                                $q->where('hod_recommendation', 'pending');
                                            })
                                            ->with(['SmallFormatDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 6) {
                $getAllSmallFormatMyTask = SmallFormatAds::whereHas('SmallFormatDetails', function($q) {
                                                $q->where('md_approval', 'pending');
                                            })
                                            ->with(['SmallFormatDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Billings' && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                $getAllSmallFormatMyTask = SmallFormatAds::whereHas('SmallFormatDetails', function($q) {
                                                $q->where('md_approval', 'approved')
                                                  ->where('bill_generated', 'pending');
                                            })
                                            ->with(['SmallFormatDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->department == 'Billings' && Auth::user()->admin_role_id == 5) {
                $getAllSmallFormatMyTask = SmallFormatAds::whereHas('SmallFormatDetails', function($q) {
                                                $q->where('bill_generated', 'generated')
                                                  ->where('final_bill_generated', 'pending');
                                            })
                                            ->with(['SmallFormatDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all third party outdoor signage upgrade and downgrade application for registry';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            }
        } else {
            return response()->json(['success' => false, 'data' => 'you do not have the privilege to view the resource'], $this->errorStatusCode);
        }
    }
    
    public function getAllTemporaryAdsMyTask() {
        if(Auth::user()->department == 'Registry' || Auth::user()->department == 'Mobile_advert' || Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3
            || Auth::user()->department == 'Billings' || Auth::user()->admin_role_id == 5  || Auth::user()->admin_role_id == 6) {
            if ((Auth::user()->department == 'Registry' || Auth::user()->department == 'Mobile_advert') && (Auth::user()->admin_role_id == 2 || Auth::user()->admin_role_id == 3)) {
                if(Auth::user()->department == 'Mobile_advert'){
                    $zones = [Auth::user()->zone, Auth::user()->zone2];
                    $getAllSmallFormatMyTask = FirstPartyTemporaryAds::where('rm_recommendation', 'pending')
                        ->where('assigned_department', Auth::user()->department)
                        ->whereIn('zone', $zones)
                        ->with(['firstPartyTemporaryAdsDetails'])
                        ->paginate(20);
                }elseif(Auth::user()->department == 'Registry'){
                    $getAllSmallFormatMyTask = FirstPartyTemporaryAds::where('rm_recommendation', 'pending')
                        ->where('assigned_department', Auth::user()->department)
                        ->where('assigned_officer', (string)Auth::user()->id)
                        ->with(['firstPartyTemporaryAdsDetails'])
                        ->paginate(20);
                }
                
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all temporary ads application';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif ((Auth::user()->department == 'Registry' || Auth::user()->department == 'Mobile_advert') && Auth::user()->admin_role_id == 5) {
                // Log::info(Auth::user()->department);
                $getAllSmallFormatMyTask = FirstPartyTemporaryAds::where('hod_recommendation', 'pending')->where('assigned_department', Auth::user()->department)
                                            ->with(['firstPartyTemporaryAdsDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all temporary ads application';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            } elseif (Auth::user()->admin_role_id == 6) {
                $getAllSmallFormatMyTask = FirstPartyTemporaryAds::where('md_approval', 'pending')->where('assigned_department', 'Registry')
                                            ->with(['firstPartyTemporaryAdsDetails'])
                                            ->paginate(20);
                if (count($getAllSmallFormatMyTask) == 0) {
                    return response()->json(['success' => false, 'data' => 'No current task available'], $this->successStatusCode);
                } else {
                    $user = Auth::user();
                    $activityInfo = new AdminActivity();
                    $fetchActivity = 'Fetched all temporary ads application';
                    $activityInfo->action = $fetchActivity;
                    $activityInfo->user_admin_id = (string)$user->id;
                    $activityInfo->save();
                    return response()->json(['success' => true, 'data' => $getAllSmallFormatMyTask], $this->successStatusCode);
                }
            }
        } else {
            return response()->json(['success' => false, 'data' => 'you do not have the privilege to view the resource'], $this->errorStatusCode);
        }
    }

    public function getLoginAdminInfo() {
        $adminId = Auth::guard('adminweb')->user()->id;
        $admin = UserAdmin::where('id', $adminId)->get();
        return response()->json(['data' => $admin], 200);
    }

    public function getActivityTimeline() {

        $userId = Auth::user()->id;
        $fetchActvityTimeline = AdminActivity::where('user_admin_id', $userId)
                                                                ->orderBy('created_at', 'DESC')->get();
        if(count($fetchActvityTimeline) == 0) {
            return response()->json(['data' => 'Empty timeline for admin'], 422);
        } else {
            return response()->json(['data' => $fetchActvityTimeline], 200);
        }
    }

    public function adminLogout() {
        $token = Auth::user()->token();
        $token->revoke();
        return response()->json(['success' => true, 'message' => 'user successfully log out'], 200);
    }

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

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

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

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

        $mail->isHTML(true);

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

    }


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

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

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

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

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

    public static function generateAdminId() {
        // $prefix = '120';
        $prefix = rand(10, 99);
        // $batchKey = Carbon::now()->format('Ymds');
        $batchKey = Carbon::now()->format('mds');
        $suffix = rand(10, 99);
        return $prefix.$batchKey.$suffix;
        // return $prefix.$suffix;
    }

    public static function generatePassword() {
        $length = 12;
        $character =  'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()-_+=<>?';
        $batchKey = Str::random($length, $character);
        $prefix = Carbon::now()->format('YmdHis');
        return $batchKey.$prefix;
    }
    
    public function getEmailContent() {
        
        $contents = EmailContent::all();
        return response()->json(['success' => true, 'data' => $contents], $this->successStatusCode);
    }
    
    public function updateEmailContent(Request $request, $id) {
        
        $content = EmailContent::findOrFail($id);
        $content->update(['content' => $request->content]);
        return response()->json(['success' => true, 'data' => 'Content updated!'], $this->successStatusCode);
    }
}
