<?php

namespace App\Libraries\NotificationChannels;

use Config\Database;

class EmailChannel implements NotificationChannelInterface
{
    public function send(string $recipient, ?string $subject, string $body): bool
    {
        $config = $this->resolveSmtpConfig();
        $email = \Config\Services::email();

        // Only override CI4's default (.env-sourced) config when the
        // Super Admin has actually saved SMTP settings via the admin
        // panel — otherwise this is a no-op and .env values apply as usual.
        if ($config !== null) {
            $email->initialize([
                'protocol'   => 'smtp',
                'SMTPHost'   => $config['host'],
                'SMTPUser'   => $config['username'],
                'SMTPPass'   => $config['password'],
                'SMTPPort'   => (int) $config['port'],
                'SMTPCrypto' => $config['encryption'] ?: 'tls',
                'mailType'   => 'html',
            ]);
            $email->setFrom($config['from_email'] ?: 'noreply@example.com', $config['from_name'] ?: 'Job Portal');
        }

        $email->setTo($recipient);
        $email->setSubject($subject ?? 'Notification');
        $email->setMessage($body);

        return $email->send();
    }

    /**
     * Reads the 'smtp' settings group from the database, populated via
     * Admin → Settings. Returns null if not yet configured there, so
     * callers fall back to whatever CI4's normal .env-driven email config
     * already provides (e.g. what the installer wrote in Step 6).
     */
    private function resolveSmtpConfig(): ?array
    {
        $rows = Database::connect()->table('settings')->where('group', 'smtp')->get()->getResultArray();
        if (empty($rows)) {
            return null;
        }

        $config = [];
        foreach ($rows as $row) {
            $config[$row['key']] = $row['value'];
        }

        // Require at minimum a host — a partially-saved group shouldn't
        // silently override a working .env configuration with blanks.
        if (empty($config['host'])) {
            return null;
        }

        return $config;
    }
}
