<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\AppHistoryThirdPartyOutdoor;
use App\Models\KycThirdParty;
use App\Models\ThirdPartyOffchargeAndExpunction;
use App\Models\ThirdPartyOutdoor;
use App\Models\ThirdPartyOutdoorSignDetails;
use App\Models\ThirdPartyOutdoorTransfer;
use App\Models\ThirdPartyUpgradeAndDowngrade;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\OutdoorSignagePricingApplication;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class ThirdPartySignageController extends Controller
{
    private $successStatusCode = 200;
    private $createStatusCode = 201;
    private $errorStatusCode = 422;

    public function __construct() {
        // $this->middleware('auth:api'); // Apply authentication first
        $this->middleware('check.multi.guard'); // Then apply your custom middleware
    }

    public function createOutdoorSignage(Request $request) {

        if(empty($request->type)){
            $user = Auth::guard('api')->user();
            $uid = $user->id;
            $utype = $user->user_type;
        }elseif($request->type == "admin"){
            $uid = $request->ud;
            $udcheck = User::find((string)$uid);
            $utype = $udcheck->user_type;
        }
        if($utype == 'third_party') {
            $getThirdPartyKycDetails = KycThirdParty::where('user_id', (string) $uid)->get();
            $getKycObj = KycThirdParty::find($getThirdPartyKycDetails[0]['id']);
            $userObj = User::find((string)$uid);
            if($getKycObj->kyc_active) {
                $validate = Validator::make($request->all(), [
                    'applicationPurpose' => 'required|string',
                    'typeSign' => 'required|string',
                    'signageAddress' =>  'required|string',
                    'lga' =>  'required|string',
                    'latitude' => 'required|numeric',
                    'longitude' => 'required|numeric',
                    'north' => 'required|numeric',
                    'east' => 'required|numeric',
                    'propertyOwnerName' => 'required|string',
                    'propertyOwnerEmail' => 'required|email',
                    'propertyOwnerphone' => 'required|string',
                    'propertyOwnerConsent' => 'required|boolean',
                    'propertyOwnerSignature' => 'nullable|string',
                    'structureHeight' => 'required|numeric',
                    'lengthSign' => 'required|numeric',
                    'breadthSign' => 'required|numeric',
                    'setbackDistance' => 'required|numeric',
                    'signageFormat' => 'required|string|in:Portrait,Landscape',
                    'numberFaces' => 'required|integer',
                    'signLighten' => 'required|string|in:None,Internal,External,L.E.D',
                    'signInteraction' => 'required|string|in:None/Static,Changing,Flashing,Others',
                    'photoMontage' => 'required|string',
                    'locationMap' => 'required|string'
                ]);

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

                $outdoorApplicationInput = $request->all();
                $utilMethod = new UtilMethods();

                // $rmRole = [2,3];
                // $getAssignedOfficer  = UserAdmin::where('department', 'Registry')->whereIn('admin_role_id', $rmRole)->pluck('id')->toArray();
                // // var_dump($getAssignedOfficer); die();

                // foreach ($getAssignedOfficer as $officer) {
                //     $counter = ThirdPartyOutdoor::where('assigned_officer', (string) $officer)->count();
                //     $officerCounter[$officer] = $counter;
                // }

                // $leastOfficer = array_search(min($officerCounter), $officerCounter);
                // $getLeastOfficer = UserAdmin::where('id', (string) $leastOfficer)->first();

                $thirdPartyOutdoor = new ThirdPartyOutdoor();
                $thirdPartyOutdoor->purpose_application = $outdoorApplicationInput['applicationPurpose'];
                $thirdPartyOutdoor->type_sign = $outdoorApplicationInput['typeSign'];
                $thirdPartyOutdoor->payment_id = $utilMethod->thirdPartyOutdoorPaymentId();
                $thirdPartyOutdoor->address_proposed_site = strtolower($outdoorApplicationInput['signageAddress']);
                $thirdPartyOutdoor->lga = strtolower($outdoorApplicationInput['lga']);
                $thirdPartyOutdoor->latitude = $outdoorApplicationInput['latitude'];
                $thirdPartyOutdoor->longitude = $outdoorApplicationInput['longitude'];
                $thirdPartyOutdoor->north = strtolower($outdoorApplicationInput['north']);
                $thirdPartyOutdoor->east = strtolower($outdoorApplicationInput['east']);
                $thirdPartyOutdoor->property_owner_name = $outdoorApplicationInput['propertyOwnerName'];
                $thirdPartyOutdoor->property_owner_email = strtolower($outdoorApplicationInput['propertyOwnerEmail']);
                $thirdPartyOutdoor->property_owner_phone = $outdoorApplicationInput['propertyOwnerphone'];
                $thirdPartyOutdoor->property_owner_consent = $outdoorApplicationInput['propertyOwnerConsent'];
                // $thirdPartyOutdoor->assigned_officer = (string)$getLeastOfficer->id;
                $thirdPartyOutdoor->assigned_officer = (string)$getKycObj->assigned_officer;
                $thirdPartyOutdoor->property_owner_signature = $utilMethod->convertBase64toImage($outdoorApplicationInput['propertyOwnerSignature']);
                $saveDetails = $userObj->thirdPartyOutdoor()->save($thirdPartyOutdoor);
                $output [] = $saveDetails;

                $thirdPartyObj = ThirdPartyOutdoor::find($output[0]['id']);
                $thirdPartyOutdoorSignDetails = new ThirdPartyOutdoorSignDetails();
                $thirdPartyOutdoorSignDetails->height_structure = $outdoorApplicationInput['structureHeight'];
                $thirdPartyOutdoorSignDetails->length_sign = $outdoorApplicationInput['lengthSign'];
                $thirdPartyOutdoorSignDetails->breadth_sign = $outdoorApplicationInput['breadthSign'];
                $thirdPartyOutdoorSignDetails->designation = $outdoorApplicationInput['typeSign'];
                $thirdPartyOutdoorSignDetails->dimension_sign = ($outdoorApplicationInput['lengthSign'] * $outdoorApplicationInput['breadthSign']);
                $thirdPartyOutdoorSignDetails->setback_distance = $outdoorApplicationInput['setbackDistance'];
                $thirdPartyOutdoorSignDetails->signage_format = strtolower($outdoorApplicationInput['signageFormat']);
                $thirdPartyOutdoorSignDetails->number_faces = $outdoorApplicationInput['numberFaces'];
                $thirdPartyOutdoorSignDetails->sign_illumination = strtolower($outdoorApplicationInput['signLighten']);
                $thirdPartyOutdoorSignDetails->sign_interaction = strtolower($outdoorApplicationInput['signInteraction']);
                $thirdPartyOutdoorSignDetails->photomontage = $utilMethod->convertBase64toImage($outdoorApplicationInput['photoMontage']);
                $thirdPartyOutdoorSignDetails->location_map = $utilMethod->convertBase64toPdfV2($outdoorApplicationInput['locationMap']);
                $thirdPartyObj->thirdPartyOutdoorSignDetails()->save($thirdPartyOutdoorSignDetails);
                $response  = ThirdPartyOutdoor::where('id', $thirdPartyObj->id)->with(['thirdPartyOutdoorSignDetails'])->get();

                $checkSignType = $outdoorApplicationInput['typeSign'];

                $applicationPrice = 0;
                $inspectPrice = 0;
                $pricingapp = OutdoorSignagePricingApplication::where('fee_type', 'Regular_fee')->first();
                if (str_contains($checkSignType, "LED")) {
                    $applicationPrice = $pricingapp->led_price;
                    $inspectPrice = $pricingapp->inspection_fee;
                } else {
                    $applicationPrice = $pricingapp->normal_price;
                    $inspectPrice = $pricingapp->inspection_fee;
                }

                $totalApplicationPrice = intval($applicationPrice + $inspectPrice);
                $chargeFee = intval(2000);
                $appHistory = new AppHistoryThirdPartyOutdoor();
                $appHistory->purpose_application = $outdoorApplicationInput['applicationPurpose'];
                $appHistory->application_price = $totalApplicationPrice;
                $thirdPartyObj->appHistoryThirdPartyOutdoor()->save($appHistory);

                return response()->json(['success' => true, 'data' => $response, 'total_price' => $totalApplicationPrice,
                    'chargeFee' => $chargeFee, 'public_key' => getenv('APPLICATION_BACK')], $this->createStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'your license is not active to apply for signage, renew your license'],
                    $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'wrong user type'], $this->errorStatusCode);
        }
    }
    
    public function secondPhaseOutdoorSignage(Request $request, $id) {

        if(empty($request->type)){
            $user = Auth::guard('api')->user();
            $uid = $user->id;
            $utype = $user->user_type;
        }elseif($request->type == "admin"){
            $uid = $request->ud;
            $udcheck = User::find((string)$uid);
            $utype = $udcheck->user_type;
        }
        if($utype == 'third_party') {
            $getThirdPartyKycDetails = KycThirdParty::where('user_id', (string) $uid)->get();
            $getKycObj = KycThirdParty::find($getThirdPartyKycDetails[0]['id']);
            $userObj = User::find((string)$uid);
            if($getKycObj->kyc_active) {
                $validate = Validator::make($request->all(), [
                    'structuralDrawings' => 'required|string',
                    'EIA' => 'required|string'
                ]);

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

                $outdoorApplicationInput = $request->all();
                $utilMethod = new UtilMethods();


                $structuralDrawings = $utilMethod->convertBase64toPdfV2($outdoorApplicationInput['structuralDrawings']);
                $EIA = $utilMethod->convertBase64toPdfV2($outdoorApplicationInput['EIA']);
                
                ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $id)->update(['structural_drawing' => $structuralDrawings, 'eia' => $EIA]);
                ThirdPartyOutdoor::where('id', $id)->update(['rm_second_recommendation' => 'pending']);
                
                $response  = ThirdPartyOutdoor::where('id', $id)->with(['thirdPartyOutdoorSignDetails'])->get();

                return response()->json(['success' => true, 'data' => $response], $this->createStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'your license is not active to apply for signage, renew your license'],
                    $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'wrong user type'], $this->errorStatusCode);
        }
    }

    public function getOneofMyOutdoorSignage($outdoorId) {

        $getOneOutdoor = ThirdPartyOutdoor::where('id', $outdoorId)
            ->with(['user', 'thirdPartyOutdoorSignDetails'])
            ->with(['thirdPartyUpgradeAndDowngrade' => function($query) {
                $query->latest()->first();
            }])->with(['thirdPartyOutdoorTransfer' => function($query) {
                $query->latest()->first();
            }])->with(['thirdPartyOffChargeAndExpunction' => function($query) {
                $query->latest()->first();
            }])->first();

        if (is_null($getOneOutdoor)) {
            return response()->json(['success' => false, 'data' => 'There is no outdoor signage application with the outdoor id'], $this->errorStatusCode);
        }
        if ($getOneOutdoor->user_id == Auth::guard('api')->user()->id){
            if(Carbon::parse($getOneOutdoor->created_at)->year > Carbon::now()->year) {
                $showbuttons = true;
            }else{
                $showbuttons = false;
            }
            
            if((int)$getOneOutdoor->permit_year < (int)Carbon::now()->year){
              $newyearbill = false;  
            }else{
              $newyearbill = true;
            }
        return response()->json(['success' => true, 'data' => $getOneOutdoor, 'show' => $showbuttons, 'new_year_bill' => $newyearbill], $this->successStatusCode);
        }else{
            $outdoorTransfer = ThirdPartyOutdoor::where('id', $outdoorId)->whereHas('ThirdPartyOutdoorTransfer', function($q) {
                                                $q->where('new_owner_id', (string)Auth::guard('api')->user()->id)
                                                  ->where('rm_recommendation', 'waiting');
                                            })
                                            ->with(['user', 'thirdPartyOutdoorSignDetails'])
                                            ->with(['thirdPartyUpgradeAndDowngrade' => function($query) {
                                                $query->latest()->first();
                                            }])->with(['thirdPartyOutdoorTransfer' => function($query) {
                                                $query->latest()->first();
                                            }])->with(['thirdPartyOffChargeAndExpunction' => function($query) {
                                                $query->latest()->first();
                                            }])->first();
            return response()->json(['success' => true, 'data' => $outdoorTransfer], $this->successStatusCode);
        }
    }
    
    public function appealOutdoorSignage(Request $request, $id) {

        if(empty($request->type)){
            $user = Auth::guard('api')->user();
            $uid = $user->id;
            $utype = $user->user_type;
        }elseif($request->type == "admin"){
            $uid = $request->ud;
            $udcheck = User::find((string)$uid);
            $utype = $udcheck->user_type;
        }
        if($utype == 'third_party') {
            $getThirdPartyKycDetails = KycThirdParty::where('user_id', (string) $uid)->get();
            $getKycObj = KycThirdParty::find($getThirdPartyKycDetails[0]['id']);
            $userObj = User::find((string)$uid);
            if($getKycObj->kyc_active) {
                $validate = Validator::make($request->all(), [
                    'appealReason' => 'required|string'
                ]);

                if ($validate->fails()) {
                    return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
                }
                
                
                $response  = ThirdPartyOutdoor::where('id', $id)->with(['thirdPartyOutdoorSignDetails'])->get();
                ThirdPartyOutdoor::where('id', $id)->update(['appeal_reason' => $request['appealReason']]);

                
                $applicationPrice = 50000;
                

                $totalApplicationPrice = intval($applicationPrice);
                $chargeFee = intval(2 / 100) * $totalApplicationPrice;
                // $appHistory = new AppHistoryThirdPartyOutdoor();
                // $appHistory->purpose_application = $outdoorApplicationInput['applicationPurpose'];
                // $appHistory->application_price = $totalApplicationPrice;
                // $thirdPartyObj->appHistoryThirdPartyOutdoor()->save($appHistory);

                return response()->json(['success' => true, 'data' => $response, 'total_price' => $totalApplicationPrice,
                    'chargeFee' => $chargeFee, 'public_key' => getenv('APPLICATION_BACK')], $this->createStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'your license is not active to apply for signage, renew your license'],
                    $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'wrong user type'], $this->errorStatusCode);
        }
    }

    public function  searchThirdPartyUser(Request $request) {

        $userId = Auth::guard('api')->user()->id;
        $keyword = $request->input('search');

        $getThirdPartyUser = User::where('user_type', 'third_party')->where('id', '!=' , $userId)->with(['kycThirdParty']);

        if($keyword) {
            $getThirdPartyUser->where(function ($query) use ($keyword) {
                $query->where('first_name','like',  '%' . $keyword . '%')
                    ->orWhere('last_name', 'like',  '%' . $keyword . '%')
                    ->orWhere('business_name', 'like' , '%' . $keyword . '%')
                    ->orWhere('email', 'like', '%' . $keyword .  '%');
            });

            $getThirdPartyUser->orWhereHas('kycThirdParty', function ($query) use ($keyword) {
                $query->where('company_name', 'like',  '%' . $keyword .'%')
                    ->orWhere('nearest_bustop', 'like',  '%' . $keyword . '%')
                    ->orWhere('lga', 'like' ,  '%' . $keyword . '%')
                    ->orWhere('office_address', 'like',  '%' . $keyword . '%')
                    ->orWhere('company_type', 'like' ,  '%' . $keyword . '%');
            });
        }
        $getThirdPartUsersItem = $getThirdPartyUser->paginate(20);

        if($getThirdPartUsersItem->count() > 0) {
            return response()->json(['success' => true, 'data' => $getThirdPartUsersItem], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'user does not exist'], $this->errorStatusCode);
        }
    }

    public function getAllMyOutdoorSignage(Request $request)
    {

        if (Auth::guard('api')->user()->user_type == 'third_party') {
            $userId = Auth::guard('api')->user()->id;

            $keyword = $request->input('search');
            $getAllMyOutdoorSigns = ThirdPartyOutdoor::where('user_id', $userId)->with(['user', 'thirdPartyOutdoorSignDetails',
                'appHistoryThirdPartyOutdoor', 'thirdPartyOffChargeAndExpunction', 'thirdPartyUpgradeAndDowngrade', 'thirdPartyOutdoorTransfer']);

            if ($keyword) {
                $getAllMyOutdoorSigns->where(function ($query) use ($keyword) {
                    $query->where('purpose_application', 'like',  '%' . $keyword . '%')
                        ->where('address_proposed_site', 'like', '%' . $keyword . '%')
                        ->where('lga', 'like',  '%' . $keyword . '%')
                        ->where('property_owner_name', 'like',  '%' . $keyword . '%');
                });

                $getAllMyOutdoorSigns->orWhereHas('user', function ($query) use ($keyword) {
                    $query->where('first_name', 'like',  '%' . $keyword . '%')
                        ->where('last_name', 'like',  '%' . $keyword . '%')
                        ->where('email', 'like',  '%' . $keyword . '%')
                        ->where('phone_number', 'like',  '%' . $keyword . '%');
                });

                $getAllMyOutdoorSigns->orWhereHas('thirdPartyOutdoorSignDetails', function ($query) use ($keyword) {
                    $query->where('signage_format','like',  '%' . $keyword . '%')
                        ->where('sign_interaction', 'like', '%' . $keyword . '%')
                        ->where('sign_illumination', 'like',  '%' . $keyword . '%')
                        ->where('number_faces', 'like',  '%' . $keyword . '%');
                });
            }
            $getAllItems = $getAllMyOutdoorSigns->orderBy('created_at', 'desc')->paginate(20);
            return response()->json(['success' => true, 'data' => $getAllItems], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'sorry you are not third party practitioner'], $this->errorStatusCode);
        }
    }

    public function editOutdoorApplication(Request $request, $outdoorId) {

        if(Auth::guard('api')->user()->user_type == 'third_party') {
            $getApplicationObj = ThirdPartyOutdoor::find($outdoorId);
            if($getApplicationObj->user_id == (string) Auth::guard('api')->user()->id) {
                if($getApplicationObj->application_certify_status == 'disapproved') {
                    $validate = Validator::make($request->all(), [
                        'applicationPurpose' => 'nullable|string',
                        'typeSign' => 'nullable|string',
                        'signageAddress' =>  'nullable|string',
                        'lga' =>  'nullable|string',
                        'latitude' => 'nullable|numeric',
                        'longitude' => 'nullable|numeric',
                        'north' => 'nullable|numeric',
                        'east' => 'nullable|numeric',
                        'propertyOwnerName' => 'nullable|string',
                        'propertyOwnerEmail' => 'nullable|email',
                        'propertyOwnerphone' => 'nullable|string',
                        'propertyOwnerConsent' => 'nullable|boolean',
                        'propertyOwnerSignature' => 'nullable|string',
                    ]);

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

                    $outdoorApplicationInput = $request->all();
                    $utilMethod = new UtilMethods();
                    $updateData = [];

                    if(!empty($outdoorApplicationInput['applicationPurpose'])) {
                        $updateData['purpose_application'] = $outdoorApplicationInput['applicationPurpose'];
                    }
                    if(!empty($outdoorApplicationInput['typeSign'])) {
                        $updateData['type_sign'] = $outdoorApplicationInput['applicationPurpose'];
                    }
                    if(!empty($outdoorApplicationInput['signageAddress'])) {
                        $updateData['address_proposed_site'] = $outdoorApplicationInput['signageAddress'];
                    }
                    if(!empty($outdoorApplicationInput['lga'])) {
                        $updateData['lga'] = $outdoorApplicationInput['lga'];
                    }
                    if(!empty($outdoorApplicationInput['latitude'])) {
                        $updateData['latitude'] = $outdoorApplicationInput['latitude'];
                    }
                    if(!empty($outdoorApplicationInput['longitude'])) {
                        $updateData['longitude'] = $outdoorApplicationInput['longitude'];
                    }
                    if(!empty($outdoorApplicationInput['north'])) {
                        $updateData['north'] = $outdoorApplicationInput['north'];
                    }
                    if(!empty($outdoorApplicationInput['east'])) {
                        $updateData['east'] = $outdoorApplicationInput['east'];
                    }
                    if(!empty($outdoorApplicationInput['propertyOwnerName'])) {
                        $updateData['property_owner_name'] = $outdoorApplicationInput['propertyOwnerName'];
                    }
                    if(!empty($outdoorApplicationInput['propertyOwnerEmail'])) {
                        $updateData['property_owner_email'] = $outdoorApplicationInput['propertyOwnerEmail'];
                    }
                    if(!empty($outdoorApplicationInput['propertyOwnerphone'])) {
                        $updateData['property_owner_phone'] = $outdoorApplicationInput['propertyOwnerphone'];
                    }
                    if(!empty($outdoorApplicationInput['propertyOwnerConsent'])) {
                        $updateData['property_owner_consent'] = $outdoorApplicationInput['propertyOwnerConsent'];
                    }
                    if(!empty($outdoorApplicationInput['propertyOwnerSignature'])) {
                        $updateData['property_owner_signature'] = $utilMethod->convertBase64toImage($outdoorApplicationInput['propertyOwnerSignature']);
                    }
                    if(!empty($updateData)) {
                        ThirdPartyOutdoor::where('id', $getApplicationObj->id)->update($updateData);
                    }
                    $getResponse = ThirdPartyOutdoor::where('id', $getApplicationObj->id)->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'edit only decertify application'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'you can only edit your application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'this is third party user action'], $this->errorStatusCode);
        }
    }

    public function editOutdoorApplicationDetails(Request $request, $outdoorId) {
        if(Auth::guard('api')->user()->user_type == 'third_party') {
            $getApplicationObj = ThirdPartyOutdoor::find($outdoorId);
            if($getApplicationObj->user_id == (string) Auth::guard('api')->user()->id) {
                if($getApplicationObj->application_certify_status == 'disapproved') {
                    $validate = Validator::make($request->all(), [
                        'structureHeight' => 'nullable|numeric',
                        'lengthSign' => 'nullable|numeric',
                        'breadthSign' => 'nullable|numeric',
                        'setbackDistance' => 'nullable|numeric',
                        'signageFormat' => 'nullable|string|in:portrait,landscape',
                        'numberFaces' => 'nullable|integer',
                        'signLighten' => 'nullable|string|in:none,internal,external,led',
                        'signInteraction' => 'nullable|string|in:none/static,changing,changing,others',
                        'photoMontage' => 'nullable|string',
                        'structuralDrawings' => 'nullable|string'
                    ]);

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

                    $outdoorApplicationInput = $request->all();
                    $utilMethod = new UtilMethods();
                    $updateData = [];

                    if(!empty($outdoorApplicationInput['structureHeight'])) {
                        $updateData['height_structure'] = $outdoorApplicationInput['structureHeight'];
                    }
                    if(!empty($outdoorApplicationInput['lengthSign'])) {
                        $updateData['length_sign'] = $outdoorApplicationInput['lengthSign'];
                    }
                    if(!empty($outdoorApplicationInput['breadthSign'])) {
                        $updateData['breadth_sign'] = $outdoorApplicationInput['breadthSign'];
                    }
                    if(!empty($outdoorApplicationInput['setbackDistance'])) {
                        $updateData['setback_distance'] = $outdoorApplicationInput['setbackDistance'];
                    }
                    if(!empty($outdoorApplicationInput['signageFormat'])) {
                        $updateData['signage_format'] = $outdoorApplicationInput['signageFormat'];
                    }
                    if(!empty($outdoorApplicationInput['numberFaces'])) {
                        $updateData['number_faces'] = $outdoorApplicationInput['numberFaces'];
                    }
                    if(!empty($outdoorApplicationInput['signLighten'])) {
                        $updateData['sign_illumination'] = $outdoorApplicationInput['signLighten'];
                    }
                    if(!empty($outdoorApplicationInput['signInteraction'])) {
                        $updateData['sign_interaction'] = $outdoorApplicationInput['signInteraction'];
                    }
                    if(!empty($outdoorApplicationInput['photoMontage'])) {
                        $updateData['photomontage'] = $utilMethod->convertBase64toImage($outdoorApplicationInput['photoMontage']);
                    }
                    if(!empty($outdoorApplicationInput['structuralDrawings'])) {
                        $updateData['structural_drawing'] = $utilMethod->convertBase64toPdfV2($outdoorApplicationInput['structuralDrawings']);
                    }
                    $updateData['dimension_sign'] = ($outdoorApplicationInput['lengthSign'] * $outdoorApplicationInput['breadthSign']);
                    if(!empty($updateData)) {
                        ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getApplicationObj->id)->update($updateData);
//                        ThirdPartyOutdoor::where('id', $getApplicationObj->id)->update(['application_certify_status' => 'pending']);
                    }
                    $getResponse = ThirdPartyOutdoorSignDetails::where('third_party_outdoor_id', $getApplicationObj->id)->get();
                    return response(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'edit only decertify application'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'you can only edit your application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'this is third party user action'], $this->errorStatusCode);
        }
    }

    public function submitEditButtonForOutdoorSignage($outdoorId) {

        $getOutdoorObj = ThirdPartyOutdoor::find($outdoorId);
        ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['application_certify_status' => 'pending', 'hod_recommedation' => null,
            'md_first_approval' => null, 'rm_second_recommendation' => null, 'hod_second_recommendation' => null, 'legal_recommendation' => null,
            'md_second_approval' => null]);

        $getResponse = ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->with(['thirdPartyOutdoorSignDetails'])->get();
        return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
    }

    public function OutdoorSignageCostRequest(Request $request, $outdoorId) {
        $validate = Validator::make($request->all(), [
            'typeCharges' => 'required|string|in:Off Charge,Expunction',
            'OffchargeLetter' => 'nullable|string',
            'off_charge_picture' => 'nullable|string',
            'off_charge_start' => 'nullable|date',
            'off_charge_end' => 'nullable|date',
            'expunge_date' => 'nullable|date',
        ]);

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

        $input = $request->all();
        $getOutdoorObj = ThirdPartyOutdoor::find($outdoorId);

        if (is_null($getOutdoorObj)) {
            return response()->json(['success' => false, 'data' => 'Outdoor signage not found'], $this->errorStatusCode);
        }

        $checker = ThirdPartyOffchargeAndExpunction::where('third_party_outdoor_id', $getOutdoorObj->id)->get();

        if ($checker->isEmpty() || $checker[0]['md_approval'] == 'approved') {
            $ongoingRequest = ThirdPartyOffchargeAndExpunction::where('third_party_outdoor_id', $getOutdoorObj->id)
                ->whereNull('md_approval')->exists();

            if ($ongoingRequest) {
                return response()->json(['success' => false, 'data' => 'Ongoing request at the moment is Expunge or OffCharge'], $this->errorStatusCode);
            }
            
            $utilMethod = new UtilMethods();

            if ($input['typeCharges'] == 'Off Charge') {
                $thirdpartyOffcharge = new ThirdPartyOffchargeAndExpunction();
                $thirdpartyOffcharge->type_charges = $this->convertOffCharge($input['typeCharges']);
                $thirdpartyOffcharge->letter_offcharge = $utilMethod->convertBase64toPdfV2($input['OffchargeLetter']);
                $thirdpartyOffcharge->off_charge_start = $input['off_charge_start'];
                $thirdpartyOffcharge->off_charge_end = $input['off_charge_end'];
                $thirdpartyOffcharge->off_charge_picture = $utilMethod->convertBase64toImage($input['off_charge_picture']);
                $getOutdoorObj->thirdPartyOffChargeAndExpunction()->save($thirdpartyOffcharge);
                ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['ongoing_request' => 'offcharge']);
                return response()->json(['success' => true, 'data' => 'Off charges request has been sent'], $this->successStatusCode);
            } elseif ($input['typeCharges'] == 'Expunction') {
                $thirdpartyExpung = new ThirdPartyOffchargeAndExpunction();
                $thirdpartyExpung->type_charges = strtolower($input['typeCharges']);
                $thirdpartyExpung->expunge_date = $input['expunge_date'];
                $getOutdoorObj->thirdPartyOffChargeAndExpunction()->save($thirdpartyExpung);
                ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['ongoing_request' => 'expunction']);
                return response()->json(['success' => true, 'data' => 'Expunction request has been sent'], $this->successStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'You have an ongoing request or approval not granted'], $this->errorStatusCode);
        }
    }

    public function outdoorSignageUpgradeandDowngrade(Request $request, $outdoorId) {
        $validate = Validator::make($request->all(), [
            'typeRequest' => 'required|string|in:downgrade,upgrade',
            'new_sign' => 'required|string'
        ]);

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

        $inputRequest = $request->all();
        $utilObj = new UtilMethods();
        $getOutdoorObj = ThirdPartyOutdoor::find($outdoorId);

        $newSignage = $this->formatDesignation($inputRequest['new_sign']);

        if($getOutdoorObj->active_status !== 'expunction' && $getOutdoorObj->ongoing_request == null) {
            $upgradeAndDowngrade = new ThirdPartyUpgradeAndDowngrade();
            $upgradeAndDowngrade->type_charges = $inputRequest['typeRequest'];
            $upgradeAndDowngrade->request_outdoor_signage = $newSignage;
            $upgradeAndDowngrade->payment_id = $utilObj->upgradeOrDowngrade(($inputRequest['typeRequest']));
            $upgradeAndDowngrade->application_id = UtilMethods::outdoorRequestAppId();
            $getOutdoorObj->thirdPartyUpgradeAndDowngrade()->save($upgradeAndDowngrade);
            ThirdPartyOutdoor::where('id', $getOutdoorObj->id)->update(['ongoing_request' => $inputRequest['typeRequest']]);
            $response = ThirdPartyUpgradeAndDowngrade::where('third_party_outdoor_id', $getOutdoorObj->id)->get();
            return response()->json(['success' => true, 'data' => $response], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'similar request has been made on this signage'], $this->errorStatusCode);
        }
    }

    public function outdoorTransferSignageRequest(Request $request, $outdoorId)  {

        $validate = Validator::make($request->all(), [
            'TransferLetter' => 'required|string',
            'NewOwner' => 'required|string',
            // 'TransferOutstanding' => 'required|boolean',
            'StartDate' => 'nullable|date_format:Y-m-d'
        ]);


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

        $transferInput = $request->all();
        $utilObj = new UtilMethods();
        $outdoorObj = ThirdPartyOutdoor::find($outdoorId);
        $startDate = 0;
        if(isset($transferInput['StartDate'])) {
            $startDate = Carbon::parse($transferInput['StartDate'])->format('Y-m-d');
        }

        if ($outdoorObj->active_status !== 'expunction') {
            // if($transferInput['TransferOutstanding'] == true){
            //     $outdoorTransfer = new ThirdPartyOutdoorTransfer();
            //     $outdoorTransfer->letter_transfer = $utilObj->convertBase64toPdfV2($transferInput['TransferLetter']);
            //     $outdoorTransfer->application_id = UtilMethods::outdoorRequestAppId();
            //     $outdoorTransfer->new_owner_id = $transferInput['NewOwner'];
            //     $outdoorTransfer->old_owner_id = (string)Auth::guard('api')->user()->id;
            //     $outdoorTransfer->rm_recommendation = "waiting";
            //     $outdoorTransfer->transfer_outstanding = $transferInput['TransferOutstanding'];
            //     $outdoorTransfer->start_date = $startDate;
            //     $outdoorObj->thirdPartyOutdoorTransfer()->save($outdoorTransfer);
            //     ThirdPartyOutdoor::where('id', $outdoorObj->id)->update(['ongoing_request' => 'transfer']);
            //     $getResponse = ThirdPartyOutdoorTransfer::where('third_party_outdoor_id', $outdoorObj->id)->get();
            //     return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
            // }else{
                $outstandbillamount = AppHistoryThirdPartyOutdoor::where('third_party_outdoor_id', $outdoorObj->id)->latest()->first();
                if($outstandbillamount->balance > 1){
                    return response()->json(['success' => false, 'data' => "Please clear the outstanding bill on this application alone and apply to transfer again, Thanks"], $this->errorStatusCode);
                }else{
                    $outdoorTransfer = new ThirdPartyOutdoorTransfer();
                    $outdoorTransfer->letter_transfer = $utilObj->convertBase64toPdfV2($transferInput['TransferLetter']);
                    $outdoorTransfer->application_id = UtilMethods::outdoorRequestAppId();
                    $outdoorTransfer->new_owner_id = $transferInput['NewOwner'];
                    $outdoorTransfer->old_owner_id = (string)Auth::guard('api')->user()->id;
                    $outdoorTransfer->rm_recommendation = "waiting";
                    // $outdoorTransfer->transfer_outstanding = $transferInput['TransferOutstanding'];
                    $outdoorTransfer->transfer_outstanding = false;
                    $outdoorTransfer->start_date = $startDate;
                    $outdoorObj->thirdPartyOutdoorTransfer()->save($outdoorTransfer);
                    ThirdPartyOutdoor::where('id', $outdoorObj->id)->update(['ongoing_request' => 'transfer']);
                    $getResponse = ThirdPartyOutdoorTransfer::where('third_party_outdoor_id', $outdoorObj->id)->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                }
            // }
            } else {
                return response()->json(['success' => false, 'data' => 'seem to be an ongoing request.'], $this->errorStatusCode);
            }
    }
    
    public function acceptOutdoorTransferSignageRequest($condition, $outdoortransferId)  {

        if ($condition == 'accept') {
                $outdoorTransfer = ThirdPartyOutdoorTransfer::where('id', $outdoortransferId)->update(['rm_recommendation' => null]);
                $outdoor = ThirdPartyOutdoorTransfer::where('id', $outdoortransferId)->first();
                ThirdPartyOutdoor::where('id', $outdoor->third_party_outdoor_id)->update([ 'created_at' => Carbon::now()]);
                return response()->json(['success' => true, 'data' => 'you acknowledge the transfer.'], $this->successStatusCode);
            } elseif ($condition == 'reject') {
                $outdoorTransfer = ThirdPartyOutdoorTransfer::where('id', $outdoortransferId)->first();
                ThirdPartyOutdoorTransfer::where('id', $outdoortransferId)->update(['rm_recommendation' => null]);
                ThirdPartyOutdoor::where('id', $outdoorTransfer->third_party_outdoor_id)->update(['ongoing_request' => null]);
                return response()->json(['success' => false, 'data' => 'you refused the transfer.'], $this->errorStatusCode);
            }
    }
    
    public function getOutdoorTransferSignage()  {
                $outdoorTransfer = ThirdPartyOutdoor::whereHas('ThirdPartyOutdoorTransfer', function($q) {
                                                $q->where('new_owner_id', (string)Auth::guard('api')->user()->id)
                                                  ->where('rm_recommendation', 'waiting');
                                            })->with('thirdPartyOutdoorTransfer')->get()->toArray();
                return response()->json(['success' => true, 'data' => $outdoorTransfer], $this->successStatusCode);
            
    }

    public function getAnnualOutdoorSignageBill() {


    }

    private function convertOffCharge($string) {
        return strtolower(str_replace(' ', '_', trim($string)));
    }

    private function formatDesignation($input) {
        $formatted = strtolower($input);
        $formatted = preg_replace_callback('/(?:^|[\s\/])\w/', function ($matches) {
            return strtoupper($matches[0]);
        }, $formatted);
        $formatted = preg_replace('/led/i', 'LED', $formatted);
        return $formatted;
    }

    public function testFunction($id) {


    }
}
