<?php

namespace App\Utility;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
use Cake\ORM\TableRegistry;
use Cake\View\View;
use Cake\Cache\Cache;
use Cake\Mailer\Email;
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class SmtpCheck{
    
    private function allPersonalizeEmail()
    {
        return Cache::remember('personalizes', function () {
            return TableRegistry::get('personalizes')->getAllPersonalizeEmails();
        });
    }
    
    public function isValidSMTP($smtpData){
        require WWW_ROOT.'/Staff/vendor/autoload.php'; 
        
        $result = false;
        $mail = new PHPMailer(true);
       
        try {
            //Server settings
            //$mail->SMTPDebug = SMTP::DEBUG_SERVER;                      // Enable verbose debug output
            $mail->isSMTP();                                            // Send using SMTP
            $mail->Host       = $smtpData['smtp_host'];                    // Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
            $mail->Username   = $smtpData['username'];                     // SMTP username
            $mail->Password   = $smtpData['password'];                               // SMTP password
            $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port       = $smtpData['smtp_port'];                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

            if($mail->smtpConnect()){
                $result = true;
            }
                //return true;
        } catch (Exception $e) {
            $result = false;
        }
        
        return $result;
        
    }
    
    public function prepareEmail($personalizeEmails,$e,$queue_id) {
            $sent = false;
            //$configName = $e['config'] === 'default' ? $this->params['config'] : $e['config'];
            //$template = $e['template'] === 'default' ? $this->params['template'] : $e['template'];
            //$layout = $e['layout'] === 'default' ? $this->params['layout'] : $e['layout'] ;
            //$headers = empty($e['headers']) ? [] : (array)$e['headers'];
            //$theme = empty($e['theme']) ? '' : (string)$e['theme'];
            $viewVars = empty($e['template_vars']) ? [] : $e['template_vars'];
            $errorMessage = null;
            
            try {
                
                if(!empty($e['attachments']) && !file_exists($e['attachments'])){
                    //$this->removeFromCacheByIndex($queue_id);
                    return false;
                }
                //pr('Email/html'.$template);exit;
                $view = new View($this->request, $this->response);
                $view->viewPath = 'Email/html';
                $view->layout = false;
                $view->set($viewVars);
                $body = $view->render($e['template']);
                
                
                
                $smtpData = $this->sendCustomEmail($personalizeEmails[$e['member_id']]);

                if(!empty($smtpData)){
                    
                    $data['subject'] = $e['subject'];
                    $data['body'] = $body;
                    $data['email'] = $e['email'];
                    $data['from_email'] = $e['from_email'];
                    $data['from_name'] = $e['from_name'];
                    $data['attachments'] = $e['attachments'];
                    $data['template'] = $e['template'];
                    $data['parent_id'] = $e['parent_id'];
                    $data['member_id'] = $e['member_id'];
                    $data['viewVars'] = $viewVars;
                   
                    $sent = $this->sendEmail($smtpData, $data);
                    
                }
            } catch (SocketException $exception) {
                $this->err($exception->getMessage());
                $errorMessage = $exception->getMessage();
                $sent = false;
            }
            
//            $all_queue_emails = Cache::read('email_queue');
//            if(isset($all_queue_emails[$queue_id]) && !empty($all_queue_emails[$queue_id])){
//                unset($all_queue_emails[$queue_id]);
//            }
//
//            if(!empty($all_queue_emails)){
//                Cache::write('email_queue',$all_queue_emails);
//            }else{
//                Cache::delete('email_queue');
//            }
            
            @unlink($e['attachments']);
            
            return $sent;
    }

    private function removeFromCacheByIndex($index){
         $all_queue_emails = Cache::read('email_queue');
         if(isset($all_queue_emails[$index])){
             unset($all_queue_emails[$index]);
         }   
         
        if(!empty($all_queue_emails)){
            Cache::write('email_queue',$all_queue_emails);
        }else{
            Cache::delete('email_queue');
        }
    }

    protected function sendCustomEmail($personalize){
       
            $APP_SMTP_USERNAME = APP_SMTP_USERNAME;
            $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME;
            $APP_SMTP_HOST = APP_SMTP_HOST;
            $APP_SMTP_PORT = APP_SMTP_PORT;
            $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD;
            
            if (!empty($personalize) && $personalize['is_smtp'] == 1) {
                $APP_SMTP_USERNAME = $personalize['username'];
                $APP_SMTP_FROM_NAME = $personalize['smtp_from'];
                $APP_SMTP_HOST = $personalize['smtp_host'];
                $APP_SMTP_PORT = $personalize['smtp_port'];
                $APP_SMTP_PASSWORD = $personalize['password'];
            }

            $default = [
                'className' => 'Smtp',
                'host' => $APP_SMTP_HOST,
                'port' => $APP_SMTP_PORT,
                //'timeout' => $APP_SMTP_TIMEOUT,
                'username' => $APP_SMTP_USERNAME,
                'password' => $APP_SMTP_PASSWORD,
                //'tls' => $APP_SMTP_IS_TLS,
                'tls' => true,
                //'log'=> true
            ];
       
       return $default;
    }
    
    public function sendEmail($smtpData,$data) {
        require WWW_ROOT.'/Staff/vendor/autoload.php'; 
        $result = false;
        $mail = new PHPMailer(true);
       
        try {
            //Server settings
            $mail->SMTPDebug = false;                      // Enable verbose debug output
            $mail->isSMTP();                                            // Send using SMTP
            $mail->Host       = $smtpData['host'];                    // Set the SMTP server to send through
            $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
            $mail->Username   = $smtpData['username'];                     // SMTP username
            $mail->Password   = $smtpData['password'];                               // SMTP password
            $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` encouraged
            $mail->Port       = $smtpData['port'];                                    // TCP port to connect to, use 465 for `PHPMailer::ENCRYPTION_SMTPS` above

           //Recipients RTG_SMTP_FROM_NAME
            $mail->setFrom($data['from_email'], $data['from_name']);
            $mail->addAddress($data['email']);    //$data['email'] // Add a recipient
            // Attachments
            if (!empty($data['attachments'])) {
                $mail->addAttachment($data['attachments']);
            }

            // Content
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = $data['subject'];
            $mail->Body = $data['body'];
            $result = $mail->send();

        } catch (\Exception $e) {
            $result = false;

            $templateName = $data['template'];
            if($templateName == "no_template"){
                $templateContent = ['body'=>$data['body']];
            }else{
                $templateContent = $data['viewVars'];
            }
            
            $to = $data['email'];
            $sub = $data['subject'];
            $APP_SMTP_FROM_NAME = $data['from_name'];
            $SMTP_FORM_EMAIL = $data['from_email'];
            $attachment = $data['attachments'];
            if(!$this->sendEmailByProdEmail($templateName, $templateContent, $to, $sub , $attachment,$APP_SMTP_FROM_NAME,$SMTP_FORM_EMAIL)){
                $templateVars['body'] = $data['body'];
                $options = $data;
                $options['exception'] = $e->getMessage();
                $options['parent_id'] = $data['parent_id'] ;
                $options['member_id'] = $data['member_id'] ;
                $emailQueue = TableRegistry::get('EmailQueue');
                $emailQueue->failedInsert($data['email'], $templateVars, $options);
            }else{
                $result = true;
            }
      
        }
        
        return $result;
    }
    
    
    public function sendEmailByProdEmail($templateName, $templateContent, $to, $sub = "New User registration", $attachment = "",$APP_SMTP_FROM_NAME,$SMTP_FORM_EMAIL){
        $result = false;
        try {
                $email = new Email('default');
                //$email = $email->transport('default');
                
                

                if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) {
                    $email->setFrom($APP_SMTP_FROM_NAME);
                }else if (filter_var($APP_SMTP_FROM_NAME, FILTER_VALIDATE_EMAIL)) {
                    $email->setFrom($APP_SMTP_FROM_NAME);
                } else {
                    $email->setFrom($SMTP_FORM_EMAIL,$APP_SMTP_FROM_NAME);
                }
                
                $email->template($templateName)
                        ->emailFormat('html')
                        ->to($to)
                        ->viewVars($templateContent)
                        ->subject($sub);

                if (!empty($attachment)) {
                    $email->addAttachments($attachment);
                }


                $email->send();
                $result = true;
                } catch (Exception $ex) {
                    $this->log($ex);
                }
                
       return $result;         
    }
            
}
