<?php
// task-comms/ajax-save-settings.php
add_action( 'wp_ajax_afb_save_gateway_settings',        'afb_handle_save_gateway_settings' );
add_action( 'wp_ajax_nopriv_afb_save_gateway_settings', 'afb_handle_save_gateway_settings' );
add_action( 'wp_ajax_afb_send_gateway_test_email',        'afb_handle_send_gateway_test_email' );
add_action( 'wp_ajax_nopriv_afb_send_gateway_test_email', 'afb_handle_send_gateway_test_email' );

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

function afb_gateway_settings_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_handle_save_gateway_settings() {
    $token = sanitize_text_field( $_POST['token'] ?? '' );

    if ( ! $token || ! afb_get_task_id_by_token( $token ) ) {
        wp_send_json_error( [ 'message' => 'Invalid token.' ] );
    }

    $save_bucket = 'save_settings|' . $token . '|' . afb_gateway_settings_request_ip();
    if ( afb_gateway_settings_rate_limit_hit( $save_bucket, 30, 60 ) ) {
        wp_send_json_error( [ 'message' => 'Too many save requests. Please wait a minute and try again.' ] );
    }

    $allowed = [
        'email_collaborators_on_comment',
        'email_collaborators_on_upload',
        'email_assignee_on_comment',
        'email_assignee_on_upload',
    ];

    $settings = afb_get_gateway_settings( $token );

    foreach ( $allowed as $key ) {
        if ( array_key_exists( $key, $_POST ) ) {
            $settings[ $key ] = ( $_POST[ $key ] === '1' || $_POST[ $key ] === 'true' );
        }
    }

    $settings['last_saved'] = gmdate( 'c' );
    afb_save_gateway_settings( $token, $settings );

    wp_send_json_success( [ 'message' => 'Settings saved.' ] );
}

function afb_handle_send_gateway_test_email() {
    $token = sanitize_text_field( $_POST['token'] ?? '' );

    if ( ! $token || ! afb_get_task_id_by_token( $token ) ) {
        wp_send_json_error( [ 'message' => 'Invalid token.' ] );
    }

    $test_bucket = 'test_email|' . $token . '|' . afb_gateway_settings_request_ip();
    if ( afb_gateway_settings_rate_limit_hit( $test_bucket, 5, 15 * MINUTE_IN_SECONDS ) ) {
        wp_send_json_error( [ 'message' => 'Too many test emails. Please wait 15 minutes and try again.' ] );
    }

    $pat = afb_get_active_pat_token();
    if ( ! $pat ) {
        $pat = get_option( 'asana_access_token' );
    }
    if ( ! $pat ) {
        afb_debug_log( '❌ Test gateway email aborted: missing Asana PAT.' );
        wp_send_json_error( [ 'message' => 'Missing Asana PAT token.' ] );
    }

    $cache_path = AFB_PLUGIN_DIR . 'cache/tasks-summary-' . $token . '.json';
    if ( ! file_exists( $cache_path ) ) {
        afb_debug_log( '❌ Test gateway email aborted: cache file missing at ' . $cache_path );
        wp_send_json_error( [ 'message' => 'Task summary cache not found for this gateway.' ] );
    }

    $data      = json_decode( file_get_contents( $cache_path ), true );
    $task      = $data['parent'] ?? [];
    $task_name = $task['name'] ?? 'Your request';
    $task_gid  = afb_get_task_id_by_token( $token );
    $gateway_url = home_url( '/task-dashboard/' . $token . '/?task_gid=' . $task_gid );

    $recipient_email = '';
    $recipient_name  = '';

    if ( ! empty( $task['assignee'] ) ) {
        $recipient_email = sanitize_email( $task['assignee']['email'] ?? '' );
        if ( ! is_email( $recipient_email ) && ! empty( $task['assignee']['gid'] ) ) {
            $recipient_email = afb_get_user_email_by_gid( $task['assignee']['gid'], $pat );
        }
        $recipient_name  = $task['assignee']['name'] ?? '';
    }

    if ( ! is_email( $recipient_email ) ) {
        foreach ( $task['followers'] ?? [] as $f ) {
            $email = sanitize_email( $f['email'] ?? '' );
            if ( ! is_email( $email ) && ! empty( $f['gid'] ) ) {
                $email = afb_get_user_email_by_gid( $f['gid'], $pat );
            }
            if ( is_email( $email ) ) {
                $recipient_email = $email;
                $recipient_name  = $f['name'] ?? '';
                break;
            }
        }
    }

    $used_fallback = false;
    if ( ! is_email( $recipient_email ) ) {
        $fallback = afb_get_gateway_fallback_email();
        if ( is_email( $fallback ) ) {
            $recipient_email = $fallback;
            $recipient_name  = 'Team';
            $used_fallback   = true;
            afb_debug_log( '⚠️ Test gateway email using fallback recipient: ' . $recipient_email );
        }
    }

    if ( ! is_email( $recipient_email ) ) {
        afb_debug_log( '❌ Test gateway email aborted: no valid assignee/collaborator email and no fallback recipient.' );
        wp_send_json_error( [ 'message' => 'Could not resolve an assignee/collaborator email from Asana, and no fallback email is configured.' ] );
    }

    $sent = afb_send_gateway_notification_email( [
        'to'          => $recipient_email,
        'name'        => $recipient_name,
        'event'       => 'comment',
        'task_name'   => $task_name,
        'gateway_url' => $gateway_url,
        'actor_name'  => 'Client Gateway (Test)',
        'actor_email' => '',
        'comment'     => 'This is a test notification from the Settings tab.',
    ] );

    afb_debug_log( sprintf(
        '%s Test gateway email | token=%s to=%s',
        $sent ? '✅' : '❌',
        $token,
        $recipient_email
    ) );

    if ( ! $sent ) {
        wp_send_json_error( [ 'message' => 'wp_mail returned false. Check plugin debug logs for PHPMailer details.' ] );
    }

    $message = $used_fallback
        ? 'Test email sent to fallback recipient: ' . $recipient_email
        : 'Test email sent to ' . $recipient_email;

    wp_send_json_success( [
        'message' => $message,
        'to'      => $recipient_email,
    ] );
}
