<?php

if (!defined('ABSPATH')) exit;

$email_test_user = wp_get_current_user();
$email_test_to_default = sanitize_email(is_object($email_test_user) ? ($email_test_user->user_email ?? '') : '');
if (!is_email($email_test_to_default)) {
  $email_test_to_default = sanitize_email((string) get_option('admin_email', ''));
}
$email_test_nonce = wp_create_nonce('afb_email_settings_test_nonce');

$submission_defaults = [
  'subject' => 'Your request has been received',
  'body'    => 'Thanks for submitting your request. You can follow it here: {{comms_link}}',
];

$client_gateway_defaults = [
  'subject' => 'Client Gateway Created',
  'body'    => '<p>Your Client Gateway has been created.</p><p>You can access it using the button below.</p>',
];

$client_gateway_completion_defaults = [
  'subject' => 'Request complete: {{task_name}}',
  'body'    => '<p>Hi {{first_name}},</p><p>Your request for "<strong>{{task_name}}</strong>" is now complete.</p><p>Please review the completed request and submit feedback using your Client Gateway below.</p>',
];

$gateway_comment_defaults = [
  'subject' => 'New comment on: {{task_name}}',
  'body'    => '<p>Hi {{recipient_name}},</p><p><strong>{{actor_name}}</strong> has left a comment on the request above{{actor_email_suffix}}.</p>{{event_detail_html}}<p>{{gateway_button_html}}</p>',
];

$gateway_upload_defaults = [
  'subject' => 'New file uploaded to: {{task_name}}',
  'body'    => '<p>Hi {{recipient_name}},</p><p><strong>{{actor_name}}</strong> uploaded a file on the request above{{actor_email_suffix}}.</p>{{event_detail_html}}<p>{{gateway_button_html}}</p>',
];

if (!function_exists('afb_render_email_template_editor')) {
  function afb_render_email_template_editor($option_name, $editor_id, $default, $rows = 8) {
    $value = get_option($option_name, $default);

    wp_editor(
      $value,
      $editor_id,
      [
        'textarea_name' => $option_name,
        'textarea_rows' => $rows,
        'media_buttons' => false,
        'tinymce'       => [
          'toolbar1' => 'bold italic underline | link unlink | bullist numlist | undo redo',
          'toolbar2' => '',
        ],
        'quicktags' => true,
      ]
    );
  }
}

if (!function_exists('afb_render_email_token_hint')) {
  function afb_render_email_token_hint(array $tokens) {
    $chunks = [];
    foreach ($tokens as $token) {
      $chunks[] = '<code>' . esc_html($token) . '</code>';
    }

    echo implode(', ', $chunks);
  }
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['afb_save_email_settings'])) {
  check_admin_referer('afb_save_email_settings');

  $text_options = [
    'afb_email_reply_to',
    'afb_email_cc',
    'afb_email_bcc',
    'afb_email_subject',
    'afb_cg_email_subject',
    'afb_cg_completion_email_subject',
    'afb_gateway_comment_email_subject',
    'afb_gateway_upload_email_subject',
  ];

  foreach ($text_options as $option_name) {
    update_option($option_name, sanitize_text_field($_POST[$option_name] ?? ''));
  }

  $html_options = [
    'afb_email_body',
    'afb_cg_email_body',
    'afb_cg_completion_email_body',
    'afb_gateway_comment_email_body',
    'afb_gateway_upload_email_body',
  ];

  foreach ($html_options as $option_name) {
    update_option($option_name, wp_kses_post($_POST[$option_name] ?? ''));
  }

  echo '<div class="notice notice-success is-dismissible"><p>Email settings saved.</p></div>';
}
?>

<div class="wrap">
  <h1>Email Notifications</h1>
  <p class="description" style="max-width:980px;">
    Manage every outbound email used in Asana Form Builder, including automatic submission copy emails and Client Gateway notifications.
  </p>

  <form method="post">
    <?php wp_nonce_field('afb_save_email_settings'); ?>

    <h2 class="title">Test Controls</h2>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb-email-test-recipient">Test Recipient</label></th>
        <td>
          <input
            type="email"
            id="afb-email-test-recipient"
            class="regular-text"
            value="<?= esc_attr($email_test_to_default) ?>"
            placeholder="name@example.com"
            autocomplete="email"
          />
          <p class="description">Each "Send Test" button uses this address. Save settings first so tests use your latest template edits.</p>
        </td>
      </tr>
    </table>

    <h2 class="title">Shared Headers</h2>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_email_reply_to">Reply-To Email</label></th>
        <td>
          <input
            name="afb_email_reply_to"
            type="email"
            id="afb_email_reply_to"
            value="<?= esc_attr(get_option('afb_email_reply_to', get_option('admin_email'))) ?>"
            class="regular-text"
          />
          <p class="description">Used in the Reply-To header for all plugin emails.</p>
        </td>
      </tr>
      <tr>
        <th scope="row"><label for="afb_email_cc">CC Recipients</label></th>
        <td>
          <input
            name="afb_email_cc"
            type="text"
            id="afb_email_cc"
            value="<?= esc_attr(get_option('afb_email_cc', '')) ?>"
            class="regular-text"
            placeholder="name@example.com, second@example.com"
          />
          <p class="description">Comma-separated list. Added to submission and client gateway created emails.</p>
        </td>
      </tr>
      <tr>
        <th scope="row"><label for="afb_email_bcc">BCC Recipients</label></th>
        <td>
          <input
            name="afb_email_bcc"
            type="text"
            id="afb_email_bcc"
            value="<?= esc_attr(get_option('afb_email_bcc', '')) ?>"
            class="regular-text"
            placeholder="name@example.com, second@example.com"
          />
          <p class="description">Comma-separated list. Added to submission and client gateway created emails.</p>
        </td>
      </tr>
    </table>

    <p style="margin:8px 0 24px;">
      <button
        type="button"
        class="button afb-email-test-btn"
        data-template="submission"
        data-status-id="afb-email-test-status-submission"
      >Send Test: Submission Copy Email</button>
      <span id="afb-email-test-status-submission" style="margin-left:10px;font-size:13px;color:#6b7280;"></span>
    </p>

    <hr />

    <h2 class="title">1. Submission Copy Email (Automatic)</h2>
    <p class="description">Sent automatically after a task is successfully submitted.</p>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_email_subject">Subject</label></th>
        <td>
          <input
            name="afb_email_subject"
            type="text"
            id="afb_email_subject"
            value="<?= esc_attr(get_option('afb_email_subject', $submission_defaults['subject'])) ?>"
            class="large-text"
          />
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{request_number}}', '{{comms_link}}', '{{fields_html}}']); ?>
          </p>
        </td>
      </tr>
      <tr>
        <th scope="row">Body</th>
        <td>
          <?php afb_render_email_template_editor('afb_email_body', 'afb_email_body_editor_submission', $submission_defaults['body'], 10); ?>
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{request_number}}', '{{comms_link}}', '{{fields_html}}']); ?>
          </p>
        </td>
      </tr>
    </table>

    <p style="margin:8px 0 24px;">
      <button
        type="button"
        class="button afb-email-test-btn"
        data-template="client_gateway_created"
        data-status-id="afb-email-test-status-cg-created"
      >Send Test: Client Gateway Created</button>
      <span id="afb-email-test-status-cg-created" style="margin-left:10px;font-size:13px;color:#6b7280;"></span>
    </p>

    <hr />

    <h2 class="title">2. Client Gateway Created Email (Automatic)</h2>
    <p class="description">Sent automatically to the submitter after a Client Gateway is created.</p>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_cg_email_subject">Subject</label></th>
        <td>
          <input
            name="afb_cg_email_subject"
            type="text"
            id="afb_cg_email_subject"
            value="<?= esc_attr(get_option('afb_cg_email_subject', $client_gateway_defaults['subject'])) ?>"
            class="large-text"
          />
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{job_number}}', '{{request_number}}', '{{gateway_url}}', '{{task_gid}}', '{{name}}', '{{first_name}}', '{{gateway_pin}}', '{{workspace_name}}']); ?>
          </p>
        </td>
      </tr>
      <tr>
        <th scope="row">Body</th>
        <td>
          <?php afb_render_email_template_editor('afb_cg_email_body', 'afb_cg_email_body_editor_gateway_created', $client_gateway_defaults['body'], 10); ?>
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{job_number}}', '{{request_number}}', '{{gateway_url}}', '{{task_gid}}', '{{name}}', '{{first_name}}', '{{gateway_pin}}', '{{workspace_name}}']); ?>
          </p>
        </td>
      </tr>
    </table>

    <p style="margin:8px 0 24px;">
      <button
        type="button"
        class="button afb-email-test-btn"
        data-template="client_gateway_completed"
        data-status-id="afb-email-test-status-cg-completed"
      >Send Test: Client Gateway Request Complete</button>
      <span id="afb-email-test-status-cg-completed" style="margin-left:10px;font-size:13px;color:#6b7280;"></span>
    </p>

    <hr />

    <h2 class="title">3. Client Gateway Request Complete Email (Automatic via Automator)</h2>
    <p class="description">Used by Automator's &quot;Email client when task completed&quot; action when rule-specific subject/body are left blank.</p>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_cg_completion_email_subject">Subject</label></th>
        <td>
          <input
            name="afb_cg_completion_email_subject"
            type="text"
            id="afb_cg_completion_email_subject"
            value="<?= esc_attr(get_option('afb_cg_completion_email_subject', $client_gateway_completion_defaults['subject'])) ?>"
            class="large-text"
          />
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{job_number}}', '{{request_number}}', '{{gateway_url}}', '{{task_gid}}', '{{name}}', '{{first_name}}', '{{gateway_pin}}', '{{workspace_name}}']); ?>
          </p>
        </td>
      </tr>
      <tr>
        <th scope="row">Body</th>
        <td>
          <?php afb_render_email_template_editor('afb_cg_completion_email_body', 'afb_cg_completion_email_body_editor_gateway_completed', $client_gateway_completion_defaults['body'], 10); ?>
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{task_name}}', '{{job_number}}', '{{request_number}}', '{{gateway_url}}', '{{task_gid}}', '{{name}}', '{{first_name}}', '{{gateway_pin}}', '{{workspace_name}}']); ?>
          </p>
        </td>
      </tr>
    </table>

    <p style="margin:8px 0 24px;">
      <button
        type="button"
        class="button afb-email-test-btn"
        data-template="gateway_comment"
        data-status-id="afb-email-test-status-gateway-comment"
      >Send Test: Gateway Comment Notification</button>
      <span id="afb-email-test-status-gateway-comment" style="margin-left:10px;font-size:13px;color:#6b7280;"></span>
    </p>

    <hr />

    <h2 class="title">4. Gateway Notification Email: New Comment (Automatic)</h2>
    <p class="description">Sent to collaborators/assignee based on Client Gateway notification toggles.</p>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_gateway_comment_email_subject">Subject</label></th>
        <td>
          <input
            name="afb_gateway_comment_email_subject"
            type="text"
            id="afb_gateway_comment_email_subject"
            value="<?= esc_attr(get_option('afb_gateway_comment_email_subject', $gateway_comment_defaults['subject'])) ?>"
            class="large-text"
          />
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{recipient_name}}', '{{task_name}}', '{{actor_name}}', '{{actor_email}}', '{{event_label}}', '{{comment}}', '{{gateway_url}}']); ?>
          </p>
        </td>
      </tr>
      <tr>
        <th scope="row">Body</th>
        <td>
          <?php afb_render_email_template_editor('afb_gateway_comment_email_body', 'afb_gateway_comment_email_body_editor', $gateway_comment_defaults['body'], 10); ?>
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{recipient_name}}', '{{task_name}}', '{{actor_name}}', '{{actor_email}}', '{{actor_email_suffix}}', '{{comment}}', '{{event_detail_html}}', '{{gateway_url}}', '{{gateway_button_html}}']); ?>
          </p>
        </td>
      </tr>
    </table>

    <hr />

    <h2 class="title">5. Gateway Notification Email: New Upload (Automatic)</h2>
    <p class="description">Sent to collaborators/assignee based on Client Gateway notification toggles.</p>
    <table class="form-table" role="presentation">
      <tr>
        <th scope="row"><label for="afb_gateway_upload_email_subject">Subject</label></th>
        <td>
          <input
            name="afb_gateway_upload_email_subject"
            type="text"
            id="afb_gateway_upload_email_subject"
            value="<?= esc_attr(get_option('afb_gateway_upload_email_subject', $gateway_upload_defaults['subject'])) ?>"
            class="large-text"
          />
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{recipient_name}}', '{{task_name}}', '{{actor_name}}', '{{actor_email}}', '{{event_label}}', '{{filename}}', '{{gateway_url}}']); ?>
          </p>
        </td>
      </tr>
      <tr>
        <th scope="row">Body</th>
        <td>
          <?php afb_render_email_template_editor('afb_gateway_upload_email_body', 'afb_gateway_upload_email_body_editor', $gateway_upload_defaults['body'], 10); ?>
          <p class="description">
            Supported placeholders:
            <?php afb_render_email_token_hint(['{{recipient_name}}', '{{task_name}}', '{{actor_name}}', '{{actor_email}}', '{{actor_email_suffix}}', '{{filename}}', '{{event_detail_html}}', '{{gateway_url}}', '{{gateway_button_html}}']); ?>
          </p>
        </td>
      </tr>
    </table>

    <p style="margin:8px 0 24px;">
      <button
        type="button"
        class="button afb-email-test-btn"
        data-template="gateway_upload"
        data-status-id="afb-email-test-status-gateway-upload"
      >Send Test: Gateway Upload Notification</button>
      <span id="afb-email-test-status-gateway-upload" style="margin-left:10px;font-size:13px;color:#6b7280;"></span>
    </p>

    <p>
      <button type="submit" name="afb_save_email_settings" class="button button-primary">Save Settings</button>
    </p>
  </form>
</div>

<script>
(function () {
  var ajaxUrl = <?= wp_json_encode(admin_url('admin-ajax.php')); ?>;
  var nonce = <?= wp_json_encode($email_test_nonce); ?>;
  var recipientEl = document.getElementById('afb-email-test-recipient');

  function setStatus(statusId, text, isError) {
    var el = document.getElementById(statusId);
    if (!el) return;
    el.textContent = text;
    el.style.color = isError ? '#b91c1c' : '#15803d';
  }

  function parseJsonSafe(raw) {
    var text = String(raw || '').trim();
    if (!text) return null;

    try {
      return JSON.parse(text);
    } catch (_) {
      var idx = text.indexOf('{');
      if (idx >= 0) {
        try {
          return JSON.parse(text.slice(idx));
        } catch (_) {}
      }
    }

    return null;
  }

  function sendTemplateTest(button) {
    if (!button) return;

    var template = button.getAttribute('data-template') || '';
    var statusId = button.getAttribute('data-status-id') || '';
    var to = recipientEl ? recipientEl.value : '';

    var originalLabel = button.textContent;
    button.disabled = true;
    button.textContent = 'Sending...';
    setStatus(statusId, 'Sending test email...', false);

    var data = new FormData();
    data.append('action', 'afb_send_email_settings_test');
    data.append('nonce', nonce);
    data.append('template', template);
    data.append('to', to);

    fetch(ajaxUrl, {
      method: 'POST',
      body: data
    })
      .then(function (res) {
        return res.text().then(function (body) {
          return { ok: !!res.ok, body: body };
        });
      })
      .then(function (json) {
        var payload = parseJsonSafe(json && json.body ? json.body : '');

        if (payload && payload.success) {
          var msg = (payload.data && payload.data.message) ? payload.data.message : 'Test email sent.';
          setStatus(statusId, msg, false);
          return;
        }

        var err = '';
        if (payload && payload.data && payload.data.message) {
          err = payload.data.message;
        } else {
          var raw = String((json && json.body) ? json.body : '')
            .replace(/<[^>]+>/g, ' ')
            .replace(/\s+/g, ' ')
            .trim();
          err = raw ? raw.slice(0, 180) : 'Test email failed.';
        }
        setStatus(statusId, err, true);
      })
      .catch(function () {
        setStatus(statusId, 'Test email failed. Please try again.', true);
      })
      .finally(function () {
        button.disabled = false;
        button.textContent = originalLabel;
      });
  }

  var buttons = document.querySelectorAll('.afb-email-test-btn');
  buttons.forEach(function (btn) {
    btn.addEventListener('click', function () {
      sendTemplateTest(btn);
    });
  });
})();
</script>
