<?php

namespace App\Services;

use App\Controllers\View\EmailController;

class EmailService
{
    protected array $senders;
    protected EmailController $mailer;
    protected int $lastCcBatchCount = 0;

    public function __construct()
    {
        $json = env('MAIL_SENDERS', '{}');
        $decoded = json_decode($json, true);
        $this->senders = is_array($decoded) ? $decoded : [];
        $this->mailer  = new EmailController();
    }

    protected function getSenderDetails(string $fromKey = 'general'): array
    {
        $senders = $this->senders;
        if (isset($senders[$fromKey])) {
            return $senders[$fromKey];
        }
        return $senders['general'] ?? [
            'email' => getenv('SMTP_USER') ?: 'no-reply@alrahmaisgl.org',
            'name'  => 'Al Rahma Sunday School',
        ];
    }

    /** NEW: expose configured sender keys to build a dropdown in the UI */
    public function listSenders(): array
    {
        // returns: ['general' => ['email' => '...', 'name' => '...'], 'finance' => [...], ...]
        return $this->senders ?: [
            'general' => [
                'email' => getenv('SMTP_USER') ?: 'no-reply@alrahmaisgl.org',
                'name'  => 'Al Rahma Sunday School',
            ],
        ];
    }

    /**
     * Send a single HTML email.
     * Backward-compatible: you can ignore $attachments/$headers.
     */
    public function send(string $to, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
    {
        $attachmentsPayload = $this->normalizeAttachments($attachments);
        // Headers are ignored by EmailController but kept for interface compatibility.
        return $this->mailer->sendEmail($to, $subject, $message, $fromKey, null, null, $attachmentsPayload);
    }

    /**
     * NEW: BCC bulk send in a single SMTP call (To must be non-empty; we use the SMTP user).
     */
    public function sendBcc(array $bccList, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
    {
        if (empty($bccList)) {
            return true; // nothing to send
        }

        $attachmentsPayload = $this->normalizeAttachments($attachments);
        $allOk = true;
        foreach ($bccList as $addr) {
            $ok = $this->mailer->sendEmail($addr, $subject, $message, $fromKey, null, null, $attachmentsPayload);
            if (!$ok) {
                $allOk = false;
                log_message('error', 'EmailService::sendBcc failed for ' . $addr);
            }
        }
        return $allOk;
    }

    /**
     * Send one email with all recipients in CC.
     */
    public function sendCc(array $ccList, string $subject, string $message, string $fromKey = 'general', array $attachments = [], array $headers = []): bool
    {
        $this->lastCcBatchCount = 0;

        if (empty($ccList)) {
            return true;
        }

        $sender = $this->getSenderDetails($fromKey);
        $to = trim((string) ($sender['email'] ?? ''));
        if ($to === '' || !filter_var($to, FILTER_VALIDATE_EMAIL)) {
            $fallback = trim((string) (getenv('SMTP_USER') ?: ''));
            $to = filter_var($fallback, FILTER_VALIDATE_EMAIL) ? $fallback : 'no-reply@alrahmaisgl.org';
        }

        $attachmentsPayload = $this->normalizeAttachments($attachments);
        $chunks = array_chunk(array_values($ccList), 10);
        $this->lastCcBatchCount = count($chunks);
        $allOk = true;

        foreach ($chunks as $index => $chunk) {
            $ok = $this->mailer->sendEmailWithCc($to, $chunk, $subject, $message, $fromKey, null, null, $attachmentsPayload);
            if (!$ok) {
                $allOk = false;
                log_message('error', 'EmailService::sendCc failed for batch ' . ($index + 1) . ' of ' . count($chunks));
            }
        }

        return $allOk;
    }

    public function getLastCcBatchCount(): int
    {
        return $this->lastCcBatchCount;
    }

    /**
     * Normalize various attachment inputs to the format expected by EmailController.
     */
    private function normalizeAttachments(array $attachments): array
    {
        $out = [];
        foreach ($attachments as $file) {
            if (is_object($file) && method_exists($file, 'isValid') && $file->isValid()) {
                $newName = $file->getRandomName();
                $path = WRITEPATH . 'uploads/' . $newName;
                $file->move(WRITEPATH . 'uploads', $newName, true);
                $out[] = ['path' => $path, 'name' => $file->getClientName()];
            } elseif (is_string($file) && is_file($file)) {
                $out[] = ['path' => $file, 'name' => basename($file)];
            } elseif (is_array($file) && !empty($file['path'])) {
                $out[] = ['path' => $file['path'], 'name' => $file['name'] ?? basename($file['path'])];
            }
        }
        return $out;
    }
}
