/**
 * Function to Send Bricks Form Data to Webhook
 */
function pro_bricks_form_to_webhook( $form ){

    $data = $form->get_fields();
    $settings = $form->get_settings();

    // Tạo mảng để ánh xạ ID với nhãn
    $field_labels = [];
    if (isset($settings['fields']) && is_array($settings['fields'])) {
        foreach ($settings['fields'] as $field) {
            if (isset($field['id']) && isset($field['label'])) {
                $field_labels[$field['id']] = $field['label'];
            }
        }
    }

    // Lấy địa chỉ IP của người dùng
    $user_ip = $_SERVER['REMOTE_ADDR'];

    // Chuẩn bị nội dung tin nhắn từ các trường trong form
    $message = "Form Submission:\n";
    foreach ($data as $field_key => $field_value) {
        if ($field_key !== 'formId' && $field_key !== 'referrer') {
            // Lấy nhãn từ mảng $field_labels, nếu không có thì để trống
            $field_id = str_replace('form-field-', '', $field_key);
            $field_label = isset($field_labels[$field_id]) ? $field_labels[$field_id] : ucfirst($field_id);
            $message .= "$field_label: " . (!empty($field_value) ? $field_value : 'N/A') . "\n";
        }
    }
    // Thêm trường Referrer và IP
    $message .= "Referrer: " . (isset($data['referrer']) ? $data['referrer'] : 'N/A') . "\n";
    $message .= "IP: $user_ip\n";

    // Telegram bot token và chat ID
    $bot_token = '8068594037:AAGu-5QdMMdkHhEYMrmgwR8xanI3XLeJeRM';
    $chat_id = '1675398386';

    // Telegram API URL
    $telegram_url = "https://api.telegram.org/bot$bot_token/sendMessage";

    // Chuẩn bị payload
    $args = [
        'body' => [
            'chat_id' => $chat_id,
            'text' => $message,
        ],
    ];

    // Gửi tin nhắn đến Telegram
    $response = wp_remote_post($telegram_url, $args);

    // Thiết lập phản hồi dựa trên kết quả gửi tin nhắn
    if (is_wp_error($response)) {
        $form->set_result([
            'action' => 'my_custom_action',
            'type'    => 'danger',
            'message' => 'Lỗi, vui lòng thử lại sau.',
        ]);
    } else {
        $form->set_result([
            'action' => 'my_custom_action',
            'type'    => 'success',
            'message' => 'Cảm ơn bạn đã để lại thông tin.',
        ]);
    }
}

add_action( 'bricks/form/custom_action', 'pro_bricks_form_to_webhook', 10, 1 );