<?php
defined('BASEPATH') or exit('No direct script access allowed');
date_default_timezone_set('Asia/Kolkata');

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'plugin/PHPMailer/src/Exception.php';
require 'plugin/PHPMailer/src/PHPMailer.php';
require 'plugin/PHPMailer/src/SMTP.php';

class Mailer
{
	function __construct()
	{
		$this->CI = &get_instance();
	}
	public $setMail;



	public function setSenderConfiguration($data, $checkcon = 0)
	{
		if ((empty($data['from_email']) && $checkcon == 0 ) || empty($data['outgoing_user_name']) || empty($data['outgoing_password']) || empty($data['outgoing_mail_server']) || empty($data['outgoing_mail_server_port'])) {
			return (array('success' => false, 'message' => 'Please Provide SMTP  to send email!!'));
		}
		$smtpSecure = '';
		if($data['security_protocol'] == 'SSL'){
			$smtpSecure = PHPMailer::ENCRYPTION_SMTPS;

		}else if($data['security_protocol'] == 'TLS'){
			$smtpSecure = PHPMailer::ENCRYPTION_STARTTLS;
		}
		$this->setMail = new PHPMailer();
		$this->setMail->SMTPDebug 	= 0;
		$this->setMail->isSMTP();
		$this->setMail->SMTPAuth 	= true;
		$this->setMail->Host 		= $data['outgoing_mail_server'];
		$this->setMail->Port 		= $data['outgoing_mail_server_port'] ? $data['outgoing_mail_server_port'] : 587;
		$this->setMail->Username 	= $data['outgoing_user_name'];
		$this->setMail->Password 	= $data['outgoing_password'];
		$this->setMail->SMTPSecure 	= $smtpSecure;
		if ($data['outgoing_mail_server'] == 'smtp.gmail.com') {
			$this->setMail->SMTPAutoTLS  = true;
			$this->setMail->SMTPSecure =  true;
		}
		$this->setMail->SMTPOptions = array(
			'ssl' => array(
				'verify_peer' => ($data['outgoing_enable_SSL'] == 1) ? true : false,
				'verify_peer_name' => ($data['outgoing_enable_SSL'] == 1) ? true : false, 'allow_self_signed' => true,
			),
		);
		$this->setMail->isHTML(true);
		$this->setMail->setFrom($data['outgoing_user_name']);
		if ($checkcon == 1) {			
		$this->setMail->addAddress($data['outgoing_user_name']);		
		$this->setMail->Subject = "test";
		$this->setMail->Body    = "test";
		if ($this->setMail->send()) {
			$email_sent = true;
			$email_sent_msg = 'Outgoing email tested successfully.';
			return (array('success' => true, 'message' => $email_sent_msg));
		} else {
			$email_sent = false;
			$email_sent_msg = " Email could not be sent. Mailer Error: {$this->setMail->ErrorInfo}";
			return (array('success' => false, 'message' => $email_sent_msg));
		}
		}
	}

	function setIncommingConfiguration($data, $checkcon = 0)
	{		
		if ((empty($data['from_email']) && $checkcon == 0) || 
		empty($data['incoming_user_name']) || 
		empty($data['incoming_password']) || 
		empty($data['incoming_mail_server']) || 
		empty($data['incoming_mail_server_port'])) {
			return (array('success' => false, 'message' => 'Please Provide Imap details to test!!'));
		}
		if(($data['incoming_enable_SSL'])){

			$mailbox = "{" . $data['incoming_mail_server'] . ":" . $data['incoming_mail_server_port'] . "/imap/ssl}INBOX";
		}else{
			$mailbox = "{" . $data['incoming_mail_server'] . ":" . $data['incoming_mail_server_port'] . "/imap}INBOX";
		}
		$username = $data['incoming_user_name'];
		$password = $data['incoming_password'];

		$imap = @imap_open($mailbox, $username, $password);
		if ($imap) {
			
			imap_close($imap);
			return array('success' => true, 'message' => 'IMAP connection successful.');
		} else {
			$errors = imap_errors();
			if ($errors) {
				foreach ($errors as $error) {
					error_log("IMAP Error: " . $error);
				}
			}
			$error_message = imap_last_error();	
			error_log("IMAP Authentication Failed for user: $username. Error: $error_message");
        
			// return array('success' => false, 'message' => 'IMAP connection failed: ' . $error_message);		
			return array('success' => false, 'message' => 'IMAP connection failed: ' . $error_message);
		}
	}

	public function companysmtpsetup($post,$checkcon = 0){

		$this->setMail = new PHPMailer();
		$this->setMail->SMTPDebug 	= 0;
		$this->setMail->isSMTP();
    $this->setMail->Host = $post['smtp_email_server'];
    $this->setMail->SMTPAuth = true;
    $this->setMail->Username = $post['smtp_email'];
    $this->setMail->Password = $post['smtp_password'];
    $this->setMail->SMTPSecure = 'smtp'; // Use TLS encryption, you can change to 'ssl' if needed
    $this->setMail->Port = $post['smtp_port'];; // Port for TLS, change to 465 for SSL
	$this->setMail->Timeout = 30;

    // Set the "from" address and name
    $this->setMail->setFrom($post['smtp_email'], "name");

    // Set the recipient's email address
    $this->setMail->addAddress($post['smtp_email']);
	
	$this->setMail->Subject = "test";
	$this->setMail->Body    = "test";
	if ($this->setMail->send()) {
		$email_sent = true;
		$email_sent_msg = 'This configuration is correct!';
		return (array('success' => true, 'message' => $email_sent_msg));
	} else {
		$email_sent = false;
		$email_sent_msg = " Email could not be sent. Mailer Error: {$this->setMail->ErrorInfo}";
		return (array('success' => false, 'message' => $email_sent_msg));
	}
	}


	public function sendOtp($post,$otp,$smtp){

		$this->setMail = new PHPMailer();
		$this->setMail->isSMTP();
    $this->setMail->Host = $smtp['smtp_email_server']; // Set your SMTP server
    $this->setMail->SMTPAuth = true;
    $this->setMail->Username = $smtp['smtp_email']; // Set your SMTP username
    $this->setMail->Password = $smtp['smtp_password']; // Set your SMTP password
    $this->setMail->SMTPSecure = 'smtp'; // Use TLS encryption, you can change to 'ssl' if needed
    $this->setMail->Port = $smtp['smtp_port'];; // Port for TLS, change to 465 for SSL

    // Set the "from" address and name
    $this->setMail->setFrom($smtp['smtp_email'], $smtp['name']);

    // Set the recipient's email address
    $this->setMail->addAddress($post['reset_email']);

    // Email subject and message
    $this->setMail->Subject = 'Password Change OTP';
    $this->setMail->Body = 'Your OTP for changing the password is: ' . $otp;
    if ($this->setMail->send()) {
        return 'OTP sent successfully.';
    } else {
        return 'Failed to send OTP: ' . $this->setMail->ErrorInfo;
    }
	}

	public function sendEmail($data, $isHtml = true)
	{
		if (empty($data['from_email']) || empty($data['outgoing_user_name']) || empty($data['outgoing_password']) || empty($data['outgoing_mail_server']) || empty($data['outgoing_mail_server_port'])) {
			return (array('success' => false, 'message' => ' Please Provide SMTP  to send email!!'));
		}
		$email_sent = false;
		$email_sent_msg = '';
		$sendTo = array();
		$sendToName = array();
		$emailSmsArrayLog = array();
		try {
			$this->setSenderConfiguration($data);
			if (!$this->setMail) {
				throw new Exception('Error in Email Configuration');
			} else {
				//To
				$send_to = explode(',', $data['to_email']);
				if ($data['to_email'] == '' || count($send_to) < 1) {
					echo json_encode(array('success' => FALSE, 'message' => ' Please provide at least one receiptant!!'));
					return;
				}

				foreach ($send_to as $key => $value) {
					$this->setMail->addAddress(strtolower(trim($value)));
				}

				//ccTo
				$allCC = explode(',', $data['cc_email']);
				if (count($allCC) > 0 && $allCC[0] != '') {
					foreach ($allCC as $key => $val) {
						if ($val != '')
							$this->setMail->addCC(trim($val));
					}
				}

				//bccTo
				$allBCC = explode(',', $data['bcc_email']);
				if (count($allBCC) > 0 && $allBCC[0] != '') {
					foreach ($allBCC as $key => $val) {
						if ($val != '')
							$this->setMail->addBCC(trim($val));
					}
				}
				$this->setMail->isHTML($isHtml);
				$this->setMail->Subject = !empty($data['subject']) ? $data['subject'] : '';
				$this->setMail->Body    = !empty($data['body']) ? $data['body'] : '';

				if ($this->setMail->send()) {
					$email_sent = true;
					$email_sent_msg = ' Email sent successfully';
					return (array('success' => true, 'message' => $email_sent_msg));
				} else {
					$email_sent = false;
					$email_sent_msg = " Email could not be sent. Mailer Error: {$this->setMail->ErrorInfo}";
					return (array('success' => false, 'message' => $email_sent_msg));
				}
			}
		} catch (Exception $e) {
			$email_sent = false;
			$email_sent_msg = " Email could not be sent. Error: " . $e->getMessage();
			return (array('success' => false, 'message' => $email_sent_msg));
		}

		// $emailSmsArrayLog[] = array(
		// 	'type'				=> TEMPLATE_TYPE_EMAIL,
		// 	'reference_name' 	=> $data['reference_name'],
		// 	'reference_id' 		=> $data['reference_id'],
		// 	'send_to' 			=> $email_data['receiver_detail'][0]['email_id'],
		// 	'send_to_name' 		=> $email_data['receiver_detail'][0]['name'],
		// 	'subject' 			=> $email_data['message_subject'],
		// 	'body' 				=> $email_data['message_body'],
		// 	'sent_by_user' 		=> !empty($this->CI->fx->clientId)?$this->CI->fx->clientId:NULL,
		// 	'response' 			=> strval($email_sent_msg)
		// );

		// if (count($emailSmsArrayLog) > 0) {
		// 	$this->CI->load->model('Acc_Model');
		// 	$this->CI->Acc_Model->createMultiEmailSmsLogs($emailSmsArrayLog);
		// }
		return $email_sent;
	}

	// function sendSMS($messageBody, $mobile, $data, $is_sms = false, $is_whatsapp = false)
	// {
	// 	try {
	// 		if ($is_sms == false && $is_whatsapp == false) {
	// 			return (array('success' => false, 'message' => "Please select atleast one medium"));
	// 		}
	// 		$responseMsg = "";
	// 		$msg = str_replace(array("&nbsp;", " ", "'"), array(' ', ' ', '`'), $messageBody);
	// 		$msg = str_replace(array('  '), array(' '), preg_replace('/[^A-Za-z0-9\<>?|_.:*#&$!(){;"%-+`}@=,\n\/ ]/', '', $msg));
	// 		$mobileArray = explode(',', $mobile);

	// 		$emailSmsArrayLog = array();
	// 		$urlArray = array();

	// 		if ($is_sms == TRUE && $this->compDtls->sms_api != '') {
	// 			$urlArray[$this->compDtls->sms_api] = array('type' => TEMPLATE_TYPE_SMS);
	// 		} else if ($is_sms == true) {
	// 			return (array('success' => false, 'message' => "SMS Api not configured!!"));
	// 		}

	// 		if ($is_whatsapp == TRUE && $this->compDtls->whatsapp_api != '') {
	// 			$urlArray[$this->compDtls->whatsapp_api] = array('type' => TEMPLATE_TYPE_WHATSAPP);
	// 		} else if ($is_whatsapp == TRUE) {
	// 			return (array('success' => false, 'message' => "Whatsapp Api not configured!!"));
	// 		}

	// 		foreach ($urlArray as $comp_url => $urlData) {
	// 			foreach ($mobileArray as $key => $mobile) {
	// 				if (strlen($mobile) != 10 || !is_numeric($mobile)) {
	// 					$responseMsg .= "Mobile Number ($mobile) should be of 10 digits only <br>";
	// 					continue;
	// 				}
	// 				$ch = curl_init();
	// 				$msg1 = curl_escape($ch, $msg);
	// 				$url = str_replace(array('{0}', '{1}'), array($mobile, $msg1), $comp_url);

	// 				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	// 				curl_setopt($ch, CURLOPT_URL, $url);
	// 				curl_setopt($ch, CURLOPT_TIMEOUT, 60);
	// 				curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	// 				curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

	// 				$curl_error = curl_error($ch);
	// 				$response = curl_exec($ch);

	// 				$http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	// 				curl_close($ch);

	// 				if (!empty($curl_error)) {
	// 					$responseMsg .= 'API Error : ' . $curl_error . "<br>";
	// 					continue;
	// 				}
	// 				if ($http_status != 200) {
	// 					$responseMsg .= 'API Error Not getting 200 Status code: ' . strval($response) . "<br>";
	// 					continue;
	// 				}
	// 				$emailSmsArrayLog[] = array(
	// 					'type'				=> $urlData['type'],
	// 					'reference_name'	=> $data['reference_name'],
	// 					'reference_id'		=> $data['reference_id'],
	// 					'send_to'			=> $mobile,
	// 					'send_to_name'		=> $data['sent_to_name'],
	// 					'subject'			=> NULL,
	// 					'body'				=> $messageBody,
	// 					'sent_by_user'		=> !empty($this->CI->fx->clientId) ? $this->CI->fx->clientId : NULL,
	// 					'response'			=> strval($response)
	// 				);
	// 			}
	// 		}

	// 		if (count($emailSmsArrayLog) > 0)
	// 			$this->CI->Acc_Model->createMultiEmailSmsLogs($emailSmsArrayLog);

	// 		if ($responseMsg != '') {
	// 			return array('success' => false, 'message' => $responseMsg);
	// 		}
	// 		return (array('success' => true, 'message' => 'Message sent successfully'));
	// 	} catch (Exception $e) {
	// 		return (array('success' => false, 'message' => $e->getMessage()));
	// 	}
	// }
}
