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

if (!defined('AFB_AUTOMATOR_EMBEDDED')) {
    add_action('admin_menu', function () {
        add_submenu_page(
            'asana-automator',
            'Mapping Profiles',
            'Mapping Profiles',
            'manage_options',
            'asana-automator-mappings',
            'asana_automator_mapping_profiles_page'
        );
    });
}

add_action('admin_init', function () {
    if (!current_user_can('manage_options')) {
        return;
    }

    if (isset($_POST['asana_automator_save_mapping_profile'])) {
        check_admin_referer('asana_automator_save_mapping_profile');

        $profiles = get_option('asana_automator_mapping_profiles', []);

        $profile_key = sanitize_key($_POST['profile_key'] ?? '');
        $profile_label = sanitize_text_field($_POST['profile_label'] ?? '');
        $raw_json = wp_unslash($_POST['mapping_rules_json'] ?? '');

        if ($profile_key === '') {
            $profile_key = sanitize_key(sanitize_title($profile_label));
        }
        if ($profile_key === '') {
            $profile_key = 'profile_' . time();
        }

        $decoded = json_decode((string)$raw_json, true);
        if (!is_array($decoded)) {
            add_settings_error('asana_automator_mapping_profiles', 'invalid_json', 'Mapping Rules JSON is invalid. Please provide a valid JSON array.', 'error');
            return;
        }

        if ($profile_label === '') {
            $profile_label = $profile_key;
        }

        $profiles[$profile_key] = [
            'label' => $profile_label,
            'mapping_rules_json' => wp_json_encode($decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES),
            'updated_at' => current_time('mysql'),
        ];

        update_option('asana_automator_mapping_profiles', $profiles, true);
        add_settings_error('asana_automator_mapping_profiles', 'saved_profile', 'Mapping profile saved.', 'updated');
    }

    if (isset($_GET['delete_profile'])) {
        $delete_key = sanitize_key($_GET['delete_profile']);
        check_admin_referer('asana_automator_delete_mapping_profile_' . $delete_key);

        $profiles = get_option('asana_automator_mapping_profiles', []);
        if (isset($profiles[$delete_key])) {
            unset($profiles[$delete_key]);
            update_option('asana_automator_mapping_profiles', $profiles, true);
            add_settings_error('asana_automator_mapping_profiles', 'deleted_profile', 'Mapping profile deleted.', 'updated');
        }
    }
});

function asana_automator_mapping_profiles_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $profiles = get_option('asana_automator_mapping_profiles', []);
    $edit_key = isset($_GET['edit_profile']) ? sanitize_key($_GET['edit_profile']) : '';
    $editing = ($edit_key !== '' && !empty($profiles[$edit_key])) ? $profiles[$edit_key] : null;

    settings_errors('asana_automator_mapping_profiles');
    ?>
    <div class="wrap">
        <h1>🧩 Mapping Profiles</h1>
        <p>Create reusable JSON mapping profiles for the <strong>Map fields from description</strong> automation.</p>

        <h2><?php echo $editing ? 'Edit Profile' : 'New Profile'; ?></h2>
        <form method="post">
            <?php wp_nonce_field('asana_automator_save_mapping_profile'); ?>
            <table class="form-table">
                <tr>
                    <th><label for="profile_key">Profile Key</label></th>
                    <td>
                        <?php if ($editing): ?>
                            <input type="text" id="profile_key" name="profile_key" value="<?php echo esc_attr($edit_key); ?>" class="regular-text" readonly>
                        <?php else: ?>
                            <input type="text" id="profile_key" name="profile_key" value="" class="regular-text" placeholder="copfm-maintenance">
                            <p class="description">Lowercase letters, numbers, hyphens, and underscores only. Leave blank to auto-generate from label.</p>
                        <?php endif; ?>
                    </td>
                </tr>
                <tr>
                    <th><label for="profile_label">Profile Label</label></th>
                    <td>
                        <input type="text" id="profile_label" name="profile_label" value="<?php echo esc_attr($editing['label'] ?? ''); ?>" class="regular-text" required>
                    </td>
                </tr>
                <tr>
                    <th><label for="mapping_rules_json">Mapping Rules JSON</label></th>
                    <td>
                        <textarea id="mapping_rules_json" name="mapping_rules_json" rows="16" class="large-text code" required><?php echo esc_textarea($editing['mapping_rules_json'] ?? '[]'); ?></textarea>
                        <p class="description">Must be a JSON array. This profile can be selected from Automation Rules.</p>
                    </td>
                </tr>
            </table>
            <?php submit_button($editing ? 'Update Profile' : 'Save Profile', 'primary', 'asana_automator_save_mapping_profile'); ?>
        </form>

        <h2 style="margin-top:40px;">Saved Profiles</h2>
        <?php if (empty($profiles)): ?>
            <p>No mapping profiles yet.</p>
        <?php else: ?>
            <table class="widefat striped" style="max-width:980px;">
                <thead>
                    <tr>
                        <th>Key</th>
                        <th>Label</th>
                        <th>Updated</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($profiles as $profile_key => $profile): ?>
                        <tr>
                            <td><?php echo esc_html($profile_key); ?></td>
                            <td><?php echo esc_html($profile['label'] ?? $profile_key); ?></td>
                            <td><?php echo esc_html($profile['updated_at'] ?? '-'); ?></td>
                            <td>
                                <a class="button button-small" href="<?php echo esc_url(admin_url('admin.php?page=asana-automator-mappings&edit_profile=' . rawurlencode($profile_key))); ?>">Edit</a>
                                <?php $delete_url = wp_nonce_url(admin_url('admin.php?page=asana-automator-mappings&delete_profile=' . rawurlencode($profile_key)), 'asana_automator_delete_mapping_profile_' . $profile_key); ?>
                                <a class="button button-small" href="<?php echo esc_url($delete_url); ?>" onclick="return confirm('Delete this mapping profile?');" style="margin-left:6px;">Delete</a>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        <?php endif; ?>
    </div>
    <?php
}
