<?php
/**
 * AJAX handler to send “Email me a copy” directly from the task-creation success page.
 * Path: task-comms/partials/handlers/email-copy-ajax.php
 */

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

add_action('wp_ajax_afb_send_email_request',        'afb_handle_ajax_email_copy_direct');
add_action('wp_ajax_nopriv_afb_send_email_request', 'afb_handle_ajax_email_copy_direct');

function afb_handle_ajax_email_copy_direct() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        wp_send_json_error(['message' => 'Invalid request method.']);
    }

    $task_gid    = sanitize_text_field($_POST['task_gid'] ?? '');
    $email       = sanitize_email($_POST['send_email_to'] ?? '');
    $job_number  = sanitize_text_field($_POST['job_number'] ?? '');

    if (!$task_gid || !is_email($email)) {
        afb_debug_log("❌ Invalid request: task_gid={$task_gid}, email={$email}");
        wp_send_json_error(['message' => 'Missing or invalid task_gid/email.']);
    }

    if (!function_exists('afb_asana_request_for_task')) {
        afb_debug_log('❌ Email copy aborted: task token routing helper unavailable.');
        wp_send_json_error(['message' => 'Task lookup helper unavailable.']);
    }

    afb_debug_log("📩 Sending email copy for task_gid={$task_gid} to {$email}");

    /* 1) Pull task (name + notes + custom fields) through token-routing helper */
    $task_url = "https://app.asana.com/api/1.0/tasks/{$task_gid}"
              . "?opt_fields=name,notes,custom_fields.name,custom_fields.text_value,"
              . "custom_fields.enum_value,custom_fields.number_value";
    $task_result = afb_asana_request_for_task($task_gid, $task_url, 'GET', null, [200]);

    if (empty($task_result['success'])) {
        $http = (int) ($task_result['code'] ?? 0);
        $body = substr((string) ($task_result['body'] ?? ''), 0, 280);
        afb_debug_log("❌ Failed to load task payload for email copy | task_gid={$task_gid} http={$http} body={$body}");
        wp_send_json_error(['message' => 'Failed to load task data from Asana.']);
    }

    $task_payload = json_decode((string) ($task_result['body'] ?? ''), true);
    $task = is_array($task_payload['data'] ?? null) ? $task_payload['data'] : [];
    if (empty($task)) {
        afb_debug_log("❌ No data returned from Asana API for task_gid={$task_gid}");
        wp_send_json_error(['message' => 'Empty task data from Asana.']);
    }

    $task_name = sanitize_text_field((string) ($task['name'] ?? 'Request'));
    $custom_fields = is_array($task['custom_fields'] ?? null) ? $task['custom_fields'] : [];
    $resolved_token = (string) ($task_result['token'] ?? '');

    /* 2) Render custom fields HTML */
    $fields_html = afb_build_email_copy_fields_html(
        $task_name,
        $custom_fields,
        $job_number
    );

    /* 3) Fetch the “Submitted Copy … .doc/.docx” attachment(s) */
    $attachment_paths = afb_fetch_submitted_copy_docs($task_gid, $resolved_token); // may return multiple
    afb_debug_log('📎 Email attachments resolved: ' . json_encode($attachment_paths));

    /* 4) Build link + send email */
    $asana_link  = "https://app.asana.com/0/{$task_gid}/{$task_gid}";
    $request_num = $task_name;

    require_once plugin_dir_path(__FILE__) . '../../../includes/email-sender.php';
    $sent = afb_send_submission_email([
        'to'             => $email,
        'task_name'      => $task_name,
        'request_number' => $request_num,
        'job_number'     => $job_number,
        'comms_link'     => $asana_link,
        'fields_html'    => $fields_html,
        'attachments'    => $attachment_paths,
    ]);

    // Clean temp files
    foreach ($attachment_paths as $p) {
        if (is_string($p) && file_exists($p)) @unlink($p);
    }

    if (!$sent) {
        afb_debug_log("❌ wp_mail failed to send to {$email} for task_gid={$task_gid}");
        wp_send_json_error(['message' => 'Email could not be sent.']);
    }

    afb_debug_log("✅ Email sent successfully to {$email} for task {$task_gid}");
    wp_send_json_success(['message' => 'Email sent successfully.']);
}

/**
 * Build the success-box email details with a strict field allowlist/order.
 */
function afb_build_email_copy_fields_html($task_name, array $custom_fields, $job_number_fallback = '') {
    $task_name = trim((string) $task_name);

    $identity = afb_get_email_copy_identity_from_admin_map($custom_fields);

    $job_number = trim((string) $job_number_fallback);
    if ($job_number === '' && function_exists('afb_get_global_field_map_data')) {
        $map = afb_get_global_field_map_data();
        $job_gid_candidates = afb_collect_email_copy_gids_from_map($map, ['job_number', 'request_number']);
        $job_number = afb_get_email_copy_value_by_gid($custom_fields, $job_gid_candidates);
    }

    $first_name = (string) ($identity['first_name'] ?? '');
    $last_name = (string) ($identity['last_name'] ?? '');
    $email = (string) ($identity['email'] ?? '');

    $rows = [
        'Task Name' => $task_name,
        'Job Number' => $job_number,
        'First Name' => $first_name,
        'Last Name' => $last_name,
        'Email Address' => $email,
    ];

    $html = '<ul style="margin:0;padding-left:18px">';
    foreach ($rows as $label => $value) {
        $html .= '<li style="margin:0 0 8px"><strong>' . esc_html($label) . ':</strong> ' . esc_html((string) $value) . '</li>';
    }
    $html .= '</ul>';

    return $html;
}

function afb_get_email_copy_identity_from_admin_map(array $custom_fields): array {
    $identity = [
        'first_name' => '',
        'last_name' => '',
        'email' => '',
    ];

    if (!function_exists('afb_get_global_field_map_data')) {
        return $identity;
    }

    $map = afb_get_global_field_map_data();
    if (!is_array($map) || empty($map)) {
        return $identity;
    }

    if (!function_exists('afb_collect_identity_gids_from_map')) {
        return $identity;
    }

    $gid_candidates = afb_collect_identity_gids_from_map($map);
    $identity['first_name'] = afb_get_email_copy_value_by_gid($custom_fields, (array) ($gid_candidates['first_name'] ?? []));
    $identity['last_name'] = afb_get_email_copy_value_by_gid($custom_fields, (array) ($gid_candidates['last_name'] ?? []));
    $identity['email'] = afb_get_email_copy_value_by_gid($custom_fields, (array) ($gid_candidates['email'] ?? []));

    return $identity;
}

function afb_get_email_copy_value_by_gid(array $custom_fields, array $gid_candidates): string {
    $gid_candidates = array_values(array_unique(array_filter(array_map(static function ($gid) {
        return preg_replace('/\\D+/', '', (string) $gid);
    }, $gid_candidates), static function ($gid) {
        return $gid !== '';
    })));

    if (empty($gid_candidates)) {
        return '';
    }

    $values_by_gid = [];

    foreach ($custom_fields as $field) {
        if (!is_array($field)) {
            continue;
        }

        $gid = preg_replace('/\\D+/', '', (string) ($field['gid'] ?? ''));
        if ($gid === '') {
            continue;
        }

        if (function_exists('afb_task_custom_field_scalar_value')) {
            $value = trim((string) afb_task_custom_field_scalar_value($field));
        } else {
            $value = '';
            if (isset($field['text_value']) && $field['text_value'] !== null) {
                $value = (string) $field['text_value'];
            } elseif (!empty($field['enum_value']['name'])) {
                $value = (string) $field['enum_value']['name'];
            } elseif (isset($field['number_value']) && $field['number_value'] !== null) {
                $value = (string) $field['number_value'];
            }
            $value = trim($value);
        }

        if ($value !== '') {
            $values_by_gid[$gid] = $value;
        }
    }

    foreach ($gid_candidates as $gid) {
        if (!empty($values_by_gid[$gid])) {
            return (string) $values_by_gid[$gid];
        }
    }

    return '';
}

function afb_collect_email_copy_gids_from_map(array $map, array $keys): array {
    $keys = array_values(array_unique(array_filter(array_map('strval', $keys))));
    if (empty($keys)) {
        return [];
    }

    $out = [];
    $walk = static function ($node) use (&$walk, &$out, $keys) {
        if (!is_array($node)) {
            return;
        }

        foreach ($node as $k => $v) {
            if (is_array($v)) {
                $walk($v);
                continue;
            }

            if (!in_array((string) $k, $keys, true)) {
                continue;
            }

            $gid = preg_replace('/\D+/', '', (string) $v);
            if ($gid !== '') {
                $out[] = $gid;
            }
        }
    };

    $walk($map);
    return array_values(array_unique($out));
}

/**
 * Poll Asana for up to 10s for any “Submitted Copy … .doc/.docx” attachments,
 * download them to temp files, and return an array of local paths.
 */
function afb_fetch_submitted_copy_docs($task_gid, $preferred_token = '') {
    $deadline = time() + 15;
    $seen = [];
    $paths = [];

    while (time() < $deadline) {
        $url = "https://app.asana.com/api/1.0/tasks/{$task_gid}/attachments"
             . "?opt_fields=name,download_url,hosted_url,created_at,size";
        $list_result = afb_asana_request_for_task($task_gid, $url, 'GET', null, [200], (string) $preferred_token);
        if (empty($list_result['success'])) {
            $http = (int) ($list_result['code'] ?? 0);
            $body = substr((string) ($list_result['body'] ?? ''), 0, 180);
            afb_debug_log("⚠️ fetch atts failed | task={$task_gid} http={$http} body={$body}");
            sleep(1);
            continue;
        }

        $body = json_decode((string) ($list_result['body'] ?? ''), true);
        $list = $body['data'] ?? [];
        $token = (string) ($list_result['token'] ?? $preferred_token);

        // newest first
        usort($list, fn($a,$b) => strcmp($b['created_at'] ?? '', $a['created_at'] ?? ''));

        foreach ($list as $att) {
            $name = (string)($att['name'] ?? '');
            if (!$name) continue;

            // accept "Submitted Copy", "Submitted-Copy", "Submitted_Copy"
            if (!preg_match('/^Submitted[\s\-_]*Copy\b/i', $name)) continue;

            if (!preg_match('/\.docx?$/i', $name)) continue;

            $key = md5($name.($att['download_url'] ?? '').($att['hosted_url'] ?? ''));
            if (isset($seen[$key])) continue;
            $seen[$key] = true;

            $dl   = (string)($att['download_url'] ?? '');
            $host = (string)($att['hosted_url']   ?? '');

            $tries = [];
            if ($dl)   $tries[] = ['url'=>$dl,   'headers'=>[]];
            if ($dl && $token !== '')   $tries[] = ['url'=>$dl,   'headers'=>['Authorization'=>'Bearer '.$token]];
            if ($host && $token !== '') $tries[] = ['url'=>$host, 'headers'=>['Authorization'=>'Bearer '.$token]];
            if ($host)                  $tries[] = ['url'=>$host, 'headers'=>[]];

            foreach ($tries as $i => $t) {
                $fr = wp_remote_get($t['url'], [
                    'headers'     => array_merge($t['headers'], ['Accept'=>'application/octet-stream']),
                    'timeout'     => 30,
                    'redirection' => 5,
                ]);
                if (is_wp_error($fr)) { afb_debug_log("⚠️ get file err try{$i} {$name}: ".$fr->get_error_message()); continue; }
                $code = wp_remote_retrieve_response_code($fr);
                if ($code < 200 || $code >= 300) { afb_debug_log("⚠️ get file code {$code} try{$i} {$name}"); continue; }

                $bin = wp_remote_retrieve_body($fr);
                if ($bin === '') { afb_debug_log("⚠️ empty body for {$name}"); continue; }

                $uploads = wp_upload_dir();
                $tmp_dir = trailingslashit($uploads['basedir']).'asana-temp';
                if (!file_exists($tmp_dir)) wp_mkdir_p($tmp_dir);

                $path = trailingslashit($tmp_dir).sanitize_file_name($name);
                if (file_put_contents($path, $bin) !== false) {
                    afb_debug_log("✅ downloaded submitted-copy attachment to {$path}");
                    $paths[] = $path;
                }
                break; // stop tries for this attachment
            }
        }

        if (!empty($paths)) return $paths;
        sleep(1);
    }

    afb_debug_log("ℹ️ No Submitted Copy .doc/.docx found for {$task_gid} after polling.");
    return [];
}
