<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Util\UtilMethods;
use App\Models\KycThirdParty;
use App\Models\KycThirdPartyScore;
use App\Models\KycThirdpartyReceipts;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\KycThirdPartyPricing;
use App\Models\EmailContent;
use Barryvdh\DomPDF\Facade\Pdf;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\File;

class AdminKycThirdPartyController extends Controller  {


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

    public function getAllThirdPartyExpression(Request $request) {

//        if(Auth::user()->admin_role_id == 12) {
            $keyword = $request->input('search');

            $getAllexpression = KycThirdParty::with(['user']);

            if ($keyword) {
                $getAllexpression->where(function ($query) use ($keyword) {
                    $query->where('company_name', 'like', '%' . $keyword . '%')
                        ->orWhere('office_address', 'like', '%' . $keyword . '%')
                        ->orWhere('nearest_bustop', 'like', '%' . $keyword . '%')
                        ->orWhere('lga', 'like', '%' . $keyword . '%');
                });

                $getAllexpression->orWhereHas('user', function ($query) use ($keyword) {
                    $query->where('first_name', 'like', '%' . $keyword . '%')
                        ->orWhere('last_name', 'like', '%' . $keyword . '%')
                        ->orWhere('email', 'like', '%' . $keyword . '%')
                        ->orWhere('phone_number', 'like', '%' . $keyword . '%')
                        ->orWhere('id', 'like', '%' . $keyword . '%');
                });
            }
            
            if ($request->has('lga') && $request->input('lga') !="") {
                $search = $request->input('lga');
                $getAllexpression->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'));
                $getAllexpression->whereBetween('created_at', [$startDate, $endDate]);
            }
            $getItems = $getAllexpression->orderBy('created_at', 'desc')->paginate(20);
            return response()->json(['success' => true, 'data' => $getItems], $this->successStatusCode);
//        } else {
//            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
//        }
    }

    public function getThirdPartyExpression($kycThirdPartyId) {

        $getKycDetails = KycThirdParty::where('id', $kycThirdPartyId)->with(['kycThirdPartyScore'])->get();
        
        $adminNames = [];
        
        
        if($getKycDetails[0]['operation_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'Operations')->where('admin_role_id', 2)->orWhere('admin_role_id', 3)->get()->toArray();
            if($calladmin){
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
            }
        }elseif($getKycDetails[0]['hod_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'Operations')->where('admin_role_id', 5)->get()->toArray();
            if($calladmin){
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
            }
        }elseif($getKycDetails[0]['md_status'] == "pending"){
            $calladmin = [
                            'first_name' => 'Managing',
                            'last_name' => 'Director',
                            'department' => 'MD'
                        ];
                        
            if($calladmin){
                array_push($adminNames, $calladmin);
            }
        }
        
        if($getKycDetails[0]['registry_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('department', 'Registry')->where('admin_role_id', 2)->orWhere('admin_role_id', 3)->get()->toArray();
            if($calladmin){
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
            }
        }
        
        if($getKycDetails[0]['account_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('admin_role_id', 8)->get()->toArray();
            if($calladmin){
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
            }
        }
        
        if($getKycDetails[0]['legal_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name')->where('admin_role_id', 9)->get()->toArray();
            if($calladmin){
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
            }
        }
        

        if(count($getKycDetails) == 0 ) {
            return response()->json(['success' => false, 'data' => 'There is no kyc details with the kyc id'], $this->errorStatusCode);
        } else {
            return response()->json(['success' => true, 'data' => $getKycDetails, 'admins' => $adminNames], $this->successStatusCode);
        }
    }

    public function operationCertifyApplication($kycThirdPartyId) {

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

            $getKycObj = KycThirdParty::find($kycThirdPartyId);

            if($getKycObj->operation_status == 'pending') {
                $operationApproval = KycThirdParty::where('id', $kycThirdPartyId)->update(['operation_status' => 'approved', 'legal_status' => 'pending',
                    'account_status' => 'pending', 'registry_status' => 'pending']);
                $getData = KycThirdParty::where('id', $kycThirdPartyId)->get();
                return response()->json(['success' => true, 'data' => $getData], $this->successStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function operationDecertifyApplication($kycThirdPartyId) {

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

            $getKycObj = KycThirdParty::find($kycThirdPartyId);
            if($getKycObj->operation_status == 'pending') {
                $operationDisapproval = KycThirdParty::where('id', $kycThirdPartyId)->update(['operation_status' => 'disapproved']);
                $getData = KycThirdParty::where('id', $kycThirdPartyId)->get();
                return response()->json(['success' => true, 'data' => $getData], $this->successStatusCode);
            } else {
                return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function legalScoreExpression(Request $request, $kycThirdPartyId) {

        $validate = Validator::make($request->all(), [
            'arcon_score' => 'required|numeric|max:8',
            'cac_score' => 'required|numeric|max:8',
            'company_profile' => 'required|numeric|max:8',
        ]);

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

        if(Auth::user()->admin_role_id == 9) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if($getKycDetails->operation_status == 'approved') {
                if($getKycDetails->legal_status == 'pending') {
                    $kycScore = KycThirdPartyScore::updateOrCreate(['kyc_third_party_id' => $getKycDetails->id], [
                        'arcon_score' => $request['arcon_score'],
                        'cac_score' => $request['cac_score'],
                        'company_profile_score' => $request['company_profile']
                    ]);
                    $grandTotal = $request['arcon_score'] + $request['cac_score'] + $request['company_profile'];
                    KycThirdParty::where('id', $getKycDetails->id)->update(['legal_score' => $grandTotal, 'legal_status' => 'approved']);

                    $getNewKycDetails = KycThirdParty::find($kycThirdPartyId);
                    if($getNewKycDetails->account_status == 'approved' &&  $getNewKycDetails->registry_status == 'approved') {
                        KycThirdParty::where('id', $getNewKycDetails->id)->update(['hod_status' => 'pending']);
                    }
                    $getResponse = KycThirdParty::where('id', $getKycDetails->id)->with(['kycThirdPartyScore'])->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
                }
            }else {
                return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
            }
    }

    public function legalDisapprovalExpression($kycThirdPartyId) {

        if(Auth::user()->admin_role_id == 9) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if($getKycDetails->operation_status = 'approved') {
                if ($getKycDetails->legal_status == 'pending') {
                    $legalDisapproval = KycThirdParty::where('id', $kycThirdPartyId)->update(['legal_status' => 'disapproved', 'legal_score' => 0]);
                    $getData = KycThirdParty::where('id', $kycThirdPartyId)->get();
                    return response()->json(['success' => true, 'data' => $getData], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function accountScoreExpression(Request $request, $kycThirdPartyId) {

        $validate = Validator::make($request->all(), [
            'return_capital' => 'required|integer',
            'current_asset_ratio' => 'required|numeric',
            'acid_test_ratio' => 'required|numeric',
            'earning_share' => 'required|numeric',
            'number_shares' => 'required|integer',
            'asset_ratio' => 'required|integer',
            'total_asset' => 'required|integer',
            'evidence_good' => 'required|integer',
//            'tax_clearance' => 'required|integer',
//            'business_plan' => 'required|integer',
//            'reference_letter' => 'required|integer',
        ]);

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

        if (Auth::user()->admin_role_id == 8) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if ($getKycDetails->operation_status == 'approved') {
                if ($getKycDetails->account_status == 'pending' && $getKycDetails->company_type == 'existing company') {

                    $returnCapitalScore = ($request['return_capital'] / 10) * 3;
                    $currentAssetRatio = ($request['current_asset_ratio'] / 1) * 6;
                    $acidTestRatio = ($request['acid_test_ratio'] / 1) * 10;
                    $earnPerShare = ($request['earning_share'] / $request['number_shares']) * 3;
                    $assetRatio = ($request['asset_ratio'] / $request['total_asset']) * 3;
                    $evidence = ($request['evidence_good'] / 25000000) * 1;
                    $referenceLetter = 0;
                    $temptax = 0;
                    $tempBusiness = 0;


                    $kycScore = KycThirdPartyScore::updateOrCreate(
                        ['kyc_third_party_id' => $getKycDetails->id], // Assuming 'kyc_third_party_id' is the foreign key
                        [
                            'return_capital' => $returnCapitalScore,
                            'current_asset_ratio' => $currentAssetRatio,
                            'acid_test_ratio' => $acidTestRatio,
                            'earning_share' => $earnPerShare,
                            'asset_ratio' => $assetRatio,
                            'evidence_finance' => $evidence,
                            'tax_clearance_score' => $getKycDetails->tax_clearance ? 1 : 0,
                            'business_plan_score' => $getKycDetails->business_plan ? 1 : 0,
                            'reference_letter_score' => ($getKycDetails->bank_or_corporate_reference ? 1 : 0) + ($getKycDetails->bank_or_corporate_reference_2 ? 1 : 0),
                        ]
                    );

                    $grandTotal = $returnCapitalScore + $currentAssetRatio + $acidTestRatio + $earnPerShare + $assetRatio + $evidence +
                        ($getKycDetails->bank_or_corporate_reference ? 1 : 0) + ($getKycDetails->bank_or_corporate_reference_2 ? 1 : 0)
                        + $temptax + $tempBusiness;

                    KycThirdParty::where('id', $kycThirdPartyId)->update(['account_score' => $grandTotal, 'account_status' => 'approved']);
                    $getNewKycDetails = KycThirdParty::find($kycThirdPartyId);
                    if($getNewKycDetails->legal_status == 'approved' &&  $getNewKycDetails->registry_status == 'approved') {
                        KycThirdParty::where('id', $getNewKycDetails->id)->update(['hod_status' => 'pending']);
                    }
                    $getResponse = KycThirdParty::where('id', $kycThirdPartyId)->with(['kycThirdPartyScore'])->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else if ($getKycDetails->account_status == 'pending' && $getKycDetails->company_type == 'new company') {

                    $evidence = ($request['evidence_good'] / 25000000) * 5;
                    $kycScore = KycThirdPartyScore::updateOrCreate(
                        ['kyc_third_party_id' => $getKycDetails->id], // Assuming 'kyc_third_party_id' is the foreign key
                        [
                            'evidence_finance' => $evidence,
                            'tax_clearance_score' => $getKycDetails->tax_clearance ? 5 : 0,
                            'business_plan_score' => $getKycDetails->business_plan ? 10 : 0,
                            'reference_letter_score' => ($getKycDetails->bank_or_corporate_reference ? 2.5 : 0) + ($getKycDetails->bank_or_corporate_reference_2 ? 2.5 : 0),
                            'bank_statement' => $getKycDetails->director_bank_statement ? 5 : 0,
                        ]
                    );

                    $grandTotal = $evidence +
                        ($getKycDetails->tax_clearance ? 5 : 0) +
                        ($getKycDetails->business_plan ? 10 : 0) +
                        (($getKycDetails->bank_or_corporate_reference ? 2.5 : 0) + ($getKycDetails->bank_or_corporate_reference_2 ? 2.5 : 0)) +
                        ($getKycDetails->director_bank_statement ? 5 : 0);

                    KycThirdParty::where('id', $kycThirdPartyId)->update(['account_score' => $grandTotal, 'account_status' => 'approved']);
                    $getNewKycDetails = KycThirdParty::find($kycThirdPartyId);
                    if($getNewKycDetails->legal_status == 'approved' &&  $getNewKycDetails->registry_status == 'approved') {
                        KycThirdParty::where('id', $getNewKycDetails->id)->update(['hod_status' => 'pending']);
                    }
                    $getResponse = KycThirdParty::where('id', $kycThirdPartyId)->with(['kycThirdPartyScore'])->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
            }
        }else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function accountDisapprovalExpression($kycThirdPartyId) {

        if(Auth::user()->admin_role_id == 8) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if($getKycDetails->operation_status == 'approved') {
                if ($getKycDetails->account_status == 'pending') {
                    $accountDisapproval = KycThirdParty::where('id', $kycThirdPartyId)->update(['account_status' => 'disapproved', 'account_score' => 0]);
                    $getData = KycThirdParty::where('id', $kycThirdPartyId)->get();
                    return response()->json(['success' => true, 'data' => $getData], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
            }
        }else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function registryScoreExpression(Request $request, $kycThirdPartyId) {

        $validate = Validator::make($request->all(), [
            'companyprofile_score' => 'required|numeric|max:10',
            'maintanance_score' => 'required|numeric|max:5',
            'pastproject_score' => 'required|numeric|max:5',
            'preliminarydesign_score' => 'required|numeric|max:10',
            'designInnovation_score' => 'required|numeric|max:5',
            'companyInfo_score' => 'required|numeric|max:5'
        ]);

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

        if(Auth::user()->department == 'Registry' && Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if($getKycDetails->operation_status == 'approved') {
                if($getKycDetails->registry_status == 'pending') {
                    $registryScore = KycThirdPartyScore::updateOrCreate(['kyc_third_party_id' => $getKycDetails->id],[
                        'registry_company_profile' => $request['companyprofile_score'],
                        'maintainance_plan' => $request['maintanance_score'],
                        'pastproject_score' => $request['pastproject_score'],
                        'preliminary_score' => $request['preliminarydesign_score'],
                        'design_innovation_score' => $request['designInnovation_score'],
                         'company_info_score' => $request['company_info_score']
                    ]);
                $grandTotal = $request['companyprofile_score'] + $request['maintanance_score'] +  $request['pastproject_score']
                    + $request['preliminarydesign_score']  + $request['designInnovation_score'] + $request['company_info_score'];
                KycThirdParty::where('id', $getKycDetails->id)->update(['registry_score' => $grandTotal, 'registry_status' => 'approved']); 
                    $getNewKycDetails = KycThirdParty::find($kycThirdPartyId);
                  
                    if($getNewKycDetails->account_status === 'approved' &&  $getNewKycDetails->legal_status === 'approved') {
                        KycThirdParty::where('id', $getNewKycDetails->id)->update(['hod_status' => 'pending']);
                    }
                $getResponse = KycThirdParty::where('id', $getKycDetails->id)->with(['kycThirdPartyScore'])->get();
                return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
            } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return  response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function registryDisapprovalExpression($kycThirdPartyId) {

        if(Auth::user()->department == 'Registry' && Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3) {
            $getKycDetails = KycThirdParty::find($kycThirdPartyId);
            if($getKycDetails->operation_status == 'approved') {
                if ($getKycDetails->registry_status == 'pending') {
                    $registryDisapproval = KycThirdParty::where('id', $kycThirdPartyId)->update(['registry_status' => 'disapproved', 'registry_score' => 0]);
                    $getData = KycThirdParty::where('id', $kycThirdPartyId)->get();
                    return response()->json(['success' => true, 'data' => $getData], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'application has been treated'], $this->errorStatusCode);
                }
            } else {
                return  response()->json(['success' => false, 'data' => 'Operation has not certify application'], $this->errorStatusCode);
            }
        }else {
            return response()->json(['success' => false, 'data' => 'can not taken this particular action'], $this->errorStatusCode);
        }
    }

    public function hodapprovalExpression($kycThirdPartyId) {

        $user =  Auth::user();
        if($user->admin_role_id == 5 && $user->department == 'Operations') {

            $getKycObj =  KycThirdParty::find($kycThirdPartyId);
            if($getKycObj->legal_status == 'approved' && $getKycObj->account_status == 'approved' && $getKycObj->registry_status == 'approved') {
                 if($getKycObj->hod_status == 'pending') {

                     KycThirdParty::where('id', $getKycObj->id)->update(['hod_status' => 'approved']);
                    if($getKycObj->ref_no == null) {
                        $getRefNo = UtilMethods::thirdPartyFirstApprovalRefno();
                        KycThirdParty::where('id', $getKycObj->id)->update(['ref_no' => $getRefNo]);
                    } else {
                        $getRefNo = $getKycObj->ref_no;
                    }
                    $data = [
                       'date' => Carbon::parse($getKycObj->updated_at)->format('jS F, Y'),
                        'companyName' => $getKycObj->company_name,
                        'address' => $getKycObj->office_address,
                        'nearestBustop' => $getKycObj->nearest_bustop,
                        'lga' => $getKycObj->lga,
                        'refno' => $getKycObj->ref_no
                    ];

                    $pdf = Pdf::loadView('firstapprovalthirdpartyeoi', compact('data'));
                    $fileObj = $pdf->download('firstapprovalthirdpartyeoi.pdf');
                    $userDetails = User::find($getKycObj->user_id);
                    
                    $emailcontent = EmailContent::getContent('kyc_eoi_approve_content');
                    $body = $emailcontent;
                    $templateData = [
                        'body' => $body,
                        'name' => $getKycObj->company_name
                    ];
                    $templateContent = view('hodeoitemplate', $templateData)->render();
                    UtilMethods::thirdPartyFirstApprovalHodEmail($userDetails->email, $templateContent, $fileObj);
                    
                    
                    $kcf = Pdf::loadView('firstapprovalthirdpartyeoi',compact('data'));
                    $pdfContent = $kcf->output();
                    $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
                    $relativePath = 'invoices/' . $filename;
                    $savePath = public_path($relativePath); // Full path to /public/invoices/
                             
                    if (!File::exists(public_path('invoices'))) {
                        File::makeDirectory(public_path('invoices'), 0755, true);
                    }
                    file_put_contents($savePath, $pdfContent);
                    $fileUrl = config('app.url') . '/public/' . $relativePath;
                    $adnewrec = new KycThirdpartyReceipts();
                    $adnewrec->link = $fileUrl;
                    $adnewrec->type = "Provisional Letter";
                    //  $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
                    $getKycObj->kycthirdpartyreceipts()->save($adnewrec);
                    
                    
                    return response()->json(['success' => true, 'data' => 'Application approved and email sent'], $this->successStatusCode);
                 } else {
                     return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                 }
            } else {
                return response()->json(['success' => false, 'data' => 'The application has not been certified by the other parties'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'You do not have the required privilege to take this action.'], $this->errorStatusCode);
        }
    }

    public function hoddisapprovalExpression($kycThirdPartyId) {

        $user =Auth::user();
        if($user->admin_role_id == 5 && $user->department == 'Operations') {
            $getKycObj =  KycThirdParty::find($kycThirdPartyId);
            if($getKycObj->legal_status == 'approved' && $getKycObj->account_status == 'approved' && $getKycObj->registry_status == 'approved') {
                if($getKycObj->hod_status == null) {
                    KycThirdParty::where('id', $getKycObj->id)->update(['hod_status' => 'disapproved']);
                    $getResponse = KycThirdParty::where('id', $getKycObj->id)->with(['kycThirdPartyScore'])->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'The application has not been certified by the other parties'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'You do not have the required privilege to take this action.'], $this->errorStatusCode);
        }
    }

    public function mdapprovalExpression($kycThirdPartyId) {

        $user  = Auth::user();
        if($user->admin_role_id == 6) {
            $getKycObj = KycThirdParty::find($kycThirdPartyId);
            if($getKycObj->hod_status == 'approved') {
                if($getKycObj->md_status == 'pending') {
                    KycThirdParty::where('id', $getKycObj->id)->update(['md_status' => 'approved', 'kyc_active' => true]);
                    User::where('id', $getKycObj->user_id)->update(['kyc_status' => true]);
                    if($getKycObj->ref_no == null) {
                        $getRefNo = UtilMethods::thirdPartyFirstApprovalRefno();
                        KycThirdParty::where('id', $getKycObj->id)->update(['ref_no' => $getRefNo]);
                    }
                    $data = [
                        'date' => Carbon::parse($getKycObj->updated_at)->format('jS F, Y'),
                        'companyName' => $getKycObj->company_name,
                        'address' => $getKycObj->office_address,
                        'nearestBustop' => $getKycObj->nearest_bustop,
                        'lga' => $getKycObj->lga,
                        'refno' => $getKycObj->ref_no
                    ];

                    $pdf = Pdf::loadView('secondapprovalthirdpartyeoi', compact('data'));
                    $fileObj = $pdf->download('secondapprovalthirdpartyeoi.pdf');
                    $userDetails = User::find($getKycObj->user_id);
                    $emailcontent = EmailContent::getContent('kyc_eoi_second_approve_content');
                    $body = $emailcontent;
                    $templateData = [
                        'body' => $body,
                        'name' => $getKycObj->company_name
                    ];
                    $templateContent = view('hodeoitemplate', $templateData)->render();
                    UtilMethods::thirdPartySecondApprovalMdEmail($userDetails->email, $templateContent, $fileObj);
                    
                    $pdf = Pdf::loadView('secondapprovalthirdpartyeoi', compact('data'));
                    $pdfContent = $pdf->output();
                    $filename = 'ApprovalLetter_' . now()->format('YmdHis') . '.pdf';
                    $relativePath = 'invoices/' . $filename;
                    $savePath = public_path($relativePath); // Full path to /public/invoices/
                             
                    if (!File::exists(public_path('invoices'))) {
                        File::makeDirectory(public_path('invoices'), 0755, true);
                    }
                    file_put_contents($savePath, $pdfContent);
                    $fileUrl = config('app.url') . '/public/' . $relativePath;
                    $adnewrec = new KycThirdpartyReceipts();
                    $adnewrec->link = $fileUrl;
                    $adnewrec->type = "Approval Letter";
                    //  $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
                    $getKycObj->kycthirdpartyreceipts()->save($adnewrec);
                    
                    
                    return response()->json(['success' => true, 'data' => 'Application approved and email sent'], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'The application has not been certified by the other parties'], $this->errorStatusCode);
            }
        }else {
            return response()->json(['success' => false, 'data' => 'You do not have the required privilege to take this action.'], $this->errorStatusCode);
        }
    }

    public function mddisapprovalExpression($kycThirdPartyId) {

        $user  = Auth::user();
        $getKycObj =  KycThirdParty::find($kycThirdPartyId);
        if($user->admin_role_id == 6) {
            if($getKycObj->hod_status == 'approved') {
                if($getKycObj->md_status == 'pending') {
                    KycThirdParty::where('id', $getKycObj->id)->update(['md_status'=> 'disapproved', 'hod_status' => 'disapproved',
                        'registry_status' => 'disapproved', 'account_status' => 'disapproved', 'legal_status' => 'disapproved', 'operation_status' => 'disapproved']);

                    $getResponse = KycThirdParty::where('id', $getKycObj->id)->with('kycThirdPartyScore')->get();
                    return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'Application has been treated'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'The application has not been certified by the other parties'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' => 'You do not have the required privilege to take this action.'], $this->errorStatusCode);
        }
    }

    public function getThirdPartyCertifcate($kycThidPartyId) {

        $getKycObj = KycThirdParty::find($kycThidPartyId);
        $lastDayOfYear = Carbon::parse($getKycObj->updated_at)->endOfYear()->format('d-m-Y');

        if($getKycObj->md_status == 'approved') {

            $data = [
                 'date' => Carbon::parse($getKycObj->updated_at)->format('d-m-Y'),
                'refno' => $getKycObj->ref_no,
                 'companyName' => $getKycObj->company_name,
                'endDate' => $lastDayOfYear
             ];
             $pdf = Pdf::loadView('certificate',compact('data'));
             $fileObj =  $pdf->download('certificate.pdf');

            $userDetails = User::find($getKycObj->user_id);
            $emailcontent = EmailContent::getContent('kyc_eoi_certificate_content');
            $body = $emailcontent;
            $templateData = [
                'body' => $body,
                'name' => $getKycObj->company_name
            ];
            $templateContent = view('hodeoitemplate', $templateData)->render();
            UtilMethods::thirdPartyCertificationEmail($userDetails->email, $templateContent, $fileObj);
            
            $kcf = Pdf::loadView('certificate',compact('data'));
            $pdfContent = $kcf->output();
            $filename = 'EOICertificate_' . now()->format('YmdHis') . '.pdf';
            $relativePath = 'invoices/' . $filename;
            $savePath = public_path($relativePath); // Full path to /public/invoices/
                             
            if (!File::exists(public_path('invoices'))) {
                File::makeDirectory(public_path('invoices'), 0755, true);
            }
            file_put_contents($savePath, $pdfContent);
            $fileUrl = config('app.url') . '/public/' . $relativePath;
            $adnewrec = new KycThirdpartyReceipts();
            $adnewrec->link = $fileUrl;
            $adnewrec->type = "Outdoor Ceritficate";
            //  $tosaveoutd = ThirdPartyOutdoor::find($getOutDoorObj[$i]['id']);
            $getKycObj->kycthirdpartyreceipts()->save($adnewrec);
            
            
            return response()->json(['success' => true, 'data' => 'Application approved and email sent'], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'application has not been approved yet'], $this->errorStatusCode);
        }
    }
    
    public function getKycformatDownloadables($id) {
        $user = Auth::user();
        $check = KycThirdpartyReceipts::where('kyc_third_party_id', $id)->exists();
        if($check){
            $getreceipts = KycThirdpartyReceipts::where('kyc_third_party_id', $id)->get()->toArray();
        
            return response()->json(['data' => $getreceipts], 200);
        }else{
            return response()->json(['data' => 'No Downloadables Yet!'], 422);
        }
        
    }
    
    public function getKycThirdPartyPricing(){
        
        $getPrices = KycThirdPartyPricing::all();
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function updateKycThirdPartyPricing(Request $request, $id) {
        
        $validator = Validator::make($request->all(), [
            'eoi_price' => ['required', 'numeric', 'min:0'],
            'permit_fee' => ['required', 'numeric', 'min:0'],
            'renewal_fee' => ['required', 'numeric', 'min:0'],
        ]);
    
        // Find the record by ID
        $pricing = KycThirdPartyPricing::findOrFail($id);
        
        if($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], $this->errorStatusCode);
        }
        
        $validated = $validator->validated();
    
        $pricing->update($validated);
    
        return response()->json(['success' => true, 'data' => 'Pricing record updated successfully'], 200);
    }
}
