<?php

namespace App\Modules\Email\Mailjet;

use App\Core\Email\AbstractEmail;
use Illuminate\Support\Facades\Http;

/**
 * PRC-106 — Mailjet email provider (EU-based, v3.1 API).
 *
 * Settings:
 *   api_key      — Mailjet public key
 *   api_secret   — Mailjet private key
 */
class Mailjet extends AbstractEmail
{
    protected string $apiUrl = 'https://api.mailjet.com/v3.1/send';

    public function sendEmail(array $params)
    {
        $validation = $this->validateEmailParams($params);
        if (! $validation['valid']) {
            return ['success' => false, 'errors' => $validation['errors']];
        }
        $key = $this->getConfig('api_key');
        $secret = $this->getConfig('api_secret');
        if (! $key || ! $secret) {
            return ['success' => false, 'error' => 'Mailjet api_key/api_secret missing'];
        }

        $message = [
            'From' => [
                'Email' => $params['from'] ?? $this->getConfig('from_email'),
                'Name' => $params['from_name'] ?? $this->getConfig('from_name', ''),
            ],
            'To' => $this->normaliseRecipients($params['to'] ?? []),
            'Subject' => $params['subject'],
            'HTMLPart' => $params['html_content'] ?? $params['content'] ?? '',
            'TextPart' => $params['text_content'] ?? $this->htmlToText($params['html_content'] ?? $params['content'] ?? ''),
        ];
        if (! empty($params['cc'])) {
            $message['Cc'] = $this->normaliseRecipients($params['cc']);
        }
        if (! empty($params['bcc'])) {
            $message['Bcc'] = $this->normaliseRecipients($params['bcc']);
        }
        if (! empty($params['attachments'])) {
            $message['Attachments'] = array_map(fn ($a) => [
                'ContentType' => $a['mime'] ?? 'application/octet-stream',
                'Filename' => $a['name'] ?? basename($a['path']),
                'Base64Content' => base64_encode(file_get_contents($a['path'])),
            ], $params['attachments']);
        }

        try {
            $resp = Http::withBasicAuth($key, $secret)
                ->timeout(30)
                ->post($this->apiUrl, ['Messages' => [$message]]);
            if (! $resp->successful()) {
                return ['success' => false, 'error' => 'Mailjet HTTP '.$resp->status().': '.$resp->body()];
            }
            $data = $resp->json();

            // Mailjet v3.1: HTTP 200 dönse bile per-mesaj Status "error" olabilir
            // (invalid sender, blocked recipient vb.). Başarıyı gövde-statüsüyle gate et.
            $msgStatus = $data['Messages'][0]['Status'] ?? null;
            if ($msgStatus !== null && strtolower((string) $msgStatus) !== 'success') {
                $errs = $data['Messages'][0]['Errors'] ?? [];
                $errMsg = ! empty($errs)
                    ? implode('; ', array_map(fn ($e) => $e['ErrorMessage'] ?? (is_string($e) ? $e : json_encode($e)), $errs))
                    : 'Mailjet message status: '.$msgStatus;

                return ['success' => false, 'error' => $errMsg];
            }

            // message_id yoksa UYDURMA — null bırak.
            $msgId = $data['Messages'][0]['To'][0]['MessageID'] ?? null;

            return ['success' => true, 'message_id' => $msgId !== null ? (string) $msgId : null, 'message' => 'Sent'];
        } catch (\Throwable $e) {
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public function renderTemplate(array $params)
    {
        return ['success' => true, 'rendered' => $params['content'] ?? ''];
    }

    public function testConnection(array $params)
    {
        $key = $params['api_key'] ?? $this->getConfig('api_key');
        $secret = $params['api_secret'] ?? $this->getConfig('api_secret');
        if (! $key || ! $secret) {
            return ['success' => false, 'message' => 'api_key/api_secret required'];
        }
        $resp = Http::withBasicAuth($key, $secret)->timeout(15)->get('https://api.mailjet.com/v3/REST/sender');

        return $resp->successful()
            ? ['success' => true, 'message' => 'Mailjet connection OK']
            : ['success' => false, 'message' => 'Mailjet HTTP '.$resp->status()];
    }

    /**
     * Email pipeline config'i YALNIZ getConfigFields()'ten okur (EmailManager →
     * ModuleConfig::resolved → yalnız declared key'ler resolve edilir). Mailjet
     * İKİ anahtar gerektirir: api_key (public) + api_secret (private) — ikisi de
     * zorunlu. Base default api_secret'i required=false yapar; burada override
     * ederek zorunlu kılıyoruz. (adminFields() Email ailesinde ölü koddu, kaldırıldı.)
     */
    public function getConfigFields(): array
    {
        return [
            'api_key' => [
                'type' => 'text',
                'label' => 'Mailjet API Key',
                'required' => true,
                'encrypted' => true,
                'description' => 'Mailjet public key',
            ],
            'api_secret' => [
                'type' => 'password',
                'label' => 'Mailjet API Secret',
                'required' => true,
                'encrypted' => true,
                'description' => 'Mailjet private key',
            ],
            'from_email' => [
                'type' => 'email',
                'label' => __('modules.email_config_from_email'),
                'required' => true,
                'description' => __('modules.email_config_from_email_desc'),
            ],
            'from_name' => [
                'type' => 'text',
                'label' => __('modules.email_config_from_name'),
                'required' => true,
                'description' => __('modules.email_config_from_name_desc'),
            ],
            'test_mode' => [
                'type' => 'boolean',
                'label' => __('modules.email_config_test_mode'),
                'required' => false,
                'default' => true,
                'description' => 'Test modunda çalıştır',
            ],
        ];
    }

    protected function getRequiredConfigFields(): array
    {
        return ['api_key', 'api_secret', 'from_email', 'from_name'];
    }

    private function normaliseRecipients($r): array
    {
        if (is_string($r)) {
            return [['Email' => $r]];
        }
        if (is_array($r) && isset($r[0]) && is_string($r[0])) {
            return array_map(fn ($e) => ['Email' => $e], $r);
        }

        return is_array($r) ? $r : [];
    }
}
