<?php
declare(strict_types=1);

/**
 * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
 * @link      https://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   https://opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;

use App\Utility\EmailQueue\EmailQueue;
use Cake\Controller\Controller;
use Cake\Mailer\Email;

/**
 * Application Controller
 *
 * Add your application-wide methods in the class below, your controllers
 * will inherit them.
 *
 * @link https://book.cakephp.org/4/en/controllers.html#the-app-controller
 */
class AppController extends Controller
{
    /**
     * Initialization hook method.
     *
     * Use this method to add common initialization code like loading components.
     *
     * e.g. `$this->loadComponent('FormProtection');`
     *
     * @return void
     */
    public function initialize(): void
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');

        /*
         * Enable the following component for recommended CakePHP form protection settings.
         * see https://book.cakephp.org/4/en/controllers/components/form-protection.html
         */
        //$this->loadComponent('FormProtection');
    }

    public function sendEmail($templateName, $templateContent, $to, $sub = "New registration", $attachment = "", $personalize = null) {
        $APP_SMTP_USERNAME = APP_SMTP_USERNAME;
        $APP_SMTP_FROM_NAME = APP_SMTP_FROM_NAME;
        $APP_EMAIL_CLASS = APP_EMAIL_CLASS;
        $APP_SMTP_HOST = APP_SMTP_HOST;
        $APP_SMTP_PORT = APP_SMTP_PORT;
        $APP_SMTP_TIMEOUT = APP_SMTP_TIMEOUT;
        $APP_SMTP_PASSWORD = APP_SMTP_PASSWORD;
        $APP_SMTP_IS_TLS = APP_SMTP_IS_TLS;


        if (!empty($personalize)) {
            $templateContent['email_signature'] = $personalize->email_signature;
            if ($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;
            }
        }



        $SMTP_FORM_EMAIL = $APP_SMTP_USERNAME;

        if($APP_SMTP_HOST == 'sandbox.smtp.mailtrap.io'){
            $SMTP_FORM_EMAIL = $APP_SMTP_FROM_NAME;
        }else if($APP_SMTP_HOST == "smtp.mail.yahoo.com"){
            $APP_SMTP_IS_TLS = true;
            $is_yahoo = true;
        }

        $default = [
            'className' => $APP_EMAIL_CLASS,
            '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
        ];



        if(isset($templateContent['company_email']) && !empty($templateContent['company_email'])){
            $SMTP_FORM_EMAIL = $templateContent['company_email'];
        }

        if(isset($templateContent['company_name']) && !empty($templateContent['company_name'])){
            $APP_SMTP_FROM_NAME = $templateContent['company_name'];
        }

        if(IS_QUEUE_ENABLE){
            $data = $templateContent;
            $options['member_id'] = 0;
            if (!empty($personalize) && $personalize->is_smtp == 1) {
                if($personalize->member_id > 0){
                    $options['member_id'] = $personalize->member_id;
                }
            }
            $new_file_link = "";
            if(!empty($attachment) && file_exists($attachment)){
                $att_email_queue_dir = WWW_ROOT."email_queue/".$this->Auth->user('id');
                if(!is_dir($att_email_queue_dir)){
                    mkdir($att_email_queue_dir,0777,true);
                }
                $extension = pathinfo($attachment, PATHINFO_EXTENSION);
                $new_file_name = time().".".$extension;
                $new_file_link = $att_email_queue_dir."/".$new_file_name;
                @copy($attachment, $new_file_link);
            }
            //$options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_name'] = $APP_SMTP_FROM_NAME;
            $options['from_email'] = $SMTP_FORM_EMAIL;
            $options['subject'] = $sub;
            $options['template'] = $templateName;
            $options['format'] = 'html';
            $options['attachments'] = $new_file_link;
            EmailQueue::enqueue($to, $data, $options);

        }
        else{

            try {
                $email = new Email();
                if (!empty($personalize) && $personalize->is_smtp == 1) {
                        Email::configTransport('custom', $default);
                        $email->transport('custom');
                }
                else {
                    $email->transport('default');
                }


                if (isset($templateContent['no_reply']) && !empty($templateContent['no_reply'])) {
                    $email = $email->from($APP_SMTP_FROM_NAME);
                } else {
                    $email = $email->from($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();

            } catch (Exception $ex) {
                $this->log($ex);
            }
        }

    }

}