<?php

class OTPEmail {

    protected $trans;
    protected $emailOTP;

    protected $emailForm = "OTP.mail.form.html";
    protected $emailInbox = "OTP.mail.inbox.html";

    public function __construct( Transaction $trans ) {
        $this->trans = $trans;
    }


    # Verify OTP
    
    public function verified() {
        
        # If email OTP is not required

        if( !$this->trans->requiresOTP('email') ) return true;

        # Get OTP Data;

        $this->emailOTP = $this->trans->bundle['email-otp'] ?? [];

        return !!$this->initOTP();

    }
    
    
    # Verify Email OTP;

    protected function initOTP() {
        
        # Auto send OTP when user first visits

        if( empty($this->emailOTP) ) {
            
            $this->sendNewOTP(); 

            # Check if email OTP has not already been confirmed
            
        } elseif( empty($this->emailOTP['confirmed']) ) {
                
            if( !empty($_POST['email-otp']) ) {

                if( $_POST['email-otp'] == '-R' ) {

                    if( $this->sendNewOTP() ) { // Resend OTP

                        $this->trans->log('info', 'A new OTP has been sent to your email'); 

                    };

                } else {

                    $this->emailOTP['confirmed'] =  ((int)$_POST['email-otp'] == $this->emailOTP['pin']);

                    if( !$this->emailOTP['confirmed'] ) {

                        $this->trans->log('error', "Incorrect OTP <br/> Please check your email for the right OTP");

                        $this->trans->setTemplate( $this->emailForm );

                    };

                    $this->trans->trackBundle( 'email-otp', $this->emailOTP );

                };

            }
            
        };
        
        return $this->emailOTP['confirmed'] ?? false;


    }

    
    # Send Email Code To User

    protected function sendNewOTP() {

         # Create OTP;

         $emailOTP = array(
            "pin" => mt_rand(1000, 9999), // The OTP Code To Send
            "confirmed" => false, // To avoid recursive rendering of the Email OTP Form
        );

        # Get Global Email Template
        $globalEmailTemplate = require Udash::VIEW_DIR . "/MAIL/template.php";

        # Get Email Content
        $emailContent = file_get_contents( $this->trans->getTemplate( $this->emailInbox ) );

        # Replace variables within the content
        $emailContent = Core::replace_var($emailContent, $emailOTP + $this->trans->user + [
            'title' => "Transaction OTP",
            "code_name" => "one-time password (OTP)"
        ]);

        # Generate Email Body
        $emailBody = Core::replace_var( $globalEmailTemplate, [
            "content" =>  $this->trans->X2Client( $emailContent )
        ]);

        $delivered = false;

        # Catch Emai Sending Exceptions
        try {

            $PHPMailer = Udash::PHPMailer(true);
            $PHPMailer->addAddress( $this->trans->user['email'] );
            $PHPMailer->Body =  $emailBody;
            $PHPMailer->Subject = "Verify Transfer OTP";

            # Allow localhost Testing with MailHog Fake SMTP
            $this->trans->localTesting( $PHPMailer );

            # Send The Email
            $delivered = $PHPMailer->send(); // Send Email;

            if( $delivered ) {
                
                $this->trans->trackBundle( 'email-otp', $emailOTP  );
                
            } else {
                
                $this->trans->log('error', "The system was unable to send confirmation OTP. <br/> Please contact the support team");

            }

        } catch( Exception $e ) {

            # Technically an error from PHPMailer;
            $this->trans->log('error', "Failed to send One-Time Password Email <br/> Please contact the support team");
            
        };

        $this->trans->setTemplate( $this->emailForm );

        return $delivered;

    }

}