<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\AppHistoryFirstPartyTemporaryAds;
use App\Models\FirstPartyTemporaryAds;
use App\Models\FirstPartyTemporaryAdsDetails;
use App\Models\UserAdmin;
use App\Models\User;
use App\Models\FirstPartyTemporaryReceipts;
use App\Models\TemporaryAdsPricing;
use App\Models\TemporaryAdsApplicationPricing;
use App\Models\EmailContent;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;

class AdminFirstPartyTemporaryAdsController extends Controller {

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

    public function adminGetAndSearchFirstPartyTemporaryAds(Request $request) {

        $keyword = $request->input('search');
        $getAllTemporaryAds = FirstPartyTemporaryAds::with(['firstPartyTemporaryAdsDetails']);

        if($keyword) {
            $getAllTemporaryAds->where(function ($query) use ($keyword) {
                $query->where('name_of_service', 'like', '%' . $keyword . '%')
                    ->orWhere('site_location', 'like', '%' . $keyword . '%')
                    ->orWhere('payment_id', 'like', '%' . $keyword . '%');
            });

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

        $getItems = $getAllTemporaryAds->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 getOneFirstPartyTemporaryAds($temporaryId) {
        $getTemporary = FirstPartyTemporaryAds::where('id', $temporaryId)->with(['user','firstPartyTemporaryAdsDetails'])->get();
        
        if($getTemporary[0]['application_status'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $getTemporary[0]['assigned_officer'])->where('department', 'Registry')->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing relational manager admin";
            }
        }elseif($getTemporary[0]['rm_recommendation'] == "pending"){
            $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $getTemporary[0]['assigned_officer'])->where('department', 'Registry')->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing relational manager admin";
            }
        }elseif($getTemporary[0]['hod_recommendation'] == "pending"){
            $callsub = UserAdmin::where('id', $getTemporary[0]['assigned_officer'])->first();
            $calladmin = UserAdmin::select('first_name', 'last_name', 'department')->where('id', $callsub->line_manager)->get()->toArray();
            if(empty($calladmin)){
                $calladmin = "missing hod admin";
            }
        }elseif($getTemporary[0]['md_approval'] == "pending"){
            $calladmin = "M.D";
        }else{
            $calladmin = "";
        }
        
        
        if(is_null($getTemporary)) {
            return response()->json(['success' => false, 'data' => 'There is no temporary ads with the id' . $temporaryId], $this->errorStatusCode);
        } else {
            return response()->json(['success' => true, 'data' => $getTemporary, 'admins' => $calladmin], $this->successStatusCode);
        }
    }

    public function rmRecommendTemporaryAdsApproval(Request $request, $temporaryId) {
        $validate = Validator::make($request->all(), [
            // 'accept_price' => 'required|boolean',
            'comments' => 'nullable|string|max:255',
            'reports_from_branchmanger' => 'required|string|max:255',
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
        }
        $input = $request->all();
        $string = true;
        $temporaryObj =  FirstPartyTemporaryAds::findOrFail($temporaryId);
        
        if(Auth::user()->department == "Registry"){
            if(Auth::user()->id == (int) $temporaryObj->assigned_officer) {
                if ($temporaryObj->application_pay_status == 'paid') {
                    // if ($temporaryObj->rm_recommendation == 'pending') {
                    if ($temporaryObj->rm_recommendation) {
                        if(isset($request['reports_from_branchmanger'])){
                            $bmcomment = $request['reports_from_branchmanger'];
                        }else{
                            $bmcomment = "";
                        }
                        if(isset($request['comments'])){
                            $ucomment = $request['comments'];
                        }else{
                            $ucomment = "";
                        }
                        $adsPrice = $this->calculateTemporaryAdsBill($string, $temporaryObj->id);
                        // var_dump($adsPrice);die();
                        FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['rm_recommendation' => 'approved', 'hod_recommendation' => 'pending', 'rm_comment' => $bmcomment]);
                        $appHistory = new AppHistoryFirstPartyTemporaryAds();
                        $appHistory->who_performed_action = (string) Auth::user()->id;
                        $appHistory->purpose = "RM recommend";
                        $appHistory->ads_price = $adsPrice;
                        $temporaryObj->appHistoryFirstPartyTemporaryAds()->save($appHistory);
                        return response()->json(['success' => true, 'data' => $adsPrice], $this->successStatusCode);
                    } else {
                        return response()->json(['success' => false, 'data' => 'temporary ads has been recommended already'], $this->errorStatusCode);
                    }
                } else {
                    return response()->json(['success' => false, 'data' => 'can not yet recommend the application'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' =>  'no sufficient priviledge to this action '], $this->errorStatusCode);
            }
        }else{
            // if(Auth::user()->id == $temporaryObj->assigned_officer) {
                if ($temporaryObj->application_pay_status == 'paid') {
                    if ($temporaryObj->rm_recommendation == 'pending') {
                        // FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['rm_recommendation' => 'approved', 'hod_recommendation' => 'pending']);
                        $adsPrice = $this->calculateTemporaryAdsBill($string, $temporaryObj->id);
                        $appHistory = new AppHistoryFirstPartyTemporaryAds();
                        $appHistory->who_performed_action = (string) Auth::user()->id;
                        $appHistory->purpose = "RM recommend";
                        $appHistory->ads_price = $adsPrice;
                        $temporaryObj->appHistoryFirstPartyTemporaryAds()->save($appHistory);
                        return response()->json(['success' => true, 'data' => $adsPrice], $this->successStatusCode);
                    } else {
                        return response()->json(['success' => false, 'data' => 'temporary ads has been recommended already'], $this->errorStatusCode);
                    }
                } else {
                    return response()->json(['success' => false, 'data' => 'can not yet recommend the application'], $this->errorStatusCode);
                }
            // } else {
            //     return response()->json(['success' => false, 'data' =>  'no sufficient priviledge to this action '], $this->errorStatusCode);
            // }
        }

    }

    public function rmRecommendTemporaryAdsDisapproval(Request $request, $temporaryId) {
        $validate = Validator::make($request->all(), [
            // 'accept_price' => 'required|boolean',
            'comments' => 'required|string|max:255',
            'reports_from_branchmanger' => 'nullable|string|max:255',
        ]);

        if($validate->fails()) {
            return response()->json(['errors' => $validate->errors()->all()], $this->errorStatusCode);
        }
        $input = $request->all();
        $string = true;
        $temporaryObj =  FirstPartyTemporaryAds::findOrFail($temporaryId);
        if(Auth::user()->id == (int) $temporaryObj->assigned_officer) {
            if ($temporaryObj->application_pay_status == 'paid') {
                if ($temporaryObj->rm_recommendation == 'pending') {
                    if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }
                    FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['rm_recommendation' => 'disapproved', 'rm_comment' => $bmcomment]);
                    // $adsPrice = $this->calculateTemporaryAdsBill($string, $temporaryObj->id);
                    $getApplicant = User::where('id', $temporaryObj['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('temporary_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('temporary_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, 'message' => 'Application has been returned'], $this->successStatusCode);
                } else {
                    return response()->json(['success' => false, 'data' => 'temporary ads has been recommended already'], $this->errorStatusCode);
                }
            } else {
                return response()->json(['success' => false, 'data' => 'can not yet recommend the application'], $this->errorStatusCode);
            }
        } else {
            return response()->json(['success' => false, 'data' =>  'no sufficient priviledge to this action'], $this->errorStatusCode);
        }
    }

    public function hodRecommendTemporaryAdsApproval($temporaryId, 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);
            }

            $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);

            if (!$this->isAuthorized($temporaryObj)) {
                return response()->json(['success' => false, 'data' => 'You are not authorized to access this resource'], $this->errorStatusCode);
            }

            if ($temporaryObj->hod_recommendation !== 'pending') {
                return response()->json(['success' => false, 'data' => 'HOD has already recommended this temporary ad'], $this->errorStatusCode);
            }
            
                    if(isset($request['reports_from_branchmanger'])){
                        $bmcomment = $request['reports_from_branchmanger'];
                    }else{
                        $bmcomment = "";
                    }
                    if(isset($request['comments'])){
                        $ucomment = $request['comments'];
                    }else{
                        $ucomment = "";
                    }

            $updateData = ['hod_recommendation' => 'approved', 'hod_comment' => $bmcomment];
            if ($temporaryObj->assigned_department === 'Registry') {
                $updateData['md_approval'] = 'pending';
            }

            FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update($updateData);

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


    public function hodrecommendTemporaryAdsDisapproval($temporaryId, Request $request) {
        $validate = Validator::make($request->all(), [
            'comments' => 'required|string|max:255',
            'reports_from_branchmanger' => 'nullable|string|max:255',
        ]);

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

        $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);

        if (!$this->isAuthorized($temporaryObj)) {
            return response()->json(['success' => false, 'data' => 'You are not authorized to access this resource'], $this->errorStatusCode);
        }

        if ($temporaryObj->hod_recommendation !== 'pending') {
            return response()->json(['success' => false, 'data' => 'HOD has already recommended this temporary ad'], $this->errorStatusCode);
        }
        
        if(isset($request['reports_from_branchmanger'])){
            $bmcomment = $request['reports_from_branchmanger'];
        }else{
            $bmcomment = "";
        }
        if(isset($request['comments'])){
            $ucomment = $request['comments'];
        }else{
            $ucomment = "";
        }

        $updateData = ['hod_recommendation' => 'disapproved', 'hod_comment' => $bmcomment];
        if ($temporaryObj->assigned_department === 'Registry') {
            $updateData['rm_recommendation'] = 'pending';
        }

        FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update($updateData);

        $getResponse = FirstPartyTemporaryAds::where('id', $temporaryObj->id)->with(['firstPartyTemporaryAdsDetails'])->get();
                    $getApplicant = User::where('id', $getResponse[0]['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('temporary_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('temporary_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);
    }

    public function mdApprovalTemporaryAds($temporaryId, 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);
        }

        if((integer)Auth::user()->admin_role_id !== 6) {
            return response()->json(['success' => false, 'data' => 'You are not authorized to access this resource'], $this->errorStatusCode);
        }

        $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
        if($temporaryObj->assigned_department !== 'Registry') {
            return response()->json(['success' => false, 'data' => 'Only registry department temporary ads that required md approval'],
                $this->errorStatusCode);
        }

        if($temporaryObj->md_approval !== 'pending') {
            return response()->json(['success' => false, 'data' => 'Temporary ads has been treated'], $this->errorStatusCode);
        }
        
        if(isset($request['reports_from_branchmanger'])){
            $bmcomment = $request['reports_from_branchmanger'];
        }else{
            $bmcomment = "";
        }
        if(isset($request['comments'])){
            $ucomment = $request['comments'];
        }else{
            $ucomment = "";
        }

        FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['md_approval' => 'approved', 'md_comment' => $bmcomment]);

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

    public function mdDisapprovalTemporaryAds($temporaryId, Request $request) {
        
        $validate = Validator::make($request->all(), [
            'comments' => 'required|string|max:255',
            'reports_from_branchmanger' => 'nullable|string|max:255',
        ]);

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

        if((integer)Auth::user()->admin_role_id !== 6) {
            return response()->json(['success' => false, 'data' => 'You are not authorized to access this resource'], $this->errorStatusCode);
        }

        $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
        if($temporaryObj->assigned_department !== 'Registry') {
            return response()->json(['success' => false, 'data' => 'Only registry department temporary ads that required md approval'],
                $this->errorStatusCode);
        }

        if($temporaryObj->md_approval !== 'pending') {
            return response()->json(['success' => false, 'data' => 'Temporary ads has been treated'], $this->errorStatusCode);
        }
        
        if(isset($request['reports_from_branchmanger'])){
            $bmcomment = $request['reports_from_branchmanger'];
        }else{
            $bmcomment = "";
        }
        if(isset($request['comments'])){
            $ucomment = $request['comments'];
        }else{
            $ucomment = "";
        }

        FirstPartyTemporaryAds::where('id', $temporaryObj->id)->update(['md_approval' => 'disapproved', 'md_comment' => $bmcomment]);

        $getResponse = FirstPartyTemporaryAds::where('id', $temporaryObj->id)->with(['firstPartyTemporaryAdsDetails'])->get();
                    $getApplicant = User::where('id', $getResponse[0]['user_id'])->get();
                    $getApplicantEmail = $getApplicant[0]['email'];
                    $emailsubject = EmailContent::getContent('temporary_decline_approve_subject');
                    $emailcontent = EmailContent::getContent('temporary_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);
    }

    // private function calculateTemporaryAdsBill($string, $temporaryId) {

    //         $userId = Auth::user()->id;
    //         $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
    //         $temporaryDetails = FirstPartyTemporaryAdsDetails::where('first_party_temporary_ads_id', $temporaryObj->id)->get();
    //         $count = FirstPartyTemporaryAdsDetails::where('first_party_temporary_ads_id', $temporaryObj->id)->count();
    //         $carbonStartDate = Carbon::parse($temporaryObj->start_date);
    //         $carbonEndDate = Carbon::parse($temporaryObj->end_date);
    //         $dayDiff = $carbonStartDate->diffInDays($carbonEndDate);
    //         $weekDiff = $carbonStartDate->diffInWeeks($carbonEndDate);
            
            
    //         // Parse the start and end dates
    //         $start = Carbon::parse($temporaryObj->start_date);
    //         $end = Carbon::parse($temporaryObj->end_date);
        
    //         // Adjust the start date to the start of its week (Monday)
    //         $startOfWeek = $start->copy()->startOfWeek();
        
    //         // Adjust the end date to the end of its week (Sunday)
    //         $endOfWeek = $end->copy()->endOfWeek();
        
    //         // Calculate the total number of weeks
    //         $weeks = $startOfWeek->diffInWeeks($endOfWeek) + 1;
            
    //         // Adjust the start date to the start of its week (Monday)
    //         $startOfMonth = $start->copy()->startOfMonth();
        
    //         // Adjust the end date to the end of its week (Sunday)
    //         $endOfMonth = $end->copy()->endOfMonth();
        
    //         // Calculate the total number of weeks
    //         $months = $startOfMonth->diffInMonths($endOfMonth) + 1;
            
            

    //         $price = 0;            
    //         for ($i = 0; $i < $count; $i++) {
    //             if ($temporaryDetails[$i]['type_sign'] == 'Branded T-Shirt') {
    //                 $amountPerDayPerUnit = 750;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $valueCount = $temporaryDetails[$i]['number_of_days'];
    //                 $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'City Walker/Skaters') {
    //                 $amountPerDayPerUnit = 2000;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $valueCount = $temporaryDetails[$i]['number_of_days'];
    //                 $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Banner On Vehicle(Car, Bus)') {
    //                 $amountPerDayPerUnit = 5000;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $valueCount = $temporaryDetails[$i]['number_of_days'];
    //                 $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Banner On A Truck') {
    //                 $amountPerDayPerUnit = 7000;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $valueCount = $temporaryDetails[$i]['number_of_days'];
    //                 $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Banner On Rig') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Feather Sign') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Cart/Trolley/Stand') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Flags') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Banners') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Parasols') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Roll-Up Banner') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1050 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Gazebos/Tent') {
    //                 $amountPerWeekPerUnit = 6000;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Kiosk') {
    //                 $amountPerWeekPerUnit = 7500;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Inflatables/Mascot') {
                    
    //                 if ($temporaryDetails[$i]['size_ads'] <= 45) {
    //                     $amountPerWeekPerUnit = 39385;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 45 && $temporaryDetails[$i]['size_ads'] <= 70){
    //                     $amountPerWeekPerUnit = 49231;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 70 && $temporaryDetails[$i]['size_ads'] <= 100){
    //                     $amountPerWeekPerUnit = 61539;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 100){
    //                     $amountPerWeekPerUnit = 76923.08;
    //                 }
                    
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Standard') {
    //                 if($temporaryObj->duration == "Monthly"){
    //                     $amountPerWeekPerUnit = 1500000;
    //                 } elseif($temporaryObj->duration == "Quarterly"){
    //                     $amountPerWeekPerUnit = 3000000;
    //                 } elseif($temporaryObj->duration == "Biannual"){
    //                     $amountPerWeekPerUnit = 5000000;
    //                 } elseif($temporaryObj->duration == "Annually"){
    //                     $amountPerWeekPerUnit = 9000000;
    //                 }
    //                 $price += $amountPerWeekPerUnit;
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Intermediate') {
    //                 if($temporaryObj->duration == "Monthly"){
    //                     $amountPerWeekPerUnit = 3000000;
    //                 } elseif($temporaryObj->duration == "Quarterly"){
    //                     $amountPerWeekPerUnit = 5000000;
    //                 } elseif($temporaryObj->duration == "Biannual"){
    //                     $amountPerWeekPerUnit = 8000000;
    //                 } elseif($temporaryObj->duration == "Annually"){
    //                     $amountPerWeekPerUnit = 12000000;
    //                 }
    //                 $price += $amountPerWeekPerUnit;
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Premium') {
    //                 if($temporaryObj->duration == "Monthly"){
    //                     $amountPerWeekPerUnit = 3000000;
    //                 } elseif($temporaryObj->duration == "Quarterly"){
    //                     $amountPerWeekPerUnit = 5000000;
    //                 } elseif($temporaryObj->duration == "Biannual"){
    //                     $amountPerWeekPerUnit = 9000000;
    //                 } elseif($temporaryObj->duration == "Annually"){
    //                     $amountPerWeekPerUnit = 15000000;
    //                 }
    //                 $price += $amountPerWeekPerUnit;
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Banner On Premise') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] > 4.5) {
    //                     $amountPerWeekPerUnit = 1250 * $temporaryDetails[$i]['size_ads'];
    //                 }else{
    //                     $amountPerWeekPerUnit = 5000;
    //                 }
    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Wall Drape For Non-Practitioner') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 1250 * $temporaryDetails[$i]['size_ads'];
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Wall Drape For Practitioner') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 725 * $temporaryDetails[$i]['size_ads'];

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
                    
    //                 // $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Development Boards') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] <= 5) {
    //                     $amountPerWeekPerUnit = 6045;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 5 && $temporaryDetails[$i]['size_ads'] <= 10){
    //                     $amountPerWeekPerUnit = 9360;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 10 && $temporaryDetails[$i]['size_ads'] <= 15){
    //                     $amountPerWeekPerUnit = 14527.5;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 15 && $temporaryDetails[$i]['size_ads'] <= 20){
    //                     $amountPerWeekPerUnit = 22132.5;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 20 && $temporaryDetails[$i]['size_ads'] <= 25){
    //                     $amountPerWeekPerUnit = 41700;
    //                 }

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $months);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Development Boards For Government Contractor') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 if ($temporaryDetails[$i]['size_ads'] <= 5) {
    //                     $amountPerWeekPerUnit = 16700;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 5 && $temporaryDetails[$i]['size_ads'] <= 10){
    //                     $amountPerWeekPerUnit = 25000;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 10 && $temporaryDetails[$i]['size_ads'] <= 15){
    //                     $amountPerWeekPerUnit = 33350;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 15 && $temporaryDetails[$i]['size_ads'] <= 20){
    //                     $amountPerWeekPerUnit = 41700;
    //                 }elseif($temporaryDetails[$i]['size_ads'] > 20 && $temporaryDetails[$i]['size_ads'] <= 25){
    //                     $amountPerWeekPerUnit = 50000;
    //                 }

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $months);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Wrap Around(Construction Site)') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 41700;

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $months);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $months);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Flag Pole/Feather Banner') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 5000;

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Water Tank') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 336 * $temporaryDetails[$i]['size_ads'];
                    

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Water Advertisement') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 44800;
                    
    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerWeekPerUnit * $quantityShirt * $weeks);
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Blimp') {
    //                 $startOfYear = Carbon::now()->startOfYear();
    //                 $lastDayofYear = Carbon::createFromDate(Carbon::now()->year, 12, 31);
    //                 $diff = $startOfYear->diffInDays($lastDayofYear);
    //                 $amountPerDayPerUnit = 4000000 * $diff;
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
    //                 $valueCount = $temporaryDetails[$i]['number_of_days'];

    //                 if(Auth::user()->department == "Registry"){
    //                     $legalf = 1 / 100 * ($amountPerDayPerUnit * $quantityShirt * $valueCount);
                    
    //                     $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount) + $legalf;

    //                 }else{
                    
    //                     $price += ($amountPerDayPerUnit * $quantityShirt * $valueCount);

    //                 }
    //             } elseif ($temporaryDetails[$i]['type_sign'] == 'Water Tank Ultra Wave For Airport') {
    //                 $quantityShirt = $temporaryDetails[$i]['number_wearable'];
                    
    //                 $amountPerWeekPerUnit = 630 * $temporaryDetails[$i]['size_ads'];
                    
    //                 $price += ($amountPerWeekPerUnit * $quantityShirt * $weeks);
    //             }
    //         }
    //         $calculatedPrice = 0;
    //         if ($string == 'true') {
    //             $appHistory = new AppHistoryFirstPartyTemporaryAds();
    //             $appHistory->purpose = 'Temporary Ads Application';
    //             $appHistory->ads_price = $price;
    //             $appHistory->who_performed_action = (string) $userId;
    //             $temporaryObj->appHistoryFirstPartyTemporaryAds()->save($appHistory);
    //             $getPrice = AppHistoryFirstPartyTemporaryAds::where('first_party_temporary_ads_id', $temporaryObj->id)->get()->last();
    //             $calculatedPrice = $getPrice->ads_price;
    //         } else {
    //             $calculatedPrice = $price;
    //         }
    //         return $calculatedPrice;
    // }
    
    public function getTemporaryPricing (){
        
        $getPrices = TemporaryAdsPricing::all();
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function getTemporaryPricingDistinct($party){
        
        if($party == "blanket"){
            $getPrices = TemporaryAdsPricing::where(function ($query) use ($party) {
                        $query->where('party_type', $party);
                    })
                    ->distinct()
                    ->pluck('type_sign');
        }else{
            $getPrices = TemporaryAdsPricing::where(function ($query) use ($party) {
                        $query->where('party_type', $party)
                              ->orWhere('party_type', 'both_party');
                    })
                    ->distinct()
                    ->pluck('type_sign');
        }
        
        
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function deleteTemporaryPricing($id){
        
        $getPrices = TemporaryAdsPricing::find($id)->delete();
        return response()->json(['success' => true, 'data' => 'Pricing record deleted successfully'], 200);
    }
    
    public function getTemporaryApplicationPricing(){
        
        $getPrices = TemporaryAdsApplicationPricing::all();
        return response()->json(['success' => true, 'data' => $getPrices], 200);
    }
    
    public function updateTemporaryAdsApplicationPricing(Request $request, $id) {
        
        $validator = Validator::make($request->all(), [
            'app_price' => ['required', 'numeric', 'min:0'],
            'not_three_working_days_percentage' => ['required', 'numeric', 'min:0'],
        ]);
    
        // Find the record by ID
        $pricing = TemporaryAdsApplicationPricing::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 updateTemporaryAdsPricing(Request $request, $id) {
        
        $validator = Validator::make($request->all(), [
            'type_sign' => ['required', 'string', 'max:255'],
            'pricing_type' => ['required', 'string', 'max:255'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'size_threshold' => ['nullable', 'numeric', 'min:0'],
            'price_per_unit_size' => ['nullable', 'numeric', 'min:0'],
            'size_range_min' => ['nullable', 'numeric', 'min:0'],
            'size_range_max' => ['nullable', 'numeric', 'min:0', 'gte:size_range_min'],
            'duration' => ['nullable', 'string', 'max:255'],
            'is_special_calculation' => ['nullable', 'boolean'],
            'party_type' => ['nullable', 'string', 'max:255']
        ]);
    
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], $this->errorStatusCode);
        }
    
        $validated = $validator->validated();
    
        // Find the record by ID
        $pricing = TemporaryAdsPricing::findOrFail($id);
    
        // For fixed pricing types, ensure duration is set
        if ($validated['pricing_type'] === 'fixed' && empty($validated['duration'])) {
            return response()->json(['duration' => 'Duration is required for fixed pricing'], $this->errorStatusCode);
        }
    
        $pricing->update($validated);
    
        return response()->json(['success' => true, 'data' => 'Pricing record updated successfully'], 200);
    }
    
    public function createTemporaryAdsPricing(Request $request) {
        
        $validator = Validator::make($request->all(), [
            'type_sign' => ['required', 'string', 'max:255'],
            'pricing_type' => ['required', 'string', 'max:255'],
            'base_price' => ['required', 'numeric', 'min:0'],
            'size_threshold' => ['nullable', 'numeric', 'min:0'],
            'price_per_unit_size' => ['nullable', 'numeric', 'min:0'],
            'size_range_min' => ['nullable', 'numeric', 'min:0'],
            'size_range_max' => ['nullable', 'numeric', 'min:0', 'gte:size_range_min'],
            'duration' => ['nullable', 'string', 'max:255'],
            'is_special_calculation' => ['nullable', 'boolean'],
            'party_type' => ['nullable', 'string', 'max:255']
        ]);
    
        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()->all()], $this->errorStatusCode);
        }
    
        $validated = $validator->validated();
    
        // For fixed pricing types, ensure duration is set
        if ($validated['pricing_type'] === 'fixed' && empty($validated['duration'])) {
            return response()->json(['duration' => 'Duration is required for fixed pricing'], $this->errorStatusCode);
        }
    
        $pricing = TemporaryAdsPricing::create($validated);
    
        return response()->json(['success' => true, 'data' => 'Pricing record created successfully'], 200);
    }
    
    private function calculateTemporaryAdsBill($string, $temporaryId)
    {
        $userId = Auth::id();
        $temporaryObj = FirstPartyTemporaryAds::findOrFail($temporaryId);
        $temporaryDetails = FirstPartyTemporaryAdsDetails::where('first_party_temporary_ads_id', $temporaryObj->id)->get();

        // Calculate date periods
        $dateCalculations = $this->calculateDatePeriods($temporaryObj);
        $weeks = $dateCalculations['weeks'];
        $months = $dateCalculations['months'];
        $dayDiff = $dateCalculations['dayDiff'];

        $price = 0;

        foreach ($temporaryDetails as $detail) {
            $pricing = $this->getApplicablePricing($detail, $temporaryObj);
            
            
            if (!$pricing) continue;

            $quantity = $detail['number_wearable'];
            $size = $detail['size_ads'] ?? 0;

            // Calculate price based on pricing type
            $price += $this->calculatePriceBasedOnType($pricing, $detail, $quantity, $size, $weeks, $months, $dayDiff);

            // var_dump($price);die();
            // Add legal fee if applicable
            if (Auth::user()->department == "Registry") {
                $legalFee = 0.01 * $price;
                $price += $legalFee;
            }
            
            // var_dump($string, $price, $temporaryObj, $userId);die();
        }

        return $this->handlePriceOutput($string, $price, $temporaryObj, $userId);
    }

    /**
     * Calculate date periods for pricing
     */
    private function calculateDatePeriods($temporaryObj)
    {
        $start = Carbon::parse($temporaryObj->start_date);
        $end = Carbon::parse($temporaryObj->end_date);

        return [
            'dayDiff' => $start->diffInDays($end),
            'weeks' => $start->copy()->startOfWeek()->diffInWeeks($end->copy()->endOfWeek()) + 1,
            'months' => $start->copy()->startOfMonth()->diffInMonths($end->copy()->endOfMonth()) + 1
        ];
    }

    /**
     * Get applicable pricing record for the ad detail
     */
    private function getApplicablePricing($detail, $temporaryObj)
    {
        $query = TemporaryAdsPricing::where('type_sign', $detail['type_sign']);

        // Handle size-based pricing
        if (in_array($detail['type_sign'], ['Inflatables/Mascot', 'Development Boards', 'Development Boards For Government Contractor'])) {
            $size = $detail['size_ads'] ?? 0;
            $query->where('size_range_min', '<=', $size)
                  ->where('size_range_max', '>=', $size);
        }
        // Handle duration-based pricing
        elseif (in_array($detail['type_sign'], ['Standard', 'Intermediate', 'Premium'])) {
            $query->where('duration', $temporaryObj->duration);
        }

        return $query->first();
    }

    /**
     * Calculate price based on pricing type
     */
    private function calculatePriceBasedOnType($pricing, $detail, $quantity, $size, $weeks, $months, $days)
    {
        if ($pricing->is_special_calculation) {
            return $this->calculateSpecialPrice($pricing, $detail, $quantity, $size, $weeks, $months, $days);
        }

        switch ($pricing->pricing_type) {
            case 'daily':
                return $this->calculateDailyPrice($pricing, $quantity, $detail['number_of_days'] ?? $days);
            case 'weekly':
                return $this->calculateWeeklyPrice($pricing, $quantity, $size, $weeks);
            case 'monthly':
                return $pricing->base_price * $quantity * $months;
            default:
                return 0;
        }
    }

    /**
     * Calculate daily price
     */
    private function calculateDailyPrice($pricing, $quantity, $days)
    {
        return $pricing->base_price * $quantity * $days;
    }

    /**
     * Calculate weekly price with size consideration
     */
    private function calculateWeeklyPrice($pricing, $quantity, $size, $weeks)
    {
        if ($pricing->size_threshold && $size > $pricing->size_threshold) {
            return $pricing->price_per_unit_size * $size * $quantity * $weeks;
        }
        return $pricing->base_price * $quantity * $weeks;
    }

    /**
     * Calculate special pricing cases
     */
    private function calculateSpecialPrice($pricing, $detail, $quantity, $size, $weeks, $months, $days)
    {
        switch ($pricing->type_sign) {
            case 'Blimp':
                $startOfYear = Carbon::now()->startOfYear();
                $lastDayofYear = Carbon::createFromDate(Carbon::now()->year, 12, 31);
                $diff = $startOfYear->diffInDays($lastDayofYear);
                return $pricing->base_price * $diff * $quantity * ($detail['number_of_days'] ?? $days);
            
            case 'Water Tank':
                return $pricing->price_per_unit_size * $size * $quantity * $weeks;
            
            case 'Water Advertisement':
                return $pricing->base_price * $quantity * $weeks;
            
            case 'Wrap Around(Construction Site)':
                return $pricing->base_price * $quantity * $months;
            
            default:
                return $pricing->base_price * $quantity * ($pricing->pricing_type === 'monthly' ? $months : $weeks);
        }
    }

    /**
     * Handle price output and history recording
     */
    private function handlePriceOutput($string, $price, $temporaryObj, $userId)
    {
        if ($string == 'true') {
            $appHistory = new AppHistoryFirstPartyTemporaryAds();
            $appHistory->who_performed_action = (string) $userId;
            $appHistory->purpose = "Temporary Ads Application";
            $appHistory->ads_price = $price;
            $temporaryObj->appHistoryFirstPartyTemporaryAds()->save($appHistory);
            // var_dump($appHistory->ads_price);die();
            return $appHistory->ads_price;
        }
        return $price;
    }

    private function isAuthorized($temporaryObj) {
        $user = Auth::user();

        if ($temporaryObj->assigned_department === 'Mobile_advert' && $user->department === 'Mobile_advert' && $user->admin_role_id == 5) {
            return true;
        }

        if ($temporaryObj->assigned_department === 'Registry' && $user->department === 'Registry' && $user->admin_role_id == 5) {
            return true;
        }
        return false;
    }
    
    public function composeEmailV2($subject, $userEmail, $emailContent) {

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

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

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

            $mail->isHTML(true);
            Log::info($userEmail);
            $mail->Subject = $subject;
            $mail->Body = $emailContent;
            $mail->send();
            Log::info("message sent");
        } catch (Exception $exception) {
//            error_log('Email delivery failed: ' . $mail->ErrorInfo);
            $message = $exception->getMessage();
            Log::error($message);
            return true;
        }
    }
    
    protected function domainExists($email)
    {
        // Extract the domain from the email address
        $parts = explode('@', $email);
        $domain = array_pop($parts);

        // Perform a DNS lookup for the domain
        $mxRecords = [];
        if (checkdnsrr($domain, 'MX')) {
            // MX records found, domain exists
            return true;
        } else {
            // No MX records found, domain does not exist
            return false;
        }
    }
    
    public function gettemporaryDownloadables($id) {
        $user = Auth::user();
        $check = FirstPartyTemporaryReceipts::where('first_party_temporary_ads_id', $id)->exists();
        if($check){
            $getreceipts = FirstPartyTemporaryReceipts::where('first_party_temporary_ads_id', $id)->get()->toArray();
        
            return response()->json(['data' => $getreceipts], 200);
        }else{
            return response()->json(['data' => 'No Downloadables Yet!'], 422);
        }
        
    }

}
