<?php
// includes/task-handler.php (LEGACY SHIM → modular flow)
if (!defined('ABSPATH')) exit;

/**
 * Purpose
 * -------
 * Keep the legacy AJAX endpoint `afb_create_asana_task` working, but delegate the
 * real work to the fast modular creator in includes/api/create-task.php.
 *
 * Notes
 * -----
 * • Long-running work (uploads, multi-home, doc attach) is handled by:
 *     - includes/api/attach-file.php       (packetised uploads)
 *     - includes/jobs/enrich-task.php      (background enrichment)
 * • Content normalisation lives in includes/functions/triagesummary/triagesummary.php
 * • Field auto-mapping (e.g. Channel IC) is applied inside create-task.php
 */

require_once AFB_PLUGIN_DIR . 'includes/lib/asana-client.php';
require_once AFB_PLUGIN_DIR . 'includes/api/create-task.php'; // exposes afb_api_create_task_fast()
require_once AFB_PLUGIN_DIR . 'includes/functions/triagesummary/triagesummary.php';

// ────────────────────────────────────────────────────────────────
// Back-compat helpers (kept for older callers)
// ────────────────────────────────────────────────────────────────

/**
 * DEPRECATED:
 * Prefer afb_normalize_html_for_asana() + *_combined_* helpers.
 * Kept for BC; delegates to the central normaliser.
 */
function afb_sanitize_triage_summary_html($html, $first_name = '') {
    return afb_normalize_html_for_asana((string)$html);
}

/**
 * Lightweight notes updater (plain text). Prefer setting notes at CREATE.
 */
function afb_update_asana_task_description_plain($task_gid, $notes_plain, $pat) {
    $payload = ['notes' => (string)$notes_plain];

    $r = afb_asana_request(
        'PUT',
        "https://app.asana.com/api/1.0/tasks/{$task_gid}",
        (string)$pat,
        ['json' => $payload],
        3 // retries
    );

    if (($r['code'] ?? 0) !== 200 && function_exists('afb_log')) {
        afb_log("notes update failed {$task_gid} http={$r['code']}", 'asana_update_notes');
    }
}

/**
 * Lightweight notes updater (HTML fragment). Prefer CREATE with html_notes when possible.
 */
function afb_update_asana_task_description_html($task_gid, $triage_html, $request_details_text, $submitted_copy_plain, $pat) {
    $fragment = afb_generate_combined_summary_html(
        (string)$triage_html,
        (string)$request_details_text
    );

    // Ensure <body> wrapper for html_notes payload
    if (!preg_match('/<body\b/i', $fragment)) {
        $fragment = '<body>' . $fragment . '</body>';
    }

    $payload = ['html_notes' => $fragment];

    $r = afb_asana_request(
        'PUT',
        "https://app.asana.com/api/1.0/tasks/{$task_gid}",
        (string)$pat,
        ['json' => $payload],
        3
    );

    if (($r['code'] ?? 0) !== 200 && function_exists('afb_log')) {
        afb_log("html_notes update failed {$task_gid} http={$r['code']}", 'asana_update_notes');
    }
}

// ────────────────────────────────────────────────────────────────
/* Legacy AJAX endpoint → shim to fast creator */
// ────────────────────────────────────────────────────────────────

add_action('wp_ajax_afb_create_asana_task',       'afb_handle_create_asana_task');
add_action('wp_ajax_nopriv_afb_create_asana_task','afb_handle_create_asana_task');

/**
 * Legacy handler now forwards to the fast, modular endpoint and returns immediately.
 * It:
 *  - guarantees request_id
 *  - seeds upload_count for legacy multi-file inputs
 *  - passes through submitted_copy fields when present
 *  - defers to afb_api_create_task_fast() which wp_send_json_* and exits
 */
function afb_handle_create_asana_task() {
    // Stable request identifier for downstream logs/workers
    if (empty($_POST['request_id']) || !is_string($_POST['request_id'])) {
        $_POST['request_id'] = uniqid('srv_', true);
    }

    // Seed upload_count from legacy multi-file input if present
    if (!isset($_POST['upload_count'])) {
        $count = 0;
        if (!empty($_FILES['uploads']['name']) && is_array($_FILES['uploads']['name'])) {
            foreach ($_FILES['uploads']['name'] as $n) {
                if ($n !== '' && $n !== null) $count++;
            }
        }
        $_POST['upload_count'] = $count;
    }

    // (Optional) submitted_copy_html/plain passthrough for enrich worker (no-op if absent)
    // if (!isset($_POST['submitted_copy_html']) && isset($_POST['ai_summary'])) { /* left intentionally blank */ }

    // Delegate to the modern fast creator (handles JSON response + exit)
    afb_api_create_task_fast();
    // No code after this; afb_api_create_task_fast() terminates with wp_send_json_*
}
