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

// 🔄 Fetch Workspaces
add_action('wp_ajax_get_asana_workspaces', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $token = asana_automator_get_pat_token();

    if (!$token) wp_send_json_error('Missing PAT');

    $res = wp_remote_get('https://app.asana.com/api/1.0/workspaces', [
        'headers' => ['Authorization' => 'Bearer ' . $token],
    ]);

    if (is_wp_error($res)) wp_send_json_error('API Error');

    $workspaces = json_decode(wp_remote_retrieve_body($res), true);
    wp_send_json_success($workspaces['data']);
});

// 💾 Save Selected Workspace
add_action('wp_ajax_save_asana_workspace', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $gid = sanitize_text_field($_POST['workspace_gid'] ?? '');
    $name = sanitize_text_field($_POST['workspace_name'] ?? '');

    if (!$gid || !$name) wp_send_json_error('Missing workspace info');

    update_option('asana_workspace_gid', $gid);
    update_option('asana_workspace_name', $name);

    wp_send_json_success('Saved');
});

// 📁 Fetch Projects
add_action('wp_ajax_get_asana_projects', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $workspace_gid = asana_automator_get_workspace_gid();
    $pat_accounts = asana_automator_get_pat_accounts();
    $projects = [];

    foreach ($pat_accounts as $label => $token) {
        $res = wp_remote_get("https://app.asana.com/api/1.0/projects?workspace={$workspace_gid}", [
            'headers' => ['Authorization' => 'Bearer ' . $token]
        ]);

        if (is_wp_error($res)) continue;

        $data = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];
        foreach ($data as $p) {
            $p['source_label'] = $label;
            $projects[] = $p;
        }
    }

    if (empty($projects)) wp_send_json_error('No projects found');

    wp_send_json_success($projects);
});

// 📂 Fetch Sections
add_action('wp_ajax_get_asana_sections', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $project_gid = sanitize_text_field($_GET['project_gid'] ?? '');
    $pat_label = sanitize_text_field($_GET['pat_label'] ?? '');
    $token = asana_automator_get_pat_token($pat_label);

    if (!$project_gid || !$token) wp_send_json_error('Missing info');

    $res = wp_remote_get("https://app.asana.com/api/1.0/projects/{$project_gid}/sections", [
        'headers' => ['Authorization' => 'Bearer ' . $token]
    ]);

    if (is_wp_error($res)) wp_send_json_error('API Error');

    $sections = json_decode(wp_remote_retrieve_body($res), true);
    wp_send_json_success($sections['data']);
});

// 🔎 Fetch Custom Fields for Project
add_action('wp_ajax_get_asana_project_fields', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $project_gid = sanitize_text_field($_GET['project_gid'] ?? '');
    $pat_label = sanitize_text_field($_GET['pat_label'] ?? '');
    $token = asana_automator_get_pat_token($pat_label);

    if (!$project_gid || !$token) wp_send_json_error('Missing info');

    $res = wp_remote_get("https://app.asana.com/api/1.0/projects/{$project_gid}/custom_field_settings", [
        'headers' => ['Authorization' => 'Bearer ' . $token]
    ]);

    if (is_wp_error($res)) wp_send_json_error('API Error');

    $fields_raw = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];

    $fields = array_map(function ($f) {
        return [
            'gid' => $f['custom_field']['gid'],
            'name' => $f['custom_field']['name'],
            'type' => $f['custom_field']['type']
        ];
    }, $fields_raw);

    wp_send_json_success($fields);
});

// 🔖 Get tags used in a project (by scanning tasks)
add_action('wp_ajax_get_asana_project_tags', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Permission denied');
    }

    $project_gid = sanitize_text_field($_GET['project_gid'] ?? '');
    $label = sanitize_text_field($_GET['pat_label'] ?? '');
    $token = asana_automator_get_pat_token($label);

    if (!$project_gid || !$token) {
        wp_send_json_error('Missing project GID or token');
    }

    $all_tags = [];
    $seen_tag_gids = [];
    $limit = 50;
    $offset = null;

    do {
        $url = "https://app.asana.com/api/1.0/projects/{$project_gid}/tasks?opt_fields=tags.gid,tags.name&limit={$limit}";
        if ($offset) {
            $url .= "&offset=" . urlencode($offset);
        }

        $res = wp_remote_get($url, [
            'headers' => [
                'Authorization' => 'Bearer ' . $token,
            ]
        ]);

        if (is_wp_error($res)) {
            wp_send_json_error(['message' => $res->get_error_message()]);
        }

        $body = json_decode(wp_remote_retrieve_body($res), true);
        $tasks = $body['data'] ?? [];

        foreach ($tasks as $task) {
            if (!empty($task['tags'])) {
                foreach ($task['tags'] as $tag) {
                    if (!in_array($tag['gid'], $seen_tag_gids)) {
                        $all_tags[] = $tag;
                        $seen_tag_gids[] = $tag['gid'];
                    }
                }
            }
        }

        $offset = $body['next_page']['offset'] ?? null;
    } while ($offset);

    wp_send_json_success($all_tags);
});

// 👤 Get users
add_action('wp_ajax_get_asana_users', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $workspace_gid = asana_automator_get_workspace_gid();
    $token = asana_automator_get_pat_token();

    if (!$workspace_gid || !$token) wp_send_json_error('Missing workspace or token');

    $res = wp_remote_get("https://app.asana.com/api/1.0/users?workspace={$workspace_gid}", [
        'headers' => ['Authorization' => 'Bearer ' . $token]
    ]);

    if (is_wp_error($res)) wp_send_json_error('API error');

    $users = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];
    wp_send_json_success($users);
});

// 🧾 Get enum options for a custom field
add_action('wp_ajax_get_custom_field_options', function () {
    if (!current_user_can('manage_options')) wp_send_json_error('Permission denied');

    $field_gid = sanitize_text_field($_GET['field_gid'] ?? '');
    $token = asana_automator_get_pat_token();

    if (!$field_gid || !$token) wp_send_json_error('Missing field GID or token');

    $res = wp_remote_get("https://app.asana.com/api/1.0/custom_fields/{$field_gid}", [
        'headers' => ['Authorization' => 'Bearer ' . $token]
    ]);

    if (is_wp_error($res)) wp_send_json_error('API error');

    $field = json_decode(wp_remote_retrieve_body($res), true)['data'] ?? [];
    $options = $field['enum_options'] ?? [];

    wp_send_json_success($options);
});

// 🪄 Bootstrap mapping rules JSON from selected project field settings
add_action('wp_ajax_asana_automator_bootstrap_mapping_rules', function () {
    if (!current_user_can('manage_options')) {
        wp_send_json_error(['message' => 'Permission denied']);
    }

    $project_gid = sanitize_text_field($_GET['project_gid'] ?? '');
    $pat_label = sanitize_text_field($_GET['pat_label'] ?? '');
    $token = asana_automator_get_pat_token($pat_label);

    if (!$project_gid || !$token) {
        wp_send_json_error(['message' => 'Missing project GID or PAT token']);
    }

    $bootstrap = asana_automator_bootstrap_mapping_rules_for_project($project_gid, $token);
    if (empty($bootstrap['ok'])) {
        wp_send_json_error(['message' => $bootstrap['message'] ?? 'Could not generate mapping rules']);
    }

    wp_send_json_success([
        'mapping_rules_json' => (string)$bootstrap['json'],
        'rule_count' => count((array)($bootstrap['rules'] ?? [])),
    ]);
});
