<?php

namespace App\Services;

use Mailjet\Client;
use Mailjet\Resources;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class MailjetService
{
    protected Client $client;

    public function __construct()
    {
        $this->client = new Client(
            getenv('MAILJET_APIKEY_PUBLIC'),
            getenv('MAILJET_SECRETKEY'),
            true,
            ['version' => 'v3.1']
        );
    }

    /**
     * Send an email via Mailjet API
     *
     * @param string $toEmail Recipient email address
     * @param string $toName Recipient name
     * @param string $subject Email subject
     * @param string $htmlContent HTML email content
     * @param string|null $textContent Plain text email content
     * @param array|null $attachments Array of file paths to attach
     * @param array|null $attachmentNames Optional custom filenames for attachments (by file path)
     * @return bool Success status
     */
    public function send(
        string $toEmail,
        string $toName,
        string $subject,
        string $htmlContent,
        ?string $textContent = null,
        ?array $attachments = null,
        ?array $attachmentNames = null
    ): bool {
        try {
            $body = [
                'Messages' => [
                    [
                        'From' => [
                            'Email' => config('mail.from.address'),
                            'Name' => config('mail.from.name'),
                        ],
                        'To' => [
                            [
                                'Email' => $toEmail,
                                'Name' => $toName,
                            ]
                        ],
                        'Subject' => $subject,
                        'HTMLPart' => $htmlContent,
                    ]
                ]
            ];

            // Add text part if provided
            if ($textContent) {
                $body['Messages'][0]['TextPart'] = $textContent;
            }

            // Add attachments if provided
            if ($attachments && is_array($attachments)) {
                $body['Messages'][0]['Attachments'] = [];
                foreach ($attachments as $filePath) {
                    if (file_exists($filePath)) {
                        $fileContent = file_get_contents($filePath);
                        // Use custom filename if provided, otherwise use basename
                        $filename = $attachmentNames[$filePath] ?? basename($filePath);
                        $body['Messages'][0]['Attachments'][] = [
                            'ContentType' => mime_content_type($filePath) ?: 'application/octet-stream',
                            'Filename' => $filename,
                            'Base64Content' => base64_encode($fileContent),
                        ];
                    }
                }
            }

            $response = $this->client->post(Resources::$Email, ['body' => $body]);

            if ($response->success()) {
                Log::info('Mailjet email sent successfully', [
                    'to' => $toEmail,
                    'subject' => $subject,
                    'response' => $response->getData(),
                ]);
                return true;
            } else {
                Log::error('Mailjet email failed', [
                    'to' => $toEmail,
                    'subject' => $subject,
                    'error' => $response->getStatus(),
                    'data' => $response->getData(),
                ]);
                return false;
            }
        } catch (\Exception $e) {
            Log::error('Mailjet email exception', [
                'to' => $toEmail,
                'subject' => $subject,
                'exception' => $e->getMessage(),
            ]);
            return false;
        }
    }
}
