<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppHistorySmallFormatDetails;
use App\Models\SmallFormatAds;
use App\Models\SmallFormatDetails;
use App\Models\User;
use App\Models\UserAdmin;
use App\Models\SmallFornatAdsApplicationPricing;
use App\Models\EmailContent;
use Illuminate\Support\Facades\Log;
use Exception;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use PHPMailer\PHPMailer\Exception as PHPMailerException;
use PHPMailer\PHPMailer\PHPMailer;

class AdminSmallFormatAdsController extends Controller
{

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

    public function adminSearchSmallFormatAds(Request $request) {

        $keyword = $request->input('search');
        $smallFormatAds = SmallFormatAds::with(['smallFormatDetails']);
        $this->annualBillingsDeptGenerateInvoice();
        if($keyword) {
            $smallFormatAds->where(function ($query) use ($keyword) {
                $query->where('purpose_application', 'like', '%' . $keyword . '%')
                    ->orWhere('address_site', 'like', '%' . $keyword . '%')
                    ->orWhere('lga', 'like', '%' . $keyword . '%')
                    ->orWhere('property_owner_phone', 'like', '%' . $keyword . '%')
                    ->orWhere('property_owner_email', 'like', '%' . $keyword . '%');
            });

            $smallFormatAds->orWhereHas('smallFormatDetails', function ($query) use ($keyword) {
                $query->where('type_signs', 'like', '%' . $keyword . '%')
                    ->orWhere('sign_format', 'like', '%' . $keyword . '%')
                    ->orWhere('sign_site','like', '%' . $keyword . '%')
                    ->orWhere('illumination', 'like', '%' . $keyword . '%');
            });
            
            $smallFormatAds->orWhereHas('user', function ($query) use ($keyword) {
                $query->where('id', 'like', '%' . $keyword . '%');
            });
        }
        
        if ($request->has('lga') && $request->input('lga') !="") {
            $search = $request->input('lga');
            $smallFormatAds->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'));
            $smallFormatAds->whereBetween('created_at', [$startDate, $endDate]);
        }

        $getItems = $smallFormatAds->orderBy('created_at', 'desc')->paginate(20);
        if($getItems->count() > 0) {
            return response()->json(['success' => true, 'data' => $getItems], $this->successStatusCode);
        } else {
            return response()->json(['success' => false, 'data' => 'No items Found'], $this->errorStatusCode);
        }
    }

    public function adminGetOneSmallFormatAds($smallFormatId) {
        try {
            $smallFormatAds = SmallFormatAds::where('id', $smallFormatId)->with(['smallFormatDetails'])->firstOrFail();
            
            $adminNames = [];
            
            
            
            
            if($smallFormatAds['inspection_fee'] == null){
                $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $smallFormatAds->assigned_officer)->where('department', 'Registry')->get()->toArray();
                foreach ($calladmin as $admin){
                    array_push($adminNames, $admin);
                }
                
            }else{
                foreach ($smallFormatAds->smallFormatDetails as $detail) {
                    if($detail['certify_application'] == "pending"){
                        $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $smallFormatAds->assigned_officer)->where('department', 'Registry')->get()->toArray();
                        if($calladmin){
                            foreach ($calladmin as $admin){
                                array_push($adminNames, $admin);
                            }
                        }
                    }elseif($detail['hod_recommendation'] == "pending"){
                        $callsub = UserAdmin::where('id', $smallFormatAds->assigned_officer)->first();
                        $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $callsub->line_manager)->get()->toArray();
                        if($calladmin){
                            foreach ($calladmin as $admin){
                                array_push($adminNames, $admin);
                            }
                        }
                    }elseif($detail['bill_generated'] == "pending"){
                        $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('department', 'Billings')->where('admin_role_id', 2)->orWhere('admin_role_id', 3)->get()->toArray();
                        if($calladmin){
                            foreach ($calladmin as $admin){
                                array_push($adminNames, $admin);
                            }
                        }
                    }elseif($detail['final_bill_generated'] == "pending"){
                        $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('department', 'Billings')->where('admin_role_id', 5)->get()->toArray();
                        if($calladmin){
                            foreach ($calladmin as $admin){
                                array_push($adminNames, $admin);
                            }
                        }
                    }elseif($detail['md_approval'] == "pending"){
                        $calladmin = [
                            'first_name' => 'Managing',
                            'last_name' => 'Director',
                            'department' => 'MD'
                        ];
                        // var_dump($calladmin);die();
                        if($calladmin){
                            array_push($adminNames, $calladmin);
                        }
                    }else{
                        
                    }
                }
            }
            
            $uniqueAdminNames = [];

            foreach ($adminNames as $admin) {
                $fullNameKey = $admin['first_name'] . ' ' . $admin['last_name'];
                
                if (!isset($uniqueAdminNames[$fullNameKey])) {
                    $uniqueAdminNames[$fullNameKey] = $admin;
                }
            }
            
            // Re-index the array if needed
            $adminNames = array_values($uniqueAdminNames);
            
            
            
            return response()->json(['success' => true, 'data' => $smallFormatAds, 'admins' => array_values($adminNames)], $this->successStatusCode);
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'There is no small format ad with the id ' . $smallFormatId], $this->errorStatusCode);
        } catch (Exception $e) {
            return response()->json(['success' => false, 'data' => 'An error occurred'], $this->errorStatusCode);
        }
    }

    public function adminGetOneSmallFormatDetails($smallFormatDetailsId) {
        try {
            $smallFormatDetails = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            return response()->json(['success' => true, 'data' => $smallFormatDetails], $this->successStatusCode);
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'There is no small format details with the id ' . $smallFormatDetailsId], $this->errorStatusCode);
        } catch (Exception $e) {
            return response()->json(['success' => false, 'data' => 'An error occurred'], $this->errorStatusCode);
        }
    }

    public function adminSetInspectionFee(Request $request, $smallFormatId) {

        $validate = Validator::make($request->all(), [
            'inspectionFee' => 'required|numeric|min:10000'
        ]);

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

        try {
            $getSmallFormatObj = SmallFormatAds::findOrFail($smallFormatId);
            if ((string)Auth::user()->id !== $getSmallFormatObj->assigned_officer) {
                return response()->json(['success' => false, 'data' => 'You are not the assigned officer for this application.'], $this->errorStatusCode);
            }

            if (!is_null($getSmallFormatObj->inspection_fee)) {
                return response()->json(['success' => false, 'data' => 'Inspection fee has already been set.'], $this->errorStatusCode);
            }

            if ($getSmallFormatObj->application_pay_status !== 'paid') {
                return response()->json(['success' => false, 'data' => 'application fee has not been paid yet'], $this->errorStatusCode);
            }

            if(!empty($getSmallFormatObj->inspection_fee)) {
                return response()->json(['success' => false, 'data' => 'Inspection fee already set'], $this->errorStatusCode);
            }
            SmallFormatAds::where('id', $getSmallFormatObj->id)->update(['inspection_fee' => $request['inspectionFee']]);
            $response = SmallFormatAds::where('id', $getSmallFormatObj->id)->with(['smallFormatDetails'])->get();
            return response()->json(['success' => true, 'data' => $response], $this->successStatusCode);
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format ad not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' => 'An error occurred while setting the inspection fee.'], $this->errorStatusCode);
        }
    }

    public function adminCertifyApplication($smallFormatId, $smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }

        try {
            $getSmallFormatObj = SmallFormatAds::findOrFail($smallFormatId);

            if ((string)Auth::user()->id !== $getSmallFormatObj->assigned_officer) {
                return response()->json(['success' => false, 'data' => 'You are not the assigned officer for this application.'], $this->errorStatusCode);
            }

            if($getSmallFormatObj->application_pay_status !== 'paid') {
                return response()->json(['success' => false, 'data' => 'application fee is not yet paid'], $this->errorStatusCode);
            }

            if($getSmallFormatObj->application_site_inspection_status !== 'paid') {
                return response()->json(['success' => false, 'data' => 'Inspection fee is not yet paid'], $this->errorStatusCode);
            }

            $getSmallFormatDetailObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailObj->certify_application !== 'pending') {
                return response()->json(['success' => false, 'data' => 'application has been certified already'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

                SmallFormatDetails::where('id', $getSmallFormatDetailObj->id)->update(['certify_application' =>'approved', 'rm_comment' => $bmcomment, 'hod_recommendation' => 'pending']);
                $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailObj->id)->get();
                return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' => 'An error occurred while certifying application'], $this->errorStatusCode);
        }
    }

    public function adminDecertifyApplication($smallFormatId,  $smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }

        try {
            $getSmallFormatObj = SmallFormatAds::findOrFail($smallFormatId);

            if ((string)Auth::user()->id !== $getSmallFormatObj->assigned_officer) {
                return response()->json(['success' => false, 'data' => 'You are not the assigned officer for this application.'], $this->errorStatusCode);
            }

            if($getSmallFormatObj->application_pay_status !== 'paid') {
                return response()->json(['success' => false, 'data' => 'application fee is not yet paid'], $this->errorStatusCode);
            }

            if($getSmallFormatObj->application_site_inspection_status !== 'paid') {
                return response()->json(['success' => false, 'data' => 'Inspection fee is not yet paid'], $this->errorStatusCode);
            }

            $getSmallFormatDetailObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailObj->certify_application !== 'pending') {
                return response()->json(['success' => false, 'data' => 'application has been certified already'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

                SmallFormatDetails::where('id', $getSmallFormatDetailObj->id)->update(['certify_application' =>'disapproved', 'rm_comment' => $bmcomment]);
                $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailObj->id)->get();
                $getResponseone = SmallFormatAds::where('id', $getSmallFormatDetailObj->small_format_ads_id)->get();
                $getApplicant = User::where('id', $getResponseone[0]['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('smallformat_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('smallformat_decline_content');
                    $subject = $emailsubject;
                    $body = $emailcontent. " ". $request['comments'] . " ";
            
                    $templateData = [
                        'body' => $body,
                        'name' => $getApplicant[0]['business_name'],
            
                    ];
                    $templateContent = view('emailtemplate', $templateData)->render();
                    $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
                return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            $message = $e->getMessage();
            Log::error($message);
            return response()->json(['success' => false, 'data' => 'An error occurred while returning application'], $this->errorStatusCode);
        }
    }

    public function registryHeadApproveRecommendation($smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }
        try {
            if(!(Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5)) {
                return response()->json(['success' => false, 'data' => 'you are not an HOD in the registry department'], $this->errorStatusCode);
            }

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailsObj->certify_application == 'pending') {
                return response()->json(['success' => false, 'data' => 'Small Format details has not been certified'], $this->errorStatusCode);
            }

            if($getSmallFormatDetailsObj->hod_recommendation !== 'pending') {
                return response()->json(['success' => false, 'data' => 'hod has already recommend the small format details'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

            SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['hod_recommendation' => 'approved', 'md_approval' => 'pending', 'hod_comment' => $bmcomment]);
                $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->get();
                return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' =>  'An error occurred while hod recommendation application'], $this->errorStatusCode);
        }
    }

    public function registryHeadDisapprovalRecommendation($smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }

        try {
            if(!(Auth::user()->department == 'Registry' && Auth::user()->admin_role_id == 5)) {
                return response()->json(['success' => false, 'data' => 'you are not an HOD in the registry department'], $this->errorStatusCode);
            }

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailsObj->certify_application == 'pending') {
                return response()->json(['success' => false, 'data' => 'Small Format details has not been certified'], $this->errorStatusCode);
            }

            if($getSmallFormatDetailsObj->hod_recommendation !== 'pending') {
                return response()->json(['success' => false, 'data' => 'hod has already recommend the small format details'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

            SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['hod_recommendation' => 'disapproved', 'certify_application' => 'disapproved', 'hod_comment' => $bmcomment]);
            $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->get();
            $getResponseone = SmallFormatAds::where('id', $getSmallFormatDetailsObj->small_format_ads_id)->get();
                $getApplicant = User::where('id', $getResponseone[0]['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('smallformat_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('smallformat_decline_content');
                    $subject = $emailsubject;
                    $body = $emailcontent. " ". $request['comments'] . " ";
            
                    $templateData = [
                        'body' => $body,
                        'name' => $getApplicant[0]['business_name'],
            
                    ];
                    $templateContent = view('emailtemplate', $templateData)->render();
                    $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' =>  'An error occurred while hod recommendation application'], $this->errorStatusCode);
        }
    }

    public function mdSmallFormatDetailsApproval($smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }

        try {
            if(!( Auth::user()->admin_role_id == 6)) {
                return response()->json(['success' => false, 'data' => 'you are not an MD role'], $this->errorStatusCode);
            }

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailsObj->hod_recommendation == 'pending') {
                return response()->json(['success' => false, 'data' => 'Small Format details has not been recommended by hod'], $this->errorStatusCode);
            }

            if($getSmallFormatDetailsObj->md_approval !== 'pending') {
                return response()->json(['success' => false, 'data' => 'md has already approved or disapproved the small format details'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

            SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['md_approval' => 'approved', 'bill_generated' => 'pending', 'md_comment' => $bmcomment]);
            $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->get();
            return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' =>  'An error occurred while hod recommendation application'], $this->errorStatusCode);
        }
    }

    public function mdSmallFormatDetailsDisapproval($smallFormatDetailsId, Request $request) {
        $validate = Validator::make($request->all(), [
                'comments' => 'nullable|string|max:255',
                'reports_from_branchmanger' => 'required|string|max:255',
            ]);
    
            if($validate->fails()) {
                return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            }

        try {
            if(!( Auth::user()->admin_role_id == 6)) {
                return response()->json(['success' => false, 'data' => 'you are not an MD role'], $this->errorStatusCode);
            }

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);
            if ($getSmallFormatDetailsObj->hod_recommendation == 'pending') {
                return response()->json(['success' => false, 'data' => 'Small Format details has not been recommended by hod'], $this->errorStatusCode);
            }

            if($getSmallFormatDetailsObj->md_approval !== 'pending') {
                return response()->json(['success' => false, 'data' => 'md has already approved or disapproved the small format details'], $this->errorStatusCode);
            }
            
            if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

            SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['md_approval' => 'disapproved', 'md_comment' => $bmcomment]);
            $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->get();
            $getResponseone = SmallFormatAds::where('id', $getSmallFormatDetailsObj->small_format_ads_id)->get();
                $getApplicant = User::where('id', $getResponseone[0]['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('smallformat_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('smallformat_decline_content');
                    $subject = $emailsubject;
                    $body = $emailcontent. " ". $request['comments'] . " ";
            
                    $templateData = [
                        'body' => $body,
                        'name' => $getApplicant[0]['business_name'],
            
                    ];
                    $templateContent = view('emailtemplate', $templateData)->render();
                    $this->composeEmailV2($subject, $getApplicantEmail,  $templateContent);
            return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);

        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' =>  'An error occurred while hod recommendation application'], $this->errorStatusCode);
        }
    }

    public function billingsDeptGenerateInvoice(Request $request, $smallFormatDetailsId) {
        try {
            if(!(Auth::user()->department == 'Billings') && (Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 5)) {
                return response()->json(['success' => false, 'data' => 'you are not a Billings role'], $this->errorStatusCode);
            }

            $validate = Validator::make($request->all(), [
                'adsPrice' => 'required|numeric',
                'annualPrice' => 'required|numeric'
            ]);

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

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($smallFormatDetailsId);

            if($getSmallFormatDetailsObj->md_approval !== 'approved') {
                return response()->json(['success' => false, 'data' => 'small format details has not been approved'], $this->errorStatusCode);
            }
            
            if(Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3){
                if($getSmallFormatDetailsObj->bill_generated == 'generated') {
                    return response()->json(['success' => false, 'data' => 'Bill has already been generated for the small format details'], $this->errorStatusCode);
                }
    
                SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['final_bill_generated' => 'pending', 'bill_generated' => 'generated', 'ads_price' => $request['adsPrice'],
                    'annual_price' => $request['annualPrice'], 'adprice_payment_status' => 'not_paid']);
            } elseif(Auth::user()->admin_role_id == 5){
                if($getSmallFormatDetailsObj->final_bill_generated == 'generated') {
                    return response()->json(['success' => false, 'data' => 'Bill has already been generated for the small format details'], $this->errorStatusCode);
                }
    
                SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['final_bill_generated' => 'approved', 'ads_price' => $request['adsPrice'],
                    'annual_price' => $request['annualPrice'], 'adprice_payment_status' => 'not_paid']);
            }
            
                
            $appHistory = new AppHistorySmallFormatDetails();
            $appHistory->purpose_application = $getSmallFormatDetailsObj->type_signs;
            $appHistory->ads_price = $request['adsPrice'];
            $appHistory->annual_adsprice = $request['annualPrice'];
            $appHistory->balance = $request['adsPrice'];
            $getSmallFormatDetailsObj->appHistorySmallFormatDetails()->save($appHistory);
            $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->with(['appHistorySmallFormatDetails'])->get();
            return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
        } catch (ModelNotFoundException $e) {
            return response()->json(['success' => false, 'data' => 'Small Format details not found.'], $this->errorStatusCode);
        } catch (\Exception $e) {
            return response()->json(['success' => false, 'data' =>  'An error occurred while hod recommendation application'], $this->errorStatusCode);
        }
    }
    
    public static function annualBillingsDeptGenerateInvoice() {
            // if(!(Auth::user()->department == 'Billings') && (Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3 || Auth::user()->admin_role_id == 5)) {
            //     return response()->json(['success' => false, 'data' => 'you are not a Billings role'], $this->errorStatusCode);
            // }

            // $validate = Validator::make($request->all(), [
            //     'adsPrice' => 'required|numeric',
            //     'annualPrice' => 'required|numeric'
            // ]);

            // if($validate->fails()) {
            //     return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
            // }
            
            $getAllSmallFormatDetailsObj = SmallFormatDetails::where('final_bill_generated', 'approved')->get();
            $getAllSmallFormatDetailsObjcount = count($getAllSmallFormatDetailsObj) - 1;
            
            for ($i = 0; $i <= $getAllSmallFormatDetailsObjcount; $i++) {
            
            $year = Carbon::now()->year;
            if((int)$getAllSmallFormatDetailsObj[$i]['permit_year'] < (int)$year){

            $getSmallFormatDetailsObj = SmallFormatDetails::findOrFail($getAllSmallFormatDetailsObj[$i]['id']);
            
            $getAppHistory = AppHistorySmallFormatDetails::where('small_format_details_id', $getSmallFormatDetailsObj->id)->get()->last();
            $getAdsPrice = $getAppHistory->balance;
            
            $getSmallFormatDetailsObj->permit_year = $year;
            $getSmallFormatDetailsObj->save();

            // if($getSmallFormatDetailsObj->md_approval !== 'approved') {
            //     return response()->json(['success' => false, 'data' => 'small format details has not been approved'], $this->errorStatusCode);
            // }
            
            // if(Auth::user()->admin_role_id  == 2 || Auth::user()->admin_role_id == 3){
            //     if($getSmallFormatDetailsObj->bill_generated == 'generated') {
            //         return response()->json(['success' => false, 'data' => 'Bill has already been generated for the small format details'], $this->errorStatusCode);
            //     }
    
            //     SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['final_bill_generated' => 'pending', 'bill_generated' => 'generated', 'ads_price' => $request['adsPrice'],
            //         'annual_price' => $request['annualPrice'], 'adprice_payment_status' => 'not_paid']);
            // } elseif(Auth::user()->admin_role_id == 5){
            //     if($getSmallFormatDetailsObj->final_bill_generated == 'generated') {
            //         return response()->json(['success' => false, 'data' => 'Bill has already been generated for the small format details'], $this->errorStatusCode);
            //     }
    
            //     SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->update(['final_bill_generated' => 'approved', 'ads_price' => $request['adsPrice'],
            //         'annual_price' => $request['annualPrice'], 'adprice_payment_status' => 'not_paid']);
            // }
            
                
            $appHistory = new AppHistorySmallFormatDetails();
            $appHistory->purpose_application = $getSmallFormatDetailsObj->type_signs;
            $appHistory->ads_price = $getSmallFormatDetailsObj->annual_price;
            $appHistory->annual_adsprice = $getSmallFormatDetailsObj->annual_price;
            $appHistory->balance = $getSmallFormatDetailsObj->annual_price + $getAdsPrice;
            $getSmallFormatDetailsObj->appHistorySmallFormatDetails()->save($appHistory);
            $getResponse = SmallFormatDetails::where('id', $getSmallFormatDetailsObj->id)->with(['appHistorySmallFormatDetails'])->get();
            // return response()->json(['success' => true, 'data' => $getResponse], $this->successStatusCode);
            
            }
            
            }
        
    }
    
    public function getSmallFormatApplicationPricing(){
        
        $getPrices = SmallFornatAdsApplicationPricing::all();
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function updateSmallFormatApplicationPricing(Request $request, $id) {
        
        $validator = Validator::make($request->all(), [
            'app_price' => ['required', 'numeric', 'min:0'],
        ]);
    
        // Find the record by ID
        $pricing = SmallFornatAdsApplicationPricing::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);
    }
    
    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 (PHPMailerException $exception) {
//            error_log('Email delivery failed: ' . $mail->ErrorInfo);
            $message = $exception->getMessage();
            Log::error($message);
            return true;
        } catch (\Exception $exception) {
//            error_log('Email delivery failed: ' . $mail->ErrorInfo);
            $message = $exception->getMessage();
            Log::error($message);
            return true;
        }
    }
    
    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;
        }
    }

}
