<?php
// includes/email-sender.php
if (!defined('ABSPATH')) exit;

if (!function_exists('afb_get_email_headers')) {
	function afb_get_email_headers($include_cc_bcc = false) {
		$headers = [
			'Content-Type: text/html; charset=UTF-8',
			'X-Mailer: Asana Form Builder',
		];

		$reply_to = sanitize_email(get_option('afb_email_reply_to', get_option('admin_email')));
		if (is_email($reply_to)) {
			$headers[] = "Reply-To: {$reply_to}";
		}

		if ($include_cc_bcc) {
			if ($cc = get_option('afb_email_cc')) {
				$headers[] = "Cc: {$cc}";
			}
			if ($bcc = get_option('afb_email_bcc')) {
				$headers[] = "Bcc: {$bcc}";
			}
		}

		return $headers;
	}
}

if (!function_exists('afb_email_expand_placeholders')) {
	/**
	 * Replace supported email placeholders in both modern and legacy forms.
	 * Supports: {{token}} and {token}
	 */
	function afb_email_expand_placeholders($template, array $tokens = []) {
		$template = (string) $template;
		if ($template === '' || empty($tokens)) {
			return $template;
		}

		$map = [];
		foreach ($tokens as $key => $value) {
			$token_key = trim((string) $key);
			if ($token_key === '') {
				continue;
			}

			$token_key = trim($token_key, "{} \t\n\r\0\x0B");
			if ($token_key === '') {
				continue;
			}

			$token_value = is_scalar($value) ? (string) $value : '';
			$map['{{' . $token_key . '}}'] = $token_value;
			$map['{' . $token_key . '}'] = $token_value;
		}

		return strtr($template, $map);
	}
}

/* ─────────────────────────────────────────────────────────────
 * Gateway event notification email (comment / upload)
 * Sent to internal staff (collaborators / assignee)
 * ─────────────────────────────────────────────────────────── */
if ( ! function_exists( 'afb_send_gateway_notification_email' ) ) {
    function afb_send_gateway_notification_email( $args ) {
        $to          = sanitize_email( $args['to'] ?? '' );
        $name        = sanitize_text_field( $args['name'] ?? '' );
        $event       = sanitize_text_field( $args['event'] ?? 'comment' ); // 'comment' | 'upload'
        $task_name   = sanitize_text_field( $args['task_name'] ?? '' );
        $gateway_url = esc_url_raw( $args['gateway_url'] ?? '' );
        $actor_name  = sanitize_text_field( $args['actor_name'] ?? '' );
        $actor_email = sanitize_email( $args['actor_email'] ?? '' );
        $comment_txt = sanitize_textarea_field( $args['comment'] ?? '' );
        $filename    = sanitize_text_field( $args['filename'] ?? '' );

		if ( ! is_email( $to ) || ! $gateway_url ) {
			afb_debug_log( sprintf(
				'❌ Gateway email aborted: invalid params | to=%s gateway_url=%s event=%s',
				$to,
				$gateway_url,
				$event
			) );
			return false;
		}

		$is_comment    = ( $event === 'comment' );
		$actor_display = $actor_name ?: ( $actor_email ?: 'A client' );
		$event_label   = $is_comment ? 'left a comment' : 'uploaded a file';

		$subject_key     = $is_comment ? 'afb_gateway_comment_email_subject' : 'afb_gateway_upload_email_subject';
		$body_key        = $is_comment ? 'afb_gateway_comment_email_body' : 'afb_gateway_upload_email_body';
		$subject_default = $is_comment
			? 'New comment on: {{task_name}}'
			: 'New file uploaded to: {{task_name}}';
		$body_default = $is_comment
			? '<p style="font-size:.9375rem;color:#1e293b;margin:0 0 .75rem">Hi {{recipient_name}},</p>'
				. '<p style="font-size:.9375rem;color:#334155;margin:0 0 .25rem"><strong>{{actor_name}}</strong> has left a comment on the request above{{actor_email_suffix}}.</p>'
				. '{{event_detail_html}}'
				. '<p style="margin:1.75rem 0 0">{{gateway_button_html}}</p>'
			: '<p style="font-size:.9375rem;color:#1e293b;margin:0 0 .75rem">Hi {{recipient_name}},</p>'
				. '<p style="font-size:.9375rem;color:#334155;margin:0 0 .25rem"><strong>{{actor_name}}</strong> uploaded a file on the request above{{actor_email_suffix}}.</p>'
				. '{{event_detail_html}}'
				. '<p style="margin:1.75rem 0 0">{{gateway_button_html}}</p>';

		$detail_html = '';
		if ( $is_comment && $comment_txt !== '' ) {
			$detail_html = '<div style="margin:1rem 0;padding:1rem 1.25rem;background:#f8fafc;border-left:3px solid #003087;border-radius:0 .375rem .375rem 0;font-size:.875rem;color:#334155;line-height:1.6">'
				. nl2br( esc_html( $comment_txt ) )
				. '</div>';
		}
		if ( ! $is_comment && $filename !== '' ) {
			$detail_html = '<p style="font-size:.875rem;color:#334155;margin:.75rem 0;padding:.625rem 1rem;background:#f0f9ff;border-radius:.375rem">'
				. '📎 <strong>' . esc_html( $filename ) . '</strong></p>';
		}

		$gateway_button_html = '<a href="' . esc_url( $gateway_url ) . '" style="display:inline-block;background:#003087;color:#fff;text-decoration:none;padding:.625rem 1.375rem;border-radius:.5rem;font-size:.875rem;font-weight:600">View Client Gateway &rarr;</a>';

		$subject_tokens = [
			'recipient_name' => ( $name ?: 'there' ),
			'task_name'      => $task_name,
			'actor_name'     => $actor_display,
			'actor_email'    => $actor_email,
			'event_label'    => $event_label,
			'comment'        => $comment_txt,
			'filename'       => $filename,
			'gateway_url'    => $gateway_url,
		];

		$subject_tpl = (string) get_option( $subject_key, $subject_default );
		if ( trim( $subject_tpl ) === '' ) {
			$subject_tpl = $subject_default;
		}
		$subject = sanitize_text_field( afb_email_expand_placeholders( $subject_tpl, $subject_tokens ) );
		if ( $subject === '' ) {
			$subject = sanitize_text_field( afb_email_expand_placeholders( $subject_default, $subject_tokens ) );
		}

		$actor_email_suffix = $actor_email
			? ' <span style="color:#64748b;font-size:.875rem">(' . esc_html( $actor_email ) . ')</span>'
			: '';

		$body_tokens = [
			'recipient_name'    => esc_html( $name ?: 'there' ),
			'task_name'         => esc_html( $task_name ),
			'actor_name'        => esc_html( $actor_display ),
			'actor_email'       => esc_html( $actor_email ),
			'actor_email_suffix' => $actor_email_suffix,
			'event_label'       => esc_html( $event_label ),
			'comment'           => nl2br( esc_html( $comment_txt ) ),
			'filename'          => esc_html( $filename ),
			'gateway_url'       => esc_url( $gateway_url ),
			'event_detail_html' => $detail_html,
			'gateway_button_html' => $gateway_button_html,
		];

		$body_tpl = (string) get_option( $body_key, $body_default );
		if ( trim( $body_tpl ) === '' ) {
			$body_tpl = $body_default;
		}
		$body_html = afb_email_expand_placeholders( $body_tpl, $body_tokens );

        $html  = '<!doctype html><html><body style="font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Helvetica,sans-serif;background:#f1f5f9;margin:0;padding:2rem 1rem">';
        $html .= '<div style="max-width:560px;margin:0 auto">';

		// Header (table + bgcolor for Outlook/email-client reliability)
		$html .= '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-collapse:collapse;background-color:#003087;" bgcolor="#003087">';
		$html .= '<tr><td style="padding:24px 32px;background-color:#003087;" bgcolor="#003087">';
		$html .= '<p style="color:#d6e0f5;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:1.6px;margin:0 0 6px;">Client Gateway &rsaquo; Notification</p>';
		$html .= '<h1 style="color:#ffffff;font-size:18px;font-weight:700;margin:0;line-height:1.3;">' . esc_html( $task_name ) . '</h1>';
		$html .= '</td></tr></table>';

        // Body
        $html .= '<div style="background:#fff;padding:1.75rem 2rem">';
		$html .= $body_html;
        $html .= '</div>';

        // Footer
        $html .= '<div style="background:#f8fafc;border-radius:0 0 .75rem .75rem;padding:.875rem 2rem;font-size:.75rem;color:#94a3b8">';
        $html .= 'You are receiving this because you are a collaborator on this request. Do not reply to this email.';
        $html .= '</div>';
        $html .= '</div></body></html>';

		$headers = afb_get_email_headers();

		$sent = wp_mail( $to, $subject, $html, $headers );

		if ( ! $sent ) {
			if ( isset( $GLOBALS['phpmailer'] ) && ! empty( $GLOBALS['phpmailer']->ErrorInfo ) ) {
				afb_debug_log( '❌ Gateway email wp_mail false – PHPMailer: ' . $GLOBALS['phpmailer']->ErrorInfo );
			} else {
				afb_debug_log( '❌ Gateway email wp_mail returned false with no PHPMailer error (to ' . $to . ')' );
			}
		} else {
			afb_debug_log( '✅ Gateway email accepted by wp_mail for ' . $to );
		}

		return $sent;
    }
}


function afb_filter_fields_for_email_hardcoded($fields_html) {
    $html = trim((string)$fields_html);
    if ($html === '') return $html;

    // Desired labels in final order (case-insensitive, parentheses ignored)
    $ORDER = ['job number','first name','last name','email address','request details'];

    // DOM load (tolerant)
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $loaded = $dom->loadHTML('<?xml encoding="utf-8" ?>'.$html, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
    libxml_clear_errors();
    if (!$loaded) return $html; // fallback

    // Find original <ul> (or create one if not present)
    $xpath = new DOMXPath($dom);
    $ul = $xpath->query('//ul')->item(0);
    if (!$ul) {
        $ul = $dom->createElement('ul');
        // wrap whole thing if they gave us naked <li>s
        foreach ($dom->getElementsByTagName('li') as $li) $ul->appendChild($li->cloneNode(true));
    }

    // Map existing <li>s by normalized label
    $bucket = [];
    foreach ($xpath->query('.//li', $ul) as $li) {
        // Expect <strong>Label:</strong> …
        $label = '';
        $strong = $xpath->query('.//strong', $li)->item(0);
        if ($strong) $label = trim(preg_replace('/:\s*$/','',$strong->textContent));
        if ($label === '') {
            // attempt: text before colon
            $txt = trim($li->textContent);
            $label = trim(strtok($txt, ':'));
        }
        $norm = strtolower(trim(preg_replace('/\s*\(.*?\)\s*/','',$label))); // drop (SCB) etc.
        if (in_array($norm, $ORDER, true)) {
            $bucket[$norm] = $li->cloneNode(true);
        }
    }

    // Rebuild a clean <ul> in desired order with only whitelisted items
    $new = $dom->createElement('ul');
    foreach ($ORDER as $key) {
        if (isset($bucket[$key])) $new->appendChild($bucket[$key]);
    }

    // Return outer HTML
    $tmp = new DOMDocument();
    $tmp->appendChild($tmp->importNode($new, true));
    return trim($tmp->saveHTML());
}


function afb_send_submission_email( $args ) {

	/* ─────────────────────────────────────────────
	 * 1. Parse + sanity-check
	 * ─────────────────────────────────────────── */
	$to            = sanitize_email( $args['to']             ?? '' );
	$task_name     = sanitize_text_field( $args['task_name'] ?? 'Request' );

	// Back-compat: original request_number (often a gid). We'll override with job number if present.
	$task_gid      = sanitize_text_field( $args['request_number'] ?? '' );

	// Prefer explicit job number; keep legacy key support for compatibility.
	$job_number = sanitize_text_field( $args['job_number'] ?? '' );
	if ($job_number !== '') {
		$task_gid = $job_number; // keep using $task_gid var so the rest of the function stays untouched
	}

	$comms_link    = esc_url_raw(       $args['comms_link']  ?? '' );
	$fields_html   = $args['fields_html'] ?? '';
	$attachments   = isset($args['attachments']) && is_array($args['attachments']) ? $args['attachments'] : [];
	$subject_template_override = sanitize_text_field((string) ($args['subject_template'] ?? ''));
	$body_template_override = wp_kses_post((string) ($args['body_template'] ?? ''));
	$template_tokens_raw = isset($args['template_tokens']) && is_array($args['template_tokens'])
		? $args['template_tokens']
		: [];
	$template_tokens = [];
	foreach ($template_tokens_raw as $token_key => $token_value) {
		$token_key = trim((string) $token_key);
		if ($token_key === '' || is_array($token_value) || is_object($token_value)) {
			continue;
		}

		$template_tokens[$token_key] = (string) $token_value;
	}
	$cc_emails_raw = isset($args['cc']) ? (array) $args['cc'] : [];
	$cc_emails = [];
	foreach ($cc_emails_raw as $cc_email_raw) {
		$cc_email = sanitize_email((string) $cc_email_raw);
		if (is_email($cc_email) && strcasecmp($cc_email, $to) !== 0) {
			$cc_emails[] = $cc_email;
		}
	}
	$cc_emails = array_values(array_unique($cc_emails));


	$debug = isset( $_GET['debug_email'] );

	if ( $debug ) {
		afb_debug_log(
			'[email:submission] attempt to=' . $to
			. ' task_name=' . $task_name
			. ' request_number=' . $task_gid
			. ' comms_link=' . $comms_link
		);
	}

	if ( ! is_email( $to ) ) {
		if ( $debug ) {
			afb_debug_log('[email:submission] invalid or missing recipient');
		}
		return false;
	}

	/* ─────────────────────────────────────────────
	 * 2. Subject + body (template or fallback)
	 * ─────────────────────────────────────────── */
	$subject_tpl = $subject_template_override !== ''
		? $subject_template_override
		: get_option( 'afb_email_subject', 'Your request has been received' );
	$body_tpl    = $body_template_override !== ''
		? $body_template_override
		: get_option( 'afb_email_body',    'Thanks for submitting your request. You can follow it here: {{comms_link}}' );

	$tokens = [
		'task_name'      => $task_name,
		'request_number' => $task_gid,
		'comms_link'     => $comms_link,
		'fields_html'    => $fields_html,
	];
	if (!empty($template_tokens)) {
		$tokens = array_merge($tokens, $template_tokens);
	}

	$subject       = afb_email_expand_placeholders( $subject_tpl, $tokens );
	$fallback_body = afb_email_expand_placeholders( $body_tpl, $tokens );
	$request_number = $task_gid;
	$email_template_tokens = $tokens;

	ob_start();
	include plugin_dir_path( __FILE__ ) . '../admin/emails/submission-template.php';
	$html_body = ob_get_clean();
	if ( empty( trim( $html_body ) ) ) {
		$html_body = $fallback_body;
		if ( $debug ) {
			afb_debug_log('[email:submission] using fallback body (template output empty)');
		}
	}

	if ( $debug ) {
		file_put_contents( WP_CONTENT_DIR . '/email-debug.html', $html_body );
	}

	/* ─────────────────────────────────────────────
	 * 3. Send
	 * ─────────────────────────────────────────── */
	$headers = afb_get_email_headers(true);
	if (!empty($cc_emails)) {
		$headers[] = 'Cc: ' . implode(', ', $cc_emails);
	}

	$sent = wp_mail( $to, $subject, $html_body, $headers, $attachments );


	/* Extra diagnostics when wp_mail returns false */
	if ( ! $sent ) {
		if ( isset( $GLOBALS['phpmailer'] ) && ! empty( $GLOBALS['phpmailer']->ErrorInfo ) ) {
			afb_debug_log( "❌ wp_mail false – PHPMailer: " . $GLOBALS['phpmailer']->ErrorInfo );
		} else {
			afb_debug_log( "❌ wp_mail returned false with no PHPMailer error (to {$to})" );
		}
	}

	if ( $debug ) {
		afb_debug_log(
			'[email:submission] subject=' . $subject
			. ' headers=' . wp_json_encode( $headers )
			. ' result=' . ( $sent ? 'success' : 'failed' )
		);
	}

	return $sent;
}


/**
 * Client Gateway Created Email
 * Template: /admin/emails/client-gateway-created.php
 *
 * Args:
 * - to (required)
 * - name
 * - task_name
 * - job_number
 * - gateway_url (required)
 * - task_gid
 * - attachments (array)
 */
if (!function_exists('afb_send_client_gateway_created_email')) {

	function afb_send_client_gateway_created_email($args) {

		$to          = sanitize_email($args['to'] ?? '');
		$name        = sanitize_text_field($args['name'] ?? '');
		$task_name   = sanitize_text_field($args['task_name'] ?? '');
		$task_gid    = sanitize_text_field($args['task_gid'] ?? '');

		// Accept either key name, keep it flexible
		$job_number  = sanitize_text_field($args['job_number'] ?? '');

		$gateway_url = esc_url_raw($args['gateway_url'] ?? '');
		$gateway_pin = sanitize_text_field($args['gateway_pin'] ?? '');
		$attachments = (isset($args['attachments']) && is_array($args['attachments'])) ? $args['attachments'] : [];
		$heading_override = sanitize_text_field($args['heading'] ?? '');
		$subject_template_override = (string)($args['subject_template'] ?? '');
		$body_template_override = (string)($args['body_template'] ?? '');

		$debug = isset($_GET['debug_email']);

		if ($debug) {
			afb_debug_log(
				'[email:client_gateway] attempt to=' . $to
				. ' name=' . $name
				. ' task_name=' . $task_name
				. ' job_number=' . $job_number
				. ' task_gid=' . $task_gid
				. ' gateway_url=' . $gateway_url
			);
		}

		if (!is_email($to) || $gateway_url === '') {
			if ($debug) {
				afb_debug_log('[email:client_gateway] invalid recipient or missing gateway_url');
			}
			return false;
		}

		$display_name = $name ?: 'there';
		$first_name = $display_name;
		if (preg_match('/^\S+/', trim($display_name), $m)) {
			$first_name = (string) $m[0];
		}
		$workspace_name = sanitize_text_field((string) get_bloginfo('name'));

		// Subject (supports placeholders and legacy single-brace aliases)
		$subject_tpl = trim($subject_template_override) !== ''
			? $subject_template_override
			: (string) get_option('afb_cg_email_subject', 'Client Gateway Created');
		$subject_tokens = [
			'task_name'      => $task_name,
			'job_number'     => $job_number,
			'request_number' => $job_number,
			'gateway_url'    => $gateway_url,
			'task_gid'       => $task_gid,
			'name'           => $display_name,
			'first_name'     => $first_name,
			'gateway_pin'    => $gateway_pin,
			'workspace_name' => $workspace_name,
		];
		$subject = afb_email_expand_placeholders($subject_tpl, $subject_tokens);

		// Render HTML via template
		$template = plugin_dir_path(__FILE__) . '../admin/emails/client-gateway-created.php';
		$html_body = '';

		if (file_exists($template)) {
			// Variables made available to template
			$submitter_name = $name; // optional alias
			$gateway_pin_template = $gateway_pin;
			$heading = $heading_override;
			$subject_template_override = $subject_tpl;
			$body_template_override = (string) $body_template_override;
			ob_start();
			include $template;
			$html_body = ob_get_clean();
		}

		// Fallback minimal body if template missing/empty
		if (empty(trim((string)$html_body))) {
			$html_body = '<p>Hi ' . esc_html($name ?: 'there') . ',</p>'
				. '<p>Your Client Gateway has been created.</p>'
				. '<p><a href="' . esc_url($gateway_url) . '">Open Client Gateway</a></p>';
			if ($debug) {
				afb_debug_log('[email:client_gateway] using fallback body (template output empty)');
			}
		}

		if ($debug) {
			file_put_contents(WP_CONTENT_DIR . '/email-debug-client-gateway.html', $html_body);
		}

		// Send (match your CC/BCC settings)
		$headers = afb_get_email_headers(true);

		$sent = wp_mail($to, $subject, $html_body, $headers, $attachments);

		if (!$sent) {
			if (isset($GLOBALS['phpmailer']) && !empty($GLOBALS['phpmailer']->ErrorInfo)) {
				afb_debug_log("❌ wp_mail false – PHPMailer: " . $GLOBALS['phpmailer']->ErrorInfo);
			} else {
				afb_debug_log("❌ wp_mail returned false with no PHPMailer error (to {$to})");
			}
		}

		if ($debug) {
			afb_debug_log(
				'[email:client_gateway] subject=' . $subject
				. ' headers=' . wp_json_encode($headers)
				. ' result=' . ($sent ? 'success' : 'failed')
			);
		}

		return $sent;
	}
}
