<?php

namespace App\Services;

use Config\Services;

class EmailService
{
    public function send(string $subject, string $body, $recipient): bool
    {

        $skEnv = env('sk_environment', 'production'); // fallback a producción si no está definido

        // Si no estamos en producción, forzar el destinatario a uno fijo
        if ($skEnv !== 'production') {
            $recipient = 'imnavajas@coit.es'; // <-- Cambia por el correo de pruebas
        }

        $settings_model = model('App\Models\Configuracion\ConfigVariableModel');
        $gateway = $settings_model->getVariable('email_protocol')->value;
        $body = html_entity_decode($body);

        if ($gateway === 'smtp') {
            try {
                $email = Services::email();

                $emailConfig = [
                    'protocol' => $gateway,
                    'SMTPHost' => $settings_model->getVariable('email_host')->value,
                    'SMTPUser' => $settings_model->getVariable('email_from_address')->value,
                    'SMTPPass' => $settings_model->getVariable('email_pass')->value,
                    'SMTPPort' => (int) $settings_model->getVariable('email_port')->value,
                    'SMTPCrypto' => $settings_model->getVariable('email_cert')->value === 'none' ? '' : $settings_model->getVariable('email_cert')->value,
                    'SMTPTimeout' => 15,
                    'mailType' => 'html',
                    'wordWrap' => true,
                ];

                $email->initialize($emailConfig);

                $email->setFrom($settings_model->getVariable('email_from_address')->value, $settings_model->getVariable('email_from_name')->value);
                $email->setTo($recipient);
                $email->setSubject($subject);
                $email->setMessage($body);

                return $email->send();
            } catch (\Throwable $e) {
                log_message('error', 'EmailService failed: ' . $e->getMessage());
                return false;
            }
        }

        return false;
    }
}
