<?php

declare(strict_types=1);

namespace App\Services;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception as MailException;

class MailService
{
    private ?PHPMailer $mailer = null;
    private array $config;

    public function __construct()
    {
        $this->config = require BASE_PATH . '/config/mail.php';

        try {
            $configModel = new \App\Models\Configuration();
            $dbConfigs = $configModel->getAll();
            $prefixMap = [
                'smtp_host' => 'host',
                'smtp_port' => 'port',
                'smtp_user' => 'user',
                'smtp_pass' => 'pass',
                'smtp_encryption' => 'encryption',
            ];
            foreach ($dbConfigs as $cfg) {
                if (isset($prefixMap[$cfg['key']]) && !empty($cfg['value'])) {
                    $this->config[$prefixMap[$cfg['key']]] = $cfg['value'];
                }
            }
        } catch (\Exception $e) {
            error_log('MailService: error loading DB config, using env defaults — ' . $e->getMessage());
        }
    }

    public function sendUserInvitation(string $email, string $token, string $role, string $password = 'Bienvenido123!'): void
    {
        $appConfig = require BASE_PATH . '/config/app.php';
        $roleLabel = $role === 'super_admin' ? 'Super Administrador' : 'Gestor Comercial';
        $acceptUrl = $appConfig['app']['url'] . '/activate?token=' . $token;

        $subject = 'Invitación a ItalvetCRM';
        $body = "
            <h2>¡Bienvenido a ItalvetCRM!</h2>
            <p>Ha sido invitado como <strong>{$roleLabel}</strong>.</p>
            <p>Para activar su cuenta, haga clic en el siguiente enlace:</p>
            <p><a href=\"{$acceptUrl}\">Activar Cuenta</a></p>
            <p>Su contraseña temporal es: <strong>{$password}</strong></p>
            <p>Al iniciar sesión por primera vez, deberá cambiar su contraseña.</p>
            <p>Este enlace expira en 24 horas.</p>
        ";

        $this->send($email, $subject, $body);
    }

    public function sendPasswordReset(string $email, string $token): void
    {
        $appConfig = require BASE_PATH . '/config/app.php';
        $resetUrl = $appConfig['app']['url'] . '/reset-password?token=' . $token;

        $this->send($email, 'Recuperación de contraseña - ItalvetCRM', "
            <h2>Recuperación de Contraseña</h2>
            <p>Ha solicitado restablecer su contraseña.</p>
            <p><a href=\"{$resetUrl}\">Restablecer Contraseña</a></p>
            <p>Este enlace expira en 1 hora.</p>
        ");
    }

    public function sendTaskReminder(string $email, string $taskType, string $leadName, string $scheduledDate, string $scheduledTime): void
    {
        $timeStr = $scheduledTime ? " a las {$scheduledTime}" : '';

        try {
            $this->send($email, 'Recordatorio de tarea - ItalvetCRM', "
                <h2>Recordatorio de Tarea</h2>
                <p>Tiene una tarea programada de tipo <strong>{$taskType}</strong>.</p>
                <p>Lead: <strong>{$leadName}</strong></p>
                <p>Fecha: <strong>{$scheduledDate}{$timeStr}</strong></p>
                <p>Ingrese al sistema para más detalles.</p>
            ");
        } catch (\RuntimeException $e) {
            error_log('Error en recordatorio de tarea: ' . $e->getMessage());
        }
    }

    private function send(string $to, string $subject, string $body): void
    {
        if (empty($this->config['host']) || empty($this->config['user'])) {
            throw new \RuntimeException('SMTP no configurado');
        }

        try {
            $mail = new PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = $this->config['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $this->config['user'];
            $mail->Password = $this->config['pass'];
            $mail->SMTPSecure = $this->config['encryption'] === 'ssl'
                ? PHPMailer::ENCRYPTION_SMTPS
                : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = (int) $this->config['port'];
            $mail->CharSet = 'UTF-8';

            $mail->setFrom(
                $this->config['from_address'] ?? $this->config['user'],
                $this->config['from_name'] ?? 'ItalvetCRM'
            );
            $mail->addAddress($to);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $body;

            $mail->send();
        } catch (MailException $e) {
            throw new \RuntimeException('Error al enviar correo: ' . $mail->ErrorInfo);
        }
    }

    public function isConfigured(): bool
    {
        return !empty($this->config['host']) && !empty($this->config['user']);
    }
}
