<?php
/*
To use this new method of phpmailer follow the following steps on ubuntu:
Step 1: Install Composer
	$	sudo apt update
		sudo apt install php-cli unzip

	$	cd ~
	$	curl -sS https://getcomposer.org/installer -o /tmp/composer-setup.php

	$	HASH=`curl -sS https://composer.github.io/installer.sig`

	$	php -r "if (hash_file('SHA384', '/tmp/composer-setup.php') === '$HASH') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;"
			Output: Installer verified
		Note: If the output says Installer corrupt, you’ll need to repeat the download and verification process until you have a verified installer.

	*   The following command will download and install Composer as a system-wide command named composer, under /usr/local/bin:
	$	sudo php /tmp/composer-setup.php --install-dir=/usr/local/bin --filename=composer

	Output
	All settings correct for using Composer
	Downloading...

	Composer (version 2.3.5) successfully installed to: /usr/local/bin/composer
	Use it: php /usr/local/bin/composer

	To test your installation, run:

	$	composer

Step 2: Go to your website root directory and Run the following command

	$ 	composer require phpmailer/phpmailer
*/
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);

require_once __DIR__ . '/EnvLoader.php';

use PHPMailer\PHPMailer\PHPMailer;

class Communicator
{

	private $host;
	private $userName;
	private $password;
	private $port;
	private $encryption;
	public $from_email;
	public $from_name;
	public $replyTo;
	public $tempVar = "";
	public $charSet = "UTF-8";
	public $charSetOpt = 0;

	// Encryption setup (must match APIs/emailSettings.php)
	private const ENCRYPTION_KEY = 'madrasa_email_secret_key_2026';
	private const ENCRYPTION_METHOD = 'aes-256-cbc';

	private function decrypt_password($encrypted_full)
	{
		if (empty($encrypted_full))
			return '';
		$data = base64_decode($encrypted_full);
		$iv_length = openssl_cipher_iv_length(self::ENCRYPTION_METHOD);
		$iv = substr($data, 0, $iv_length);
		$encrypted = substr($data, $iv_length);
		return openssl_decrypt($encrypted, self::ENCRYPTION_METHOD, self::ENCRYPTION_KEY, 0, $iv);
	}

	/**
	 * Constructor - Load email configuration from Database
	 */
	public function __construct()
	{
		$this->loadConfig();
	}

	private function loadConfig()
	{
		require_once __DIR__ . '/DbPathsArray.php';
		require_once __DIR__ . '/App_DB.php';

		$db = new App_DB(DBU::$dba_user);

		// 1. Get default mailer type
		$config_res = $db->getRecordSet("SELECT default_mailer_type FROM config LIMIT 1");
		$default_type = !empty($config_res) ? $config_res[0]['default_mailer_type'] : 'gmail';

		// 2. Fetch appropriate account
		$account = null;
		if ($default_type === 'personal') {
			$acc_res = $db->getRecordSet("SELECT * FROM email_config WHERE account_type = 'personal' LIMIT 1");
			if (!empty($acc_res))
				$account = $acc_res[0];
		}

		// If personal not found or type is gmail, pick random gmail
		if (!$account) {
			$acc_res = $db->getRecordSet("SELECT * FROM email_config WHERE account_type = 'gmail'");
			if (!empty($acc_res)) {
				$account = $acc_res[array_rand($acc_res)];
			}
		}

		if ($account) {
			$this->host = $account['smtp_host'];
			$this->userName = $account['email_user'];
			$this->password = $this->decrypt_password($account['email_pass']);
			$this->port = $account['smtp_port'];
			$this->encryption = $account['encryption'];
			$this->from_email = $account['email_from'];
			$this->from_name = EnvLoader::get('MAIL_FROM_NAME', 'ESDN'); // Fallback to name from env
			$this->replyTo = $account['reply_to'];
		} else {
			// Legacy/Fallback to .env
			$this->host = EnvLoader::get('MAIL_HOST', 'premium155.web-hosting.com');
			$this->userName = EnvLoader::get('MAIL_USERNAME', 'info@esdn.com.pk');
			$this->password = EnvLoader::get('MAIL_PASSWORD', '');
			$this->from_email = EnvLoader::get('MAIL_FROM_ADDRESS', 'info@esdn.com.pk');
			$this->from_name = EnvLoader::get('MAIL_FROM_NAME', 'ESDN');
			$this->replyTo = $this->from_email;
			$this->port = 465;
			$this->encryption = 'ssl';
		}
	}

	//for multiple/single recipient(s) and from random robots
	public function sendEmailRnd($to = array(), $sender_name = "", $subject = '', $body = '', $attachement_path = "", $cc = "", $bcc = "")
	{
		require_once __DIR__ . '/vendor/autoload.php';
		$mail = new PHPMailer;
		$mail->IsSMTP();
		$mail->Host = $this->host;
		$mail->SMTPAuth = true;
		$mail->Username = $this->userName;
		$mail->Password = $this->password;
		$mail->Port = $this->port;
		$mail->SMTPSecure = $this->encryption;
		$mail->CharSet = $this->charSet;

		$mail->From = $this->from_email;
		$mail->FromName = !empty($sender_name) ? $sender_name : $this->from_name;

		foreach ($to as $value) {
			$mail->addAddress($value);
		}
		if (isset($bcc) && !empty($bcc)) {
			$mail->addBCC($bcc);
		}
		if (isset($cc) && !empty($cc)) {
			$mail->addCC($cc);
		}
		$mail->addReplyTo($this->replyTo);
		$mail->WordWrap = 50;
		if (isset($attachement_path) && !empty($attachement_path)) {
			$mail->AddAttachment($attachement_path);
		}
		$mail->isHTML(true);
		$mail->Subject = $subject;
		$mail->Body = $body;

		if (!$mail->send()) {
			$this->tempVar = $mail->ErrorInfo;
			return false;
		} else {
			return true;
		}
	}


}
