<?php

namespace Tricks\CampaignMonitor\Helpers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class Transactional
{
    /**
     * Send a given Transational
     * @param  string  $transactional Token of the transaction. Must be configured in config/campaignmonitor.php.
     * @param  array  $data Array with keys as defined in config/campaignmonitor.php and data with corresponding values.
     * @return bool|array True when the Transaction was sent successfully, array with Response json otherwise.
     */
    public static function send(string $transactional, array $data): bool|array
    {
        $response = Http::timeout(120)->acceptJson()->post(route('api.campaignmonitor.transactional.'.$transactional), $data);

        if(Str::contains($response->body(), 'Accepted')) {
            return true;
        }
        Log::error('Failed to send transactional', [
            'transactional' => $transactional,
            'data' => $data,
            'body' => $response->json(),
        ]);
        return $response->json();
    }
}
