<?php

namespace App\Http\Controllers\Util;

use App\Models\KycThirdPartyFirstApprovalSequence;
use App\Models\EmailContent;
use Carbon\Carbon;
use Exception;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use js\tools\numbers2words\Speller;
use NumberToWords\NumberToWords;
use PHPMailer\PHPMailer\PHPMailer;


class UtilMethods  {


    public static function convertBase64toPdf($base64Doc) {

        $pdfFile = explode('base64,',$base64Doc);
        $pdfFile = end($pdfFile);
        $pdfFile = str_replace(' ', '+', $pdfFile);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/pdf/" . $uniqueid . '.pdf';

        Storage::disk('public')->put($file,base64_decode($pdfFile));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('pdf/' . $uniqueid . '.pdf'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    public static function thirdPartyFirstApprovalRefno() {

        $sequence = KycThirdPartyFirstApprovalSequence::firstOrCreate([]);
        $lastNumber = $sequence->last_number + 1;
        $sequence->update(['last_number' => $lastNumber]);
        $getYear = Carbon::now()->format('Y');
        $getYear = substr($getYear, 2);
        $getMonth = Carbon::now()->format('m');

        return 'LASAA/MD/EOI/'. $getYear.'/'.$getMonth.'/'. str_pad($lastNumber, 3, '0', STR_PAD_LEFT);
    }

    public static function outdoorRequestAppId() {
        $sequence = KycThirdPartyFirstApprovalSequence::firstOrCreate([]);
        $lastNumber = $sequence->last_number + 1;
        $sequence->update(['last_number' => $lastNumber]);
        $getYear = Carbon::now()->format('Y');
        $getYear = substr($getYear, 2);
        $getMonth = Carbon::now()->format('m');
        return 'LASAA/MD/signage/' . $getYear.'/'.$getMonth.'/'.str_pad($lastNumber, 3, '0', STR_PAD_LEFT);
    }

     public 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 static function thirdPartyFirstApprovalHodEmail($userEmail, $emailContent, $filegenereated) {

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

            $emailsubject = EmailContent::getContent('kyc_eoi_decline_approve_subject');
            
        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenereated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'firstapproval.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info( 'Email sent successfully.');
        } catch (Exception $e) {
            Log::error( 'Error: ' . $mail->ErrorInfo);
        }

    }

    public static function thirdPartySecondApprovalMdEmail($userEmail, $emailContent, $filegenereated) {

        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('kyc_eoi_decline_approve_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenereated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'Secondapproval.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }

    public static function thirdPartyCertificationEmail($userEmail, $emailContent, $filegenerated) {

        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('kyc_eoi_certificate_subject');

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

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'certificate.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
            
            
            
        } catch (Exception $e) {
             Log::error('Error: ' . $mail->ErrorInfo);
        }
    }

    public static function outdoorSignageInvoiceBill($userEmail, $emailContent, $filegenerated) {

        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('outdoor_bill_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'BillInvoice.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }

    public static function  outdoorSignageUpgradeandDowngrade($userEmail, $emailContent, $filegenerated) {

        require base_path('vendor/autoload.php');
        $emailsubject = EmailContent::getContent('outdoor_upgrade_downgrade_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'upgradeanddowngrade.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    public static function  outdoorSignageApproval($userEmail, $emailContent, $filegenerated) {

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

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = 'Outdoor Approval letter';
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'outdoorapproval.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }

    public static function temporaryAdsSendApproval($userEmail, $emailContent, $filegenerated) {

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

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = 'Approval Letter for Temporary Ads';
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'firstpartytemporaryadsletter.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }

    public static function smallFormatSendApproval($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = 'Approval Letter for Small Format Ads';
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'smallformat.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    
    public static function onpremiseSendApproval($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('onpremise_decline_approve_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'onpremiseapproval.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    public static function onpremiseSendDisapproval($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = 'Disapproval Letter for First Party Signage Display';
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'onpremisedisapproval.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    public static function debitnotefirstparty($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('debit_credit_note_firstparty_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'CreditDebitNote.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    public static function debitnotethirdparty($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');
        $emailsubject = EmailContent::getContent('outdoor_debit_credit_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'CreditDebitNote.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }
    
    public static function billgenonpremise($userEmail, $emailContent, $filegenerated) {
        require base_path('vendor/autoload.php');
        
        $emailsubject = EmailContent::getContent('onpremisebill_approve_subject');

        try {
            $mail = new PHPMailer(true);
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'ssl://business74.web-hosting.com';
            $mail->SMTPAuth = true;
            $mail->Username = 'noreply@lasaa.lg.gov.ng';
            $mail->Password = 'SH7ZL,&^^pCL';
            $mail->SMTPSecure = 'ssl';
            $mail->Port = 465;
            $mail->setFrom('noreply@lasaa.lg.gov.ng', 'Lasaa');
            $mail->addAddress($userEmail);
            $mail->addReplyTo('noreply@lasaa.lg.gov.ng', 'Lasaa');

            $mail->isHTML(true);
            $mail->Subject = $emailsubject;
            $mail->Body = $emailContent;

            // Add attachment
            $attachmentContent = $filegenerated; // Replace with your function to generate the attachment content

            // Add attachment
            $attachmentFileName = 'BillInvoiceFirstParty.pdf'; // Name of the attachment file
            $mail->addStringAttachment($attachmentContent, $attachmentFileName);

            $mail->send();
            Log::info('Email sent successfully.');
            Log::info($userEmail);
        } catch (Exception $e) {
            Log::error('Error: ' . $mail->ErrorInfo);
        }
    }


    /**
     * @throws \NumberToWords\Exception\NumberToWordsException
     * @throws \NumberToWords\Exception\InvalidArgumentException
     */
    public static function getAmountInWords($getNumber) {

        $intAmount = (int) $getNumber * 100;
        $numberToWords = new NumberToWords();
        $currencyTransformer = $numberToWords->getCurrencyTransformer('en');
        $amountInWord = $currencyTransformer->toWords($intAmount, 'NGN');
        return $amountInWord;
    }

    public static function temporaryInWords($days) {
        $daysInWord = Speller::spellNumber($days, Speller::LANGUAGE_ENGLISH);
        return $daysInWord;
    }

    public static function smallFormatInMonth($months) {
        $monthsInWord = Speller::spellNumber($months, Speller::LANGUAGE_ENGLISH);
        return $monthsInWord;
    }

    public function thirdPartyOutdoorPaymentId() {
        $prefix = 'outdoor';
        $batchKey = Carbon::now()->format('YmdHis');
        $suffix = rand(100,999);
        return $prefix.$batchKey.$suffix;
    }

    public function upgradeOrDowngrade($option) {
        $prefix = $option;
        $batchKey = Carbon::now()->format('YmdHis');
        $suffix = rand(100,999);
        return $prefix.$batchKey.$suffix;
    }

    public function convertBase64toImage($base64Image) {
        $image = explode('base64,',$base64Image);
        $image = end($image);
        $image = str_replace(' ', '+', $image);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/images/" . $uniqueid . '.png';

        Storage::disk('public')->put($file,base64_decode($image));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('images/' . $uniqueid . '.png'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    public function convertBase64toPdfV2($base64Doc) {
        $pdfFile = explode('base64,',$base64Doc);
        $pdfFile = end($pdfFile);
        $pdfFile = str_replace(' ', '+', $pdfFile);
        //$filename =
        $uniqueid = uniqid();
        $file =  "/pdf/" . $uniqueid . '.pdf';

        Storage::disk('public')->put($file,base64_decode($pdfFile));

        $sourcePath = storage_path('app/public' . $file); // Get the source path in the storage directory
        $destinationPath = public_path('pdf/' . $uniqueid . '.pdf'); // Define the destination path in the public directory

        // Move the file from the storage directory to the public directory
        File::move($sourcePath, $destinationPath);

        $url = env('APP_URL').'/public'.$file;
        return $url;
    }

    public function capitalizeFirstWordInString( $string) {

        $string = strtolower($string);
        $string = preg_replace_callback('/(?:^|[\s\/-])\w/', function ($matches) {
            return strtoupper($matches[0]);
        }, $string);
        return $string;
    }

}
