<?php
add_action('wp_ajax_afb_post_comment', 'afb_post_comment');
add_action('wp_ajax_nopriv_afb_post_comment', 'afb_post_comment');
add_action('wp_ajax_afb_get_comments_timeline_html', 'afb_get_comments_timeline_html');
add_action('wp_ajax_nopriv_afb_get_comments_timeline_html', 'afb_get_comments_timeline_html');

function afb_gateway_request_ip() {
    $raw = (string) ($_SERVER['REMOTE_ADDR'] ?? 'unknown');
    return sanitize_text_field($raw ?: 'unknown');
}

function afb_gateway_rate_limit_hit($bucket, $max_attempts, $window_seconds) {
    $key = 'afb_rl_' . md5((string) $bucket);
    $hits = (int) get_transient($key);
    $hits++;
    set_transient($key, $hits, (int) $window_seconds);
    return $hits > (int) $max_attempts;
}

function afb_gateway_validate_token_task_pair($gateway_token, $task_gid) {
    $gateway_token = sanitize_text_field((string) $gateway_token);
    $task_gid = sanitize_text_field((string) $task_gid);

    if ($gateway_token === '' || $task_gid === '' || !ctype_digit($task_gid)) {
        return false;
    }

    $mapped = (string) afb_get_task_id_by_token($gateway_token);
    return ($mapped !== '' && hash_equals($mapped, $task_gid));
}

function afb_post_comment() {
    // STEP 1: Validate and prepare request
    $task_gid     = sanitize_text_field($_POST['task_gid'] ?? '');
    $gateway_token = sanitize_text_field($_POST['gateway_token'] ?? '');
    $guest_name   = sanitize_text_field($_POST['guest_name'] ?? '');
    $guest_email  = sanitize_email($_POST['guest_email'] ?? '');
    $comment      = sanitize_textarea_field($_POST['comment'] ?? '');

    if (!$task_gid || !$comment) {
        wp_send_json_error(['message' => 'Missing task or comment.']);
    }

    if (!afb_gateway_validate_token_task_pair($gateway_token, $task_gid)) {
        wp_send_json_error(['message' => 'Invalid gateway token/task pair.']);
    }

    $ip = afb_gateway_request_ip();
    $rl_bucket = 'comment|' . $gateway_token . '|' . $ip;
    if (afb_gateway_rate_limit_hit($rl_bucket, 20, 60)) {
        wp_send_json_error(['message' => 'Too many requests. Please wait a minute and try again.']);
    }

    if (($guest_name === '' || $guest_email === '') && function_exists('afb_get_submitter_identity_from_task')) {
        $task_data = afb_get_asana_task_data($task_gid);
        if (is_array($task_data)) {
            $identity = afb_get_submitter_identity_from_task($task_data);
            if ($guest_name === '') {
                $guest_name = trim((string) ($identity['name'] ?? ''));
            }
            if ($guest_email === '') {
                $guest_email = sanitize_email((string) ($identity['email'] ?? ''));
            }
        }
    }

    $guest_prefix = '[Guest]';
    if ($guest_name !== '' && $guest_email !== '') {
        $guest_prefix .= " *{$guest_name}* ({$guest_email})";
    } elseif ($guest_name !== '') {
        $guest_prefix .= " *{$guest_name}*";
    } elseif ($guest_email !== '') {
        $guest_prefix .= " ({$guest_email})";
    }

    $full_comment = $guest_prefix . " wrote:\n\n{$comment}";

    // STEP 2: Post comment using task-aware PAT resolution
    $comment_result = afb_add_asana_comment($task_gid, $full_comment);
    if (!empty($comment_result['success'])) {
        // Send gateway notifications
        if ( $gateway_token ) {
            afb_send_gateway_notifications( $gateway_token, 'comment', [
                'actor_name'  => $guest_name,
                'actor_email' => $guest_email,
                'comment'     => $comment,
            ] );
        }
        wp_send_json_success(['message' => 'Comment posted']);
    } else {
        $error_message = (string) ($comment_result['error'] ?? 'Unknown error');
        wp_send_json_error(['message' => 'Asana error: ' . $error_message]);
    }
}

function afb_get_comments_timeline_html() {
    $task_gid = sanitize_text_field($_POST['task_gid'] ?? '');
    $gateway_token = sanitize_text_field($_POST['gateway_token'] ?? '');
    if (!$task_gid) {
        wp_send_json_error(['message' => 'Missing task_gid.']);
    }

    if (!afb_gateway_validate_token_task_pair($gateway_token, $task_gid)) {
        wp_send_json_error(['message' => 'Invalid gateway token/task pair.']);
    }

    $ip = afb_gateway_request_ip();
    $rl_bucket = 'timeline|' . $gateway_token . '|' . $ip;
    if (afb_gateway_rate_limit_hit($rl_bucket, 40, 60)) {
        wp_send_json_error(['message' => 'Too many requests. Please wait a minute and try again.']);
    }

    $comments = afb_get_asana_task_comments($task_gid);

    ob_start();
    include plugin_dir_path(__FILE__) . 'partials/layout/comments-timeline.php';
    $html = ob_get_clean();

    wp_send_json_success([
        'html' => (string) $html,
    ]);
}
