<?php
// includes/functions/emails/loader.php
if (!defined('ABSPATH')) exit;

require_once AFB_PLUGIN_DIR . 'includes/functions/emails/helpers.php';
require_once AFB_PLUGIN_DIR . 'includes/functions/emails/mailer.php';
require_once AFB_PLUGIN_DIR . 'includes/functions/emails/registry.php';

// Locate an email template across old/new locations
if (!function_exists('afb_email_locate_template')) {
    function afb_email_locate_template($basename) {
        $candidates = [
            AFB_PLUGIN_DIR . 'includes/functions/emails/templates/' . $basename, // new
            AFB_PLUGIN_DIR . 'admin/emails/' . $basename,                        // legacy
            AFB_PLUGIN_DIR . 'emails/' . $basename,                              // ad-hoc
        ];
        foreach ($candidates as $p) {
            if (file_exists($p)) return $p;
        }
        return '';
    }
}

/**
 * Register built-in emails here. You can add more via:
 *   afb_register_email('slug', [...]) or the filter at the bottom.
 */
add_action('init', function () {

    // ─────────────────────────────────────────────────────────────
    // A) Client Gateway “created” email
    // ─────────────────────────────────────────────────────────────
    afb_register_email('client_gateway.created', [
        'enabled_option' => 'afb_cg_email_enabled', // '1' to enable

        // Defaults (overridable per-send or via *_option)
        'from_name_option'  => 'afb_cg_email_from_name',
        'from_email_option' => 'afb_cg_email_from_email',
        'reply_to_option'   => 'afb_cg_email_reply_to',
        'cc_option'         => 'afb_cg_email_cc',
        'bcc_option'        => 'afb_cg_email_bcc',

        // Targeting: use 'to' if provided, else submitter_email
        'to' => function ($vars) {
            if (!empty($vars['to'])) return $vars['to'];
            if (!empty($vars['submitter_email'])) return $vars['submitter_email'];
            return [];
        },

        // Subject
        'subject' => function ($v) {
            $job = $v['job_number'] ?? '';
            return $job ? "Your Client Gateway link – {$job}" : "Your Client Gateway link";
        },

        // HTML body
        'html' => function ($v) {
            $name = esc_html($v['submitter_name'] ?? '');
            $url  = esc_url($v['gateway_url'] ?? '#');
            $task = esc_html($v['task_name'] ?? '');
            $job  = esc_html($v['job_number'] ?? '');
            ob_start(); ?>
                <div style="font-family:system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;line-height:1.5;color:#0f172a">
                  <p>Hi <?= $name ?: 'there' ?>,</p>
                  <p>Your Client Gateway link<?= $job ? " for <strong>{$job}</strong>" : '' ?><?= $task ? " (<em>{$task}</em>)" : '' ?> is ready:</p>
                  <p><a href="<?= $url ?>" style="display:inline-block;padding:10px 14px;background:#0ea5e9;color:#fff;text-decoration:none;border-radius:8px">Open Client Gateway</a></p>
                  <p>If the button doesn’t work, copy &amp; paste this URL:<br><code><?= $url ?></code></p>
                  <hr style="border:none;border-top:1px solid #e2e8f0;margin:20px 0" />
                  <p style="color:#475569;font-size:12px">This message was sent automatically.</p>
                </div>
            <?php return (string)ob_get_clean();
        },

        // Plain text (token replacement handled by mailer)
        'text' => "Your Client Gateway link is ready:\n{{gateway_url}}\n\n{{task_name}}\n{{job_number}}",

        'attachments' => function ($vars) { return []; },
    ]);

    // ─────────────────────────────────────────────────────────────
    // B) Submission confirmation to the requester
    // ─────────────────────────────────────────────────────────────
    afb_register_email('submission.received', [
        // Option-backed defaults (reuse existing option keys)
        'from_name_option'  => 'afb_email_from_name',
        'from_email_option' => 'afb_email_from_email',
        'reply_to_option'   => 'afb_email_reply_to',
        'cc_option'         => 'afb_email_cc',
        'bcc_option'        => 'afb_email_bcc',

        // Who to send to
        'to' => function ($v) { return $v['to'] ?? []; },

        // Subject from options with token replacement
        'subject' => function ($v) {
            $tpl  = get_option('afb_email_subject', 'Your request has been received');
            $vars = [
                'task_name'      => $v['task_name'] ?? 'Request',
                // Prefer job_number, then job_number_scb, then request_number
                'request_number' => ($v['job_number'] ?? '') ?: ($v['job_number_scb'] ?? '') ?: ($v['request_number'] ?? ''),
                'comms_link'     => $v['comms_link'] ?? '',
                'fields_html'    => $v['fields_html'] ?? '',
            ];
            return afb_email_token_replace($tpl, $vars);
        },

        // HTML body: try template file, otherwise fallback to option
        'html' => function ($v) {
            $vars = [
                'task_name'      => $v['task_name'] ?? 'Request',
                'request_number' => ($v['job_number'] ?? '') ?: ($v['job_number_scb'] ?? '') ?: ($v['request_number'] ?? ''),
                'comms_link'     => $v['comms_link'] ?? '',
                'fields_html'    => $v['fields_html'] ?? '',
            ];
            if (function_exists('afb_filter_fields_for_email_hardcoded')) {
                $vars['fields_html'] = afb_filter_fields_for_email_hardcoded($vars['fields_html']);
            }

            // Prefer new template location; fall back to legacy paths
            $tpl_file = afb_email_locate_template('submission-template.php');
            if ($tpl_file) {
                ob_start();
                extract($vars, EXTR_SKIP);
                include $tpl_file;
                $html = (string) ob_get_clean();
                if (trim($html) !== '') return $html;
            }

            // Fallback to option copy
            $body_tpl = get_option('afb_email_body', 'Thanks for submitting your request. You can follow it here: {{comms_link}}');
            return afb_email_token_replace($body_tpl, $vars);
        },

        // Attachments passthrough
        'attachments' => function ($v) {
            return !empty($v['attachments']) && is_array($v['attachments']) ? $v['attachments'] : [];
        },
    ]);

    // Allow themes/plugins to register more emails
    $extra = apply_filters('afb/email/register', []);
    if (is_array($extra)) {
        foreach ($extra as $slug => $cfg) afb_register_email($slug, $cfg);
    }
});
