<?php

namespace App\Services\Install;

use CodeIgniter\Email\Email;

/**
 * Step 6. Sends a one-off test email using transient config (not yet saved
 * anywhere) so the admin can confirm SMTP settings work before committing
 * them to .env in Step 8.
 */
class SmtpTester
{
    public function sendTest(array $smtp, string $toEmail): array
    {
        $email = \Config\Services::email();

        $email->initialize([
            'protocol'   => 'smtp',
            'SMTPHost'   => $smtp['host'],
            'SMTPUser'   => $smtp['username'],
            'SMTPPass'   => $smtp['password'],
            'SMTPPort'   => (int) $smtp['port'],
            'SMTPCrypto' => $smtp['encryption'] ?? 'tls',
            'mailType'   => 'html',
        ]);

        $email->setFrom($smtp['from_email'], $smtp['from_name'] ?? 'Job Portal');
        $email->setTo($toEmail);
        $email->setSubject('Job Portal — SMTP Test');
        $email->setMessage('<p>This is a test email from the Job Portal installation wizard. If you received this, your SMTP configuration is working correctly.</p>');

        $sent = $email->send();

        return [
            'success' => $sent,
            'message' => $sent ? 'Test email sent successfully.' : ('Failed to send: ' . $email->printDebugger(['headers'])),
        ];
    }
}
