<?php

namespace App\Services;

use Postal\Client as PostalClient;
use Postal\Send\Message as PostalMessage;
use Illuminate\Support\Facades\Crypt;

class PostalAPIService
{
    public static function send($api_base_url, $api_key, $from_email, $from_name, $to_email, $reply_email, $subject, $content, $content_type = 'html', $message_id = null, $attachments_path = null, $attachments = null)
    {
        try {
            // Decrypt the API key if encrypted
            $decrypted_api_key = Crypt::decrypt($api_key);

            //$decrypted_api_key = $api_key;

            // Initialize Postal Client
            $client = new PostalClient($api_base_url, $decrypted_api_key);

            // Create new Postal message
            $message = new PostalMessage();

            // Set recipients (supporting multiple recipients, comma-separated)
            if (is_array($to_email)) {
                foreach ($to_email as $recipient) {
                    $message->to($recipient);
                }
            } else {
                $message->to($to_email);
            }

            // Set from address
            $message->from($from_email);

            // Set reply-to if provided
            if (!empty($reply_email)) {
                $message->replyTo($reply_email);
            }

            // Set subject
            $message->subject($subject);

            // Set content
            if ($content_type == 'html') {
                $message->htmlBody($content);
                $message->plainBody($content);
            } else {
                $message->plainBody($content);
            }

            // Set message ID or headers if provided
            if (!empty($message_id)) {
                $message->header('RZ-Message-ID', $message_id);
            }

            // Attachments
            if (!empty($attachments)) {
                foreach ($attachments as $filename) {
                    $attached_file = $attachments_path . DIRECTORY_SEPARATOR . $filename;
                    if (file_exists($attached_file)) {
                        $file_content = file_get_contents($attached_file);
                        $mime_type = mime_content_type($attached_file);

                        $message->attach($filename, $mime_type, $file_content);
                    }
                }
            }

            // Send the message
            $result = $client->send->message($message);
            return 'send';
        } catch (\Exception $e) {
            \Log::error('PostalService Exception: ' . $e->getMessage());
            return $e->getMessage();
        }
    }
}
