<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * Mailer — SMTP / notification wrapper around CI's Email library.
 * Provides branded HTML emails for auto-responses and admin alerts.
 *
 * Email delivery is configured from Admin > Settings (the "email" group).
 * If SMTP is not configured, it falls back to PHP mail(). Email failures
 * are logged but NEVER fatal — a failed email must not break a form submit.
 */
#[\AllowDynamicProperties]
class Mailer {

	protected $CI;

	public function __construct()
	{
		$this->CI =& get_instance();
		$this->CI->load->library('email');
	}

	/**
	 * Build the CI email config from saved settings.
	 *
	 * Settings keys (all optional) under the "email" group:
	 *   mail_protocol   'smtp' | 'mail' | 'sendmail'   (default 'mail')
	 *   smtp_host       e.g. mail.bloomiris.com
	 *   smtp_user       full mailbox address
	 *   smtp_pass       mailbox password
	 *   smtp_port       587 (TLS) or 465 (SSL)
	 *   smtp_crypto     'tls' | 'ssl' | ''
	 */
	protected function config()
	{
		$protocol = setting('mail_protocol', 'mail');
		$host     = setting('smtp_host', '');

		// If SMTP is selected but no host is set, fall back to mail().
		if ($protocol === 'smtp' && $host === '')
		{
			$protocol = 'mail';
		}

		$config = array(
			'protocol'    => $protocol,
			'mailtype'    => 'html',
			'charset'     => 'utf-8',
			'newline'     => "\r\n",
			'crlf'        => "\r\n",
			'wordwrap'    => TRUE,
			'validate'    => TRUE,
		);

		if ($protocol === 'smtp')
		{
			$config['smtp_host']    = $host;
			$config['smtp_user']    = setting('smtp_user', '');
			$config['smtp_pass']    = setting('smtp_pass', '');
			$config['smtp_port']    = (int) (setting('smtp_port', '587'));
			$config['smtp_crypto']  = setting('smtp_crypto', 'tls');
			$config['smtp_timeout'] = 10;
		}

		return $config;
	}

	/**
	 * Send a branded HTML email.
	 * Returns TRUE on success; failures are logged but never fatal.
	 */
	public function send($to, $subject, $heading, $body_html)
	{
		// A missing or malformed recipient should not cause an error.
		if (empty($to) || ! filter_var($to, FILTER_VALIDATE_EMAIL))
		{
			log_message('error', 'Mailer: invalid recipient "'.$to.'"');
			return FALSE;
		}

		$from_email = setting('email', 'hello@bloomiris.com');
		$from_name  = setting('site_name', 'Bloom Iris Agency');

		try
		{
			$this->CI->email->clear(TRUE);
			$this->CI->email->initialize($this->config());
			$this->CI->email->from($from_email, $from_name);
			$this->CI->email->to($to);
			$this->CI->email->subject($subject);
			$this->CI->email->message($this->wrap($heading, $body_html));

			if ( ! $this->CI->email->send(FALSE))
			{
				log_message('error', 'Mailer failed: '
					.$this->CI->email->print_debugger(array('headers')));
				return FALSE;
			}
			return TRUE;
		}
		catch (\Throwable $e)
		{
			// Never let an email problem bubble up as a fatal error.
			log_message('error', 'Mailer exception: '.$e->getMessage());
			return FALSE;
		}
	}

	/** Notify the agency inbox of a new submission. */
	public function notify_admin($subject, $heading, $body_html)
	{
		$to = setting('email', 'hello@bloomiris.com');
		return $this->send($to, $subject, $heading, $body_html);
	}

	/** Wrap content in the branded HTML email shell. */
	protected function wrap($heading, $body_html)
	{
		$brand  = setting('site_name', 'Bloom Iris Agency');
		$plum   = '#631A6C';
		$accent = '#B45F9A';
		$year   = date('Y');

		return '
<!DOCTYPE html>
<html><head><meta charset="utf-8"></head>
<body style="margin:0;padding:0;background:#f4eef2;font-family:Arial,Helvetica,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#f4eef2;padding:32px 0;">
    <tr><td align="center">
      <table width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:14px;overflow:hidden;">
        <tr><td style="background:linear-gradient(135deg,'.$plum.','.$accent.');padding:28px 32px;">
          <span style="color:#ffffff;font-size:20px;font-weight:bold;letter-spacing:.5px;">'.$brand.'</span>
        </td></tr>
        <tr><td style="padding:32px;">
          <h2 style="margin:0 0 16px;color:'.$plum.';font-size:20px;">'.$heading.'</h2>
          <div style="color:#3a3340;font-size:15px;line-height:1.65;">'.$body_html.'</div>
        </td></tr>
        <tr><td style="padding:20px 32px;background:#faf6f9;border-top:1px solid #eee;">
          <span style="color:#9a8fa3;font-size:12px;">&copy; '.$year.' '.$brand.'. All rights reserved.</span>
        </td></tr>
      </table>
    </td></tr>
  </table>
</body></html>';
	}
}
