<?php
if (!defined('ABSPATH')) exit;

require_once ASANA_AUTOMATOR_DIR . 'includes/automation-registry.php';
require_once ASANA_AUTOMATOR_DIR . 'includes/dispatcher.php';

if (!defined('AFB_AUTOMATOR_EMBEDDED')) {
    add_action('admin_menu', function () {
        add_submenu_page(
            'asana-automator',
            'Automation Rules',
            'Automation Rules',
            'manage_options',
            'asana-automator-rules',
            'asana_automator_rules_page'
        );
    });
}

add_action('admin_init', function () {
    if (isset($_POST['asana_automator_save_rule']) && current_user_can('manage_options')) {
        $rules = get_option('asana_automator_rules', []);
        $edit_index = isset($_POST['edit_rule_index']) ? intval($_POST['edit_rule_index']) : null;

        $entry = [
            'rule_id' => $edit_index !== null && isset($rules[$edit_index]) ? $rules[$edit_index]['rule_id'] : uniqid('rule_', true),
            'rule_label' => sanitize_text_field($_POST['rule_label'] ?? ''),
            'project_gid' => sanitize_text_field($_POST['project_gid'] ?? ''),
            'project_name' => sanitize_text_field($_POST['project_name'] ?? ''),
            'section_gids' => isset($_POST['section_gids']) ? array_map('sanitize_text_field', (array)$_POST['section_gids']) : [],
            'section_names' => isset($_POST['section_names']) ? array_map('sanitize_text_field', (array)$_POST['section_names']) : [],
            'action' => sanitize_text_field($_POST['action_type'] ?? ''),
            'pat_label' => sanitize_text_field($_POST['pat_label'] ?? ''),
            'marker_label' => sanitize_text_field($_POST['marker_label'] ?? ''),
            'email_subject_template' => sanitize_text_field($_POST['email_subject_template'] ?? ''),
            'email_body_template' => sanitize_textarea_field($_POST['email_body_template'] ?? ''),
            'completion_state' => sanitize_text_field($_POST['completion_state'] ?? 'any'),
            'email_field_gid' => sanitize_text_field($_POST['email_field_gid'] ?? ''),
            'email_field_name' => sanitize_text_field($_POST['email_field_name'] ?? ''),
            'first_name' => sanitize_text_field($_POST['first_name'] ?? ''),
            'first_name_field_name' => sanitize_text_field($_POST['first_name_field_name'] ?? ''),
            'last_name' => sanitize_text_field($_POST['last_name'] ?? ''),
            'last_name_field_name' => sanitize_text_field($_POST['last_name_field_name'] ?? ''),
            'include_gateway_pin' => !empty($_POST['include_gateway_pin']) ? '1' : '0',
            'auto_refresh_gateway' => !empty($_POST['auto_refresh_gateway']) ? '1' : '0',
            'trigger_phrase' => sanitize_text_field($_POST['trigger_phrase'] ?? ''),
            'overwrite_existing' => !empty($_POST['overwrite_existing']) ? '1' : '0',
            'mapping_profile_key' => sanitize_key($_POST['mapping_profile_key'] ?? ''),
            'mapping_rules_json' => sanitize_textarea_field(wp_unslash($_POST['mapping_rules_json'] ?? '')),
            'dry_run' => !empty($_POST['dry_run']) ? '1' : '0',
            'delete_attachments_on_complete' => !empty($_POST['delete_attachments_on_complete']) ? '1' : '0',
            'delete_local_client_gateway_on_complete' => !empty($_POST['delete_local_client_gateway_on_complete']) ? '1' : '0',
            'complete_private_companion_on_complete' => !empty($_POST['complete_private_companion_on_complete']) ? '1' : '0',
            'remove_private_companion_references_on_complete' => !empty($_POST['remove_private_companion_references_on_complete']) ? '1' : '0',
            'cleanup_field_gids' => isset($_POST['cleanup_field_gids']) ? array_map('sanitize_text_field', (array)$_POST['cleanup_field_gids']) : [],
            'cleanup_field_names' => isset($_POST['cleanup_field_names']) ? array_map('sanitize_text_field', (array)$_POST['cleanup_field_names']) : [],
            'clear_notes_on_complete' => !empty($_POST['clear_notes_on_complete']) ? '1' : '0',
            'notes_redact_phrases' => sanitize_textarea_field($_POST['notes_redact_phrases'] ?? ''),
            // Guardrails for scan-style runs
            'lookback_days' => max(0, absint($_POST['lookback_days'] ?? 14)),
            'max_tasks_per_run' => max(1, min(1000, absint($_POST['max_tasks_per_run'] ?? 100))),
        ];

        if (
            $entry['action'] === 'map_fields_from_description' &&
            trim((string)$entry['mapping_rules_json']) === '' &&
            trim((string)$entry['mapping_profile_key']) === ''
        ) {
            $token = asana_automator_get_pat_token((string) $entry['pat_label']);

            if (!empty($entry['project_gid']) && !empty($token)) {
                $bootstrap = asana_automator_bootstrap_mapping_rules_for_project((string)$entry['project_gid'], (string)$token);
                if (!empty($bootstrap['ok']) && !empty($bootstrap['json'])) {
                    $entry['mapping_rules_json'] = (string)$bootstrap['json'];
                }
            }
        }

        if ($edit_index !== null && isset($rules[$edit_index])) {
            $rules[$edit_index] = $entry;
        } else {
            $rules[] = $entry;
        }
        update_option('asana_automator_rules', $rules, true);
    }

    if (isset($_GET['delete_rule']) && current_user_can('manage_options')) {
        $rules = get_option('asana_automator_rules', []);
        $idx = intval($_GET['delete_rule']);
        if (isset($rules[$idx])) {
            unset($rules[$idx]);
            update_option('asana_automator_rules', array_values($rules));
        }
    }

    if (isset($_GET['run_rule']) && current_user_can('manage_options')) {
        $idx = intval($_GET['run_rule']);
        check_admin_referer('asana_run_rule_' . $idx);
        $ok = asana_automator_run_rule_by_index($idx);
        add_action('admin_notices', function () use ($ok) {
            echo '<div class="notice ' . ($ok ? 'notice-success' : 'notice-error') . '"><p>' . ($ok ? 'Automation executed.' : 'Nothing ran – invalid index.') . '</p></div>';
        });
    }
});

function asana_automator_rules_page() {
    $rules = get_option('asana_automator_rules', []);
    $pat_accounts = asana_automator_get_pat_accounts();
    $mapping_profiles = get_option('asana_automator_mapping_profiles', []);
    $available = asana_automator_get_registered_automations();
    $edit_index = isset($_GET['edit_rule']) ? intval($_GET['edit_rule']) : null;
    $editing_rule = ($edit_index !== null && isset($rules[$edit_index])) ? $rules[$edit_index] : null;
?>
<div class="wrap">
    <h1>⚙️ Automation Rules</h1>

    <form method="post" id="automation-rule-form">
        <?php if ($editing_rule): ?>
            <input type="hidden" name="edit_rule_index" value="<?php echo esc_attr($edit_index); ?>">
        <?php endif; ?>

        <table class="form-table">
            <tr>
                <th>Rule Name</th>
                <td>
                    <input type="text" name="rule_label" class="regular-text" value="<?php echo esc_attr($editing_rule['rule_label'] ?? ''); ?>" required>
                    <p class="description">Give this rule a descriptive name to easily identify it.</p>
                </td>
            </tr>
            <tr>
                <th>PAT Account</th>
                <td>
                    <select name="pat_label" id="pat_label" required>
                        <?php foreach ($pat_accounts as $label => $_): ?>
                            <option value="<?php echo esc_attr($label); ?>" <?php selected($editing_rule['pat_label'] ?? '', $label); ?>><?php echo esc_html($label); ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>
            <tr>
                <th>Project</th>
                <td>
                    <button type="button" id="fetch-projects" class="button button-small">🔄 Fetch Projects</button><br><br>
                    <select id="asana-project" name="project_gid" style="width:300px;" required>
                        <?php if ($editing_rule): ?>
                            <option value="<?php echo esc_attr($editing_rule['project_gid']); ?>" selected><?php echo esc_html($editing_rule['project_name']); ?></option>
                        <?php endif; ?>
                    </select>
                    <input type="hidden" name="project_name" id="asana-project-name" value="<?php echo esc_attr($editing_rule['project_name'] ?? ''); ?>">
                </td>
            </tr>

            <tr>
                <th>Sections</th>
                <td>
                    <select id="asana-section" name="section_gids[]" multiple size="6" style="width:300px;" required>
                        <?php if ($editing_rule && !empty($editing_rule['section_gids'])) : foreach ($editing_rule['section_gids'] as $gid_index => $section_gid) : ?>
                            <option value="<?php echo esc_attr($section_gid); ?>" selected><?php echo esc_html($editing_rule['section_names'][$gid_index] ?? $section_gid); ?></option>
                        <?php endforeach; endif; ?>
                    </select>
                    <input type="hidden" name="section_names[]" id="section-name-holder">
                </td>
            </tr>

            <tr>
                <th>Action</th>
                <td>
                    <select name="action_type" id="action_type_selector" required>
                        <?php foreach ($available as $key => $meta): ?>
                            <option value="<?php echo esc_attr($key); ?>" <?php selected($editing_rule['action'] ?? '', $key); ?>><?php echo esc_html($meta['label']); ?></option>
                        <?php endforeach; ?>
                    </select>
                </td>
            </tr>

            <tr>
                <th>Lookback Window (days)</th>
                <td>
                    <input
                        type="number"
                        name="lookback_days"
                        min="0"
                        step="1"
                        value="<?php echo esc_attr((string)($editing_rule['lookback_days'] ?? 14)); ?>"
                        style="width:120px;"
                    >
                    <p class="description">Used for completion-focused scans. <strong>14</strong> means only tasks completed in the last 14 days are scanned. Set to <strong>0</strong> to scan all history.</p>
                </td>
            </tr>

            <tr>
                <th>Max Tasks Per Run</th>
                <td>
                    <input
                        type="number"
                        name="max_tasks_per_run"
                        min="1"
                        max="1000"
                        step="1"
                        value="<?php echo esc_attr((string)($editing_rule['max_tasks_per_run'] ?? 100)); ?>"
                        style="width:120px;"
                    >
                    <p class="description">Safety cap across all selected sections for one rule execution. Lower this to reduce Asana API pressure and avoid rate limiting.</p>
                </td>
            </tr>

            <!-- Email-specific fields -->
            <tr class="email-field-row" style="display:none;">
                <th>Email Field</th>
                <td>
                    <select id="email-field-selector" name="email_field_gid" style="width:300px;">
                        <?php if ($editing_rule && !empty($editing_rule['email_field_gid'])): ?>
                            <option value="<?php echo esc_attr($editing_rule['email_field_gid']); ?>" selected><?php echo esc_html($editing_rule['email_field_name'] ?? $editing_rule['email_field_gid']); ?></option>
                        <?php endif; ?>
                    </select>
                    <input type="hidden" name="email_field_name" id="email-field-name" value="<?php echo esc_attr($editing_rule['email_field_name'] ?? ''); ?>">
                </td>
            </tr>
            <tr class="email-field-row" style="display:none;">
                <th>First Name Field</th>
                <td>
                    <select id="first-name-field-selector" name="first_name" style="width:300px;">
                        <?php if ($editing_rule && !empty($editing_rule['first_name'])): ?>
                            <option value="<?php echo esc_attr($editing_rule['first_name']); ?>" selected><?php echo esc_html($editing_rule['first_name_field_name'] ?? $editing_rule['first_name']); ?></option>
                        <?php endif; ?>
                    </select>
                    <input type="hidden" name="first_name_field_name" id="first-name-field-name" value="<?php echo esc_attr($editing_rule['first_name_field_name'] ?? ''); ?>">
                </td>
            </tr>
            <tr class="email-field-row" style="display:none;">
                <th>Last Name Field</th>
                <td>
                    <select id="last-name-field-selector" name="last_name" style="width:300px;">
                        <?php if ($editing_rule && !empty($editing_rule['last_name'])): ?>
                            <option value="<?php echo esc_attr($editing_rule['last_name']); ?>" selected><?php echo esc_html($editing_rule['last_name_field_name'] ?? $editing_rule['last_name']); ?></option>
                        <?php endif; ?>
                    </select>
                    <input type="hidden" name="last_name_field_name" id="last-name-field-name" value="<?php echo esc_attr($editing_rule['last_name_field_name'] ?? ''); ?>">
                </td>
            </tr>

            <tr class="param-field" data-param="marker_label" style="display:none;">
                <th>Marker Label</th>
                <td><input type="text" name="marker_label" class="regular-text" value="<?php echo esc_attr($editing_rule['marker_label'] ?? ''); ?>"></td>
            </tr>
            <tr class="param-field" data-param="email_subject_template" style="display:none;">
                <th>Email Subject</th>
                <td>
                    <input type="text" name="email_subject_template" class="regular-text" value="<?php echo esc_attr($editing_rule['email_subject_template'] ?? ''); ?>">
                    <p class="description">Tokens: {task_name}, {task_link}, {full_name}, {project_name}, {section_names}, {comment_author}, {comment_text}, {job_number}, {request_number}, {gateway_url}, {gateway_pin}, {workspace_name}, {task_gid}</p>
                    <p class="description">For completion gateway rules, leave this blank to use Email Settings → Client Gateway Request Complete subject.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="email_body_template" style="display:none;">
                <th>Email Body</th>
                <td>
                    <textarea name="email_body_template" rows="6" class="large-text"><?php echo esc_textarea($editing_rule['email_body_template'] ?? ''); ?></textarea>
                    <p class="description">For comment rules you can include: {comment_author}, {comment_text}, and {story_gid}. For completion gateway rules you can include: {gateway_url}, {job_number}, {request_number}, and {gateway_pin}.</p>
                    <p class="description">For completion gateway rules, leave this blank to use Email Settings → Client Gateway Request Complete body.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="include_gateway_pin" style="display:none;">
                <th>Include Gateway PIN</th>
                <td>
                    <label>
                        <input type="checkbox" name="include_gateway_pin" value="1" <?php checked($editing_rule['include_gateway_pin'] ?? '0', '1'); ?>>
                        Include the Gateway PIN in this completion email.
                    </label>
                </td>
            </tr>
            <tr class="param-field" data-param="auto_refresh_gateway" style="display:none;">
                <th>Auto Refresh Gateway</th>
                <td>
                    <label>
                        <input type="checkbox" name="auto_refresh_gateway" value="1" <?php checked($editing_rule['auto_refresh_gateway'] ?? '1', '1'); ?>>
                        Add an auto-refresh flag to the gateway link so the latest task status is rebuilt before viewing.
                    </label>
                </td>
            </tr>
            <tr class="param-field" data-param="completion_state" style="display:none;">
                <th>Trigger on Task Completion</th>
                <td>
                    <select name="completion_state">
                        <option value="any" <?php selected($editing_rule['completion_state'] ?? '', 'any'); ?>>Any (default)</option>
                        <option value="complete" <?php selected($editing_rule['completion_state'] ?? '', 'complete'); ?>>Only if Complete</option>
                        <option value="incomplete" <?php selected($editing_rule['completion_state'] ?? '', 'incomplete'); ?>>Only if Incomplete</option>
                    </select>
                </td>
            </tr>
            <tr class="param-field" data-param="delete_attachments_on_complete" style="display:none;">
                <th>Delete Attachments</th>
                <td>
                    <label>
                        <input type="checkbox" name="delete_attachments_on_complete" value="1" <?php checked($editing_rule['delete_attachments_on_complete'] ?? '1', '1'); ?>>
                        Delete all attachments when the task is completed.
                    </label>
                </td>
            </tr>
            <tr class="param-field" data-param="delete_local_client_gateway_on_complete" style="display:none;">
                <th>Delete WordPress Client Gateway</th>
                <td>
                    <label>
                        <input type="checkbox" name="delete_local_client_gateway_on_complete" value="1" <?php checked($editing_rule['delete_local_client_gateway_on_complete'] ?? '0', '1'); ?>>
                        If a Client Gateway exists for this task in WordPress, expire/delete it locally.
                    </label>
                    <p class="description">This invalidates the local gateway token/cache in WordPress. Use with field cleanup if you also want to clear Asana link fields.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="complete_private_companion_on_complete" style="display:none;">
                <th>Complete Linked Companion Task</th>
                <td>
                    <label>
                        <input type="checkbox" name="complete_private_companion_on_complete" value="1" <?php checked($editing_rule['complete_private_companion_on_complete'] ?? '0', '1'); ?>>
                        If task notes contain "Private companion task:" link, mark that companion task complete too.
                    </label>
                    <p class="description">Use this with your Private Data project rule that deletes tasks on completion.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="remove_private_companion_references_on_complete" style="display:none;">
                <th>Strip Companion References from Main Task</th>
                <td>
                    <label>
                        <input type="checkbox" name="remove_private_companion_references_on_complete" value="1" <?php checked($editing_rule['remove_private_companion_references_on_complete'] ?? '1', '1'); ?>>
                        Remove "Confidential data notice" and "Private companion task" lines from the main task description on completion.
                    </label>
                    <p class="description">Keeps the main task anonymous after completion while still allowing lookup by job number/custom fields.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="cleanup_field_gids" style="display:none;">
                <th>Fields to Clear</th>
                <td>
                    <select id="cleanup-field-selector" name="cleanup_field_gids[]" multiple size="6" style="width:420px;">
                        <?php
                            $cleanup_gids = $editing_rule ? (array)($editing_rule['cleanup_field_gids'] ?? []) : [];
                            $cleanup_names = $editing_rule ? (array)($editing_rule['cleanup_field_names'] ?? []) : [];
                        ?>
                        <?php if (!empty($cleanup_gids)) : foreach ($cleanup_gids as $index => $gid) : ?>
                            <?php
                                $cleanup_name = trim((string)($cleanup_names[$index] ?? ''));
                                $cleanup_label = $cleanup_name !== '' && $cleanup_name !== $gid
                                    ? $cleanup_name . ' (' . $gid . ')'
                                    : $gid;
                            ?>
                            <option value="<?php echo esc_attr($gid); ?>" selected><?php echo esc_html($cleanup_label); ?></option>
                        <?php endforeach; endif; ?>
                    </select>
                    <p class="description">Select one or more text custom fields to clear on completion.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="clear_notes_on_complete" style="display:none;">
                <th>Clear Task Description</th>
                <td>
                    <label>
                        <input type="checkbox" name="clear_notes_on_complete" value="1" <?php checked($editing_rule['clear_notes_on_complete'] ?? '0', '1'); ?>>
                        Clear the task description (notes) when completed.
                    </label>
                </td>
            </tr>
            <tr class="param-field" data-param="notes_redact_phrases" style="display:none;">
                <th>Redact Phrases in Description</th>
                <td>
                    <textarea name="notes_redact_phrases" rows="4" class="large-text" placeholder="One phrase per line"><?php echo esc_textarea($editing_rule['notes_redact_phrases'] ?? ''); ?></textarea>
                    <p class="description">Optional. Removes matching phrases from description text. Ignored if "Clear Task Description" is enabled.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="trigger_phrase" style="display:none;">
                <th>Trigger Phrase</th>
                <td>
                    <input type="text" name="trigger_phrase" class="regular-text" value="<?php echo esc_attr($editing_rule['trigger_phrase'] ?? 'This request was submitted through Flash Triage'); ?>">
                    <p class="description">Only parse tasks whose description contains this phrase. Leave as default for Flash Triage tasks.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="overwrite_existing" style="display:none;">
                <th>Overwrite Existing Values</th>
                <td>
                    <label>
                        <input type="checkbox" name="overwrite_existing" value="1" <?php checked($editing_rule['overwrite_existing'] ?? '0', '1'); ?>>
                        Replace field values even if the task already has a value.
                    </label>
                </td>
            </tr>
            <tr class="param-field" data-param="mapping_rules_json" style="display:none;">
                <th>Mapping Rules (JSON)</th>
                <td>
                    <p style="margin-top:0;">
                        <button type="button" id="bootstrap-mapping-json" class="button button-small">🪄 Bootstrap from Project Fields</button>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=asana-automator-mappings')); ?>" class="button button-small">📚 Manage Profiles</a>
                    </p>
                    <textarea name="mapping_rules_json" rows="12" class="large-text code" placeholder='[
  {
    "source_label": "Site",
    "target_field_gid": "1208219536311276",
    "target_type": "enum",
    "aliases": {
      "108 Wickham Street": "108 Wickham Street, Fortitude Valley"
    }
  }
]'><?php echo esc_textarea($editing_rule['mapping_rules_json'] ?? ''); ?></textarea>
                    <p class="description">Each rule maps a description line label (for example "Site") to an Asana custom field GID. target_type supports: enum, text, number, date. You can also paste full Asana custom_field_settings JSON and it will be auto-converted. If this is left empty and no profile is selected, mappings are auto-generated from the selected project when you save.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="mapping_profile_key" style="display:none;">
                <th>Mapping Profile</th>
                <td>
                    <select id="mapping-profile-key" name="mapping_profile_key" style="width:300px;">
                        <option value="">- None (use JSON above) -</option>
                        <?php foreach ($mapping_profiles as $profile_key => $profile): ?>
                            <option value="<?php echo esc_attr($profile_key); ?>" <?php selected($editing_rule['mapping_profile_key'] ?? '', $profile_key); ?>><?php echo esc_html($profile['label'] ?? $profile_key); ?></option>
                        <?php endforeach; ?>
                    </select>
                    <p class="description">Optional. If selected, this reusable profile is used when Mapping Rules JSON is empty.</p>
                </td>
            </tr>
            <tr class="param-field" data-param="dry_run" style="display:none;">
                <th>Dry Run</th>
                <td>
                    <label>
                        <input type="checkbox" name="dry_run" value="1" <?php checked($editing_rule['dry_run'] ?? '0', '1'); ?>>
                        Dry run only. No changes are written to Asana. Results are logged to custom-debug.log.
                    </label>
                </td>
            </tr>
        </table>

        <?php submit_button($editing_rule ? '💾 Update Rule' : '➕ Save Rule', 'primary', 'asana_automator_save_rule'); ?>
    </form>

    <?php if (!empty($rules)) : ?>
        <h2 style="margin-top:40px;">📋 Saved Rules</h2>
        <table class="widefat striped">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Name</th>
                    <th>Marker</th>
                    <th>Project</th>
                    <th>Sections</th>
                    <th>Action</th>
                    <th>Completion State</th>
                    <th>PAT</th>
                    <th>Actions</th>
                </tr>
            </thead>
            <tbody>
            <?php foreach ($rules as $i => $r): ?>
                <tr>
                    <td><?php echo $i; ?></td>
                    <td><?php echo esc_html($r['rule_label'] ?? '(Unnamed)'); ?></td>
                    <td><?php echo esc_html($r['marker_label'] ?? '-'); ?></td>
                    <td><?php echo esc_html($r['project_name'] ?? ($r['project_gid'] ?? '')); ?></td>
                    <td>
                        <ul style="margin:0;padding-left:20px;">
                            <?php foreach ((array)($r['section_names'] ?? []) as $n): ?>
                                <li><?php echo esc_html($n); ?></li>
                            <?php endforeach; ?>
                        </ul>
                    </td>
                    <td><?php echo esc_html($available[$r['action']]['label'] ?? $r['action']); ?></td>
                    <td><?php echo esc_html($r['completion_state'] ?? 'any'); ?></td>
                    <td><?php echo esc_html($r['pat_label'] ?? ''); ?></td>
                    <td>
                        <a href="?page=asana-automator-rules&edit_rule=<?php echo $i; ?>" class="button button-small">✏️ Edit</a>
                        <?php $run_url = wp_nonce_url(admin_url('admin.php?page=asana-automator-rules&run_rule=' . $i), 'asana_run_rule_' . $i); ?>
                        <a href="<?php echo esc_url($run_url); ?>" class="button button-small" style="margin-left:5px;">▶️ Run</a>
                        <button type="button" class="button button-small send-test-email" data-index="<?php echo $i; ?>" style="margin-left:5px;">📨 Send Test</button>
                        <a href="?page=asana-automator-rules&delete_rule=<?php echo $i; ?>" class="button button-small" style="margin-left:5px;">🗑 Delete</a>
                    </td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<script>
(function ($) {
    /* ---------- Registry helpers ---------- */
    const registry = <?php echo json_encode(asana_automator_get_registered_automations()); ?>;
    const mappingProfiles = <?php
        $profile_payload = [];
        foreach ($mapping_profiles as $profile_key => $profile) {
            $profile_payload[$profile_key] = [
                'label' => (string)($profile['label'] ?? $profile_key),
                'mapping_rules_json' => (string)($profile['mapping_rules_json'] ?? ''),
            ];
        }
        echo json_encode($profile_payload);
    ?>;

    const sendEmailNonce = '<?php echo wp_create_nonce('asana_automator_send_test_email'); ?>';
    const currentUserEmail = '<?php echo esc_js(wp_get_current_user()->user_email); ?>';
    const editingRule = <?php
        $editing_payload = [
            'section_gids' => array_map('strval', (array)($editing_rule['section_gids'] ?? [])),
            'email_field_gid' => (string)($editing_rule['email_field_gid'] ?? ''),
            'first_name' => (string)($editing_rule['first_name'] ?? ''),
            'last_name' => (string)($editing_rule['last_name'] ?? ''),
            'cleanup_field_gids' => array_map('strval', (array)($editing_rule['cleanup_field_gids'] ?? [])),
        ];
        echo json_encode($editing_payload);
    ?>;

    const esc = value => String(value ?? '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;');

    const toggleParamFields = key => {
        $('.param-field').hide();
        (registry[key]?.params || []).forEach(param => $('[data-param="' + param + '"]').show());
    };

    const toggleEmailFields = key => $('.email-field-row').toggle(String(key || '').includes('email'));

    const applyProfileToTextarea = profileKey => {
        if (!profileKey || !mappingProfiles[profileKey]) return;
        const json = (mappingProfiles[profileKey].mapping_rules_json || '').trim();
        if (!json) return;

        const $ta = $('textarea[name="mapping_rules_json"]');
        if ($ta.length && (!$ta.val() || !$ta.val().trim())) {
            $ta.val(json);
        }
    };

    const setSingleFieldName = (selector, hiddenSelector) => {
        const label = String($(selector).find('option:selected').text() || '').trim();
        if (!label || label === '— Select —') {
            $(hiddenSelector).val('');
            return;
        }
        $(hiddenSelector).val(label.replace(/\s+\([0-9]+\)\s*$/, '').trim());
    };

    const loadProjectSections = (project_gid, pat_label) => {
        const selectedSectionGids = ($('#asana-section').val() || editingRule.section_gids || []).map(String);

        $.get(ajaxurl, {action: 'get_asana_sections', project_gid, pat_label}, response => {
            if (!response.success) return;
            const $sec = $('#asana-section').empty();
            (response.data || []).forEach(section => {
                const gid = String(section.gid || '');
                if (!gid) return;
                const selected = selectedSectionGids.includes(gid) ? ' selected' : '';
                $sec.append(`<option value="${esc(gid)}"${selected}>${esc(section.name || gid)}</option>`);
            });
        });
    };

    const loadProjectFields = (project_gid, pat_label) => {
        const currentEmail = String($('#email-field-selector').val() || editingRule.email_field_gid || '');
        const currentFirst = String($('#first-name-field-selector').val() || editingRule.first_name || '');
        const currentLast  = String($('#last-name-field-selector').val() || editingRule.last_name || '');
        const selectedCleanup = ($('#cleanup-field-selector').val() || editingRule.cleanup_field_gids || []).map(String);

        $.get(ajaxurl, {action: 'get_asana_project_fields', project_gid, pat_label}, response => {
            if (!response.success) return;

            const textFields = (response.data || []).filter(field => field.type === 'text');
            const baseOptions = textFields
                .map(field => `<option value="${esc(field.gid)}">${esc(field.name)}</option>`)
                .join('');

            ['#email-field-selector', '#first-name-field-selector', '#last-name-field-selector']
                .forEach(selector => $(selector).html('<option value="">— Select —</option>' + baseOptions));

            if (currentEmail) $('#email-field-selector').val(currentEmail);
            if (currentFirst) $('#first-name-field-selector').val(currentFirst);
            if (currentLast)  $('#last-name-field-selector').val(currentLast);

            const cleanupOptions = textFields.map(field => {
                const gid = String(field.gid || '');
                if (!gid) return '';
                const selected = selectedCleanup.includes(gid) ? ' selected' : '';
                return `<option value="${esc(gid)}"${selected}>${esc(field.name)} (${esc(gid)})</option>`;
            }).join('');
            $('#cleanup-field-selector').html(cleanupOptions);

            setSingleFieldName('#email-field-selector', '#email-field-name');
            setSingleFieldName('#first-name-field-selector', '#first-name-field-name');
            setSingleFieldName('#last-name-field-selector', '#last-name-field-name');
        });
    };

    const runBootstrap = (silentMode = false) => {
        const project_gid = $('#asana-project').val();
        const pat_label = $('#pat_label').val();
        if (!project_gid) {
            if (!silentMode) alert('Select a project first.');
            return;
        }

        const $btn = $('#bootstrap-mapping-json');
        $btn.prop('disabled', true).text('Generating...');

        $.get(ajaxurl, { action: 'asana_automator_bootstrap_mapping_rules', project_gid, pat_label }, response => {
            if (!response.success || !response.data?.mapping_rules_json) {
                if (!silentMode) {
                    alert((response.data && response.data.message) ? response.data.message : 'Could not generate mapping rules.');
                }
                return;
            }

            const $ta = $('textarea[name="mapping_rules_json"]');
            if ($ta.length && (silentMode ? (!$ta.val() || !$ta.val().trim()) : true)) {
                $ta.val(response.data.mapping_rules_json);
            }

            if (!silentMode) {
                alert('Bootstrap mapping JSON generated. Review and save the rule.');
            }
        }).always(() => {
            $btn.prop('disabled', false).text('🪄 Bootstrap from Project Fields');
        });
    };

    $('#action_type_selector')
        .on('change', function () {
            toggleParamFields(this.value);
            toggleEmailFields(this.value);
        })
        .trigger('change');

    $('#mapping-profile-key').on('change', function () {
        applyProfileToTextarea(this.value);
    });

    $('#bootstrap-mapping-json').on('click', function (event) {
        event.preventDefault();
        runBootstrap(false);
    });

    $('#fetch-projects').on('click', function (event) {
        event.preventDefault();

        $.get(ajaxurl, {action: 'get_asana_projects'}, response => {
            const $project = $('#asana-project').empty();
            if (!response.success || !response.data?.length) {
                $project.append('<option value="">No projects found</option>');
                return;
            }

            const grouped = {};
            response.data.forEach(project => {
                const key = project.source_label || 'Other';
                grouped[key] = grouped[key] || [];
                grouped[key].push(project);
            });

            Object.entries(grouped).forEach(([label, list]) => {
                const optgroup = $('<optgroup>').attr('label', label);
                list.forEach(project => {
                    optgroup.append(`<option value="${esc(project.gid)}">${esc(project.name)}</option>`);
                });
                $project.append(optgroup);
            });

            $project.trigger('change');
        });
    });

    $('#asana-project').on('change', function () {
        const project_gid = String(this.value || '');
        const project_name = String($(this).find('option:selected').text() || '');
        const pat_label = String($('#pat_label').val() || '');

        $('#asana-project-name').val(project_name);

        if (!project_gid) return;

        loadProjectSections(project_gid, pat_label);
        loadProjectFields(project_gid, pat_label);

        const action = $('#action_type_selector').val();
        const hasProfile = !!$('#mapping-profile-key').val();
        const hasManualJson = !!($('textarea[name="mapping_rules_json"]').val() || '').trim();
        if (action === 'map_fields_from_description' && !hasProfile && !hasManualJson) {
            runBootstrap(true);
        }
    });

    $('#pat_label').on('change', function () {
        const project_gid = String($('#asana-project').val() || '');
        if (project_gid) {
            $('#asana-project').trigger('change');
        }
    });

    $('#email-field-selector').on('change', function () {
        setSingleFieldName('#email-field-selector', '#email-field-name');
    });
    $('#first-name-field-selector').on('change', function () {
        setSingleFieldName('#first-name-field-selector', '#first-name-field-name');
    });
    $('#last-name-field-selector').on('change', function () {
        setSingleFieldName('#last-name-field-selector', '#last-name-field-name');
    });

    $('#automation-rule-form').on('submit', () => {
        const $form = $('#automation-rule-form');

        $('input[name="section_names[]"]').remove();
        $('#asana-section option:selected').each(function () {
            $('<input>', {type: 'hidden', name: 'section_names[]', value: $(this).text()})
                .appendTo($form);
        });

        $('input[name="cleanup_field_names[]"]').remove();
        $('#cleanup-field-selector option:selected').each(function () {
            const raw = String($(this).text() || '').trim();
            const label = raw.replace(/\s+\([0-9]+\)\s*$/, '').trim();
            $('<input>', {type: 'hidden', name: 'cleanup_field_names[]', value: label || raw})
                .appendTo($form);
        });

        setSingleFieldName('#email-field-selector', '#email-field-name');
        setSingleFieldName('#first-name-field-selector', '#first-name-field-name');
        setSingleFieldName('#last-name-field-selector', '#last-name-field-name');
    });

    // Send test email for a rule (admin-only)
    $(document).on('click', '.send-test-email', function (e) {
        e.preventDefault();
        const $btn = $(this);
        const idx = parseInt($btn.data('index'), 10);
        const origText = $btn.text();
        let to = prompt('Send test email to (leave blank to use your email):', currentUserEmail);
        if (to === null) return; // cancelled
        if (!to) to = currentUserEmail;

        $btn.prop('disabled', true).text('Sending...');

        $.post(ajaxurl, { action: 'asana_automator_send_test_email', rule_index: idx, to_email: to, nonce: sendEmailNonce }, function (resp) {
            if (resp && resp.success) {
                alert('Test email sent to ' + to);
            } else {
                const msg = resp && resp.data && resp.data.message ? resp.data.message : JSON.stringify(resp);
                alert('Send failed: ' + msg);
            }
        }).fail(function (jqxhr) {
            alert('Request failed: ' + (jqxhr && jqxhr.statusText ? jqxhr.statusText : 'unknown'));
        }).always(function () {
            $btn.prop('disabled', false).text(origText);
        });
    });

    $(document).ready(() => {
        const initialName = $('#asana-project').find('option:selected').text();
        if (initialName) {
            $('#asana-project-name').val(initialName);
        }

        const selectedProfile = $('#mapping-profile-key').val();
        if (selectedProfile) {
            applyProfileToTextarea(selectedProfile);
        }

        setSingleFieldName('#email-field-selector', '#email-field-name');
        setSingleFieldName('#first-name-field-selector', '#first-name-field-name');
        setSingleFieldName('#last-name-field-selector', '#last-name-field-name');

        if ($('#asana-project').val()) {
            $('#asana-project').trigger('change');
        }
    });
})(jQuery);
</script>

<?php
}
