<?php

namespace App\Services;

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

/**
 * Servicio de Email
 * Envío de notificaciones y emails del sistema
 */
class EmailService
{
    private Logger $logger;
    private PHPMailer $mailer;

    private string $emailLogFile;

    public function __construct()
    {
        $this->logger = new Logger();
        $this->mailer = new PHPMailer(true);

        // Archivo de log específico para emails
        $this->emailLogFile = storage_path('logs/email.log');
        $logDir = dirname($this->emailLogFile);
        if (!is_dir($logDir)) {
            mkdir($logDir, 0755, true);
        }

        $this->logEmail('INFO', 'EmailService initialized', [
            'enabled' => $this->isEnabled(),
            'host' => $_ENV['MAIL_HOST'] ?? 'not set',
            'port' => $_ENV['MAIL_PORT'] ?? 'not set',
            'user' => $_ENV['MAIL_USER'] ?? 'not set'
        ]);

        if ($this->isEnabled()) {
            $this->configure();
        }
    }

    /**
     * Verificar si el email está habilitado
     */
    public function isEnabled(): bool
    {
        return filter_var($_ENV['MAIL_ENABLED'] ?? false, FILTER_VALIDATE_BOOLEAN);
    }

    /**
     * Configurar PHPMailer
     */
    private function configure(): void
    {
        try {
            // Configuración del servidor
            $this->mailer->isSMTP();
            $this->mailer->Host = $_ENV['MAIL_HOST'];
            $this->mailer->SMTPAuth = true;
            $this->mailer->Username = $_ENV['MAIL_USER'];
            $this->mailer->Password = $_ENV['MAIL_PASS'];

            // Configurar encriptación según .env (ssl, tls, starttls)
            $encryption = strtolower($_ENV['MAIL_ENCRYPTION'] ?? 'tls');
            if ($encryption === 'ssl') {
                $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            } elseif ($encryption === 'starttls') {
                $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } else {
                $this->mailer->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS; // default
            }

            $this->mailer->Port = (int) $_ENV['MAIL_PORT'];

            // Debug mode
            $this->mailer->SMTPDebug = 2; // Verbose debug
            $this->mailer->Debugoutput = function($str, $level) {
                $this->logEmail('DEBUG', "PHPMailer: $str", ['level' => $level]);
            };

            // Configuración del remitente
            $this->mailer->setFrom($_ENV['MAIL_FROM'], $_ENV['MAIL_FROM_NAME']);

            // Configuración general
            $this->mailer->CharSet = 'UTF-8';
            $this->mailer->isHTML(true);

            $this->logEmail('INFO', 'SMTP configured successfully', [
                'host' => $_ENV['MAIL_HOST'],
                'port' => $_ENV['MAIL_PORT'],
                'encryption' => $encryption
            ]);

        } catch (Exception $e) {
            $this->logEmail('ERROR', 'Email configuration error: ' . $e->getMessage());
            $this->logger->error('Email configuration error: ' . $e->getMessage());
        }
    }

    /**
     * Enviar link de firma al cliente
     */
    public function sendSignatureLink(array $contract): bool
    {
        $contractService = new ContractService();
        $link = $contractService->getSignatureLink($contract['token']);

        $subject = "Contrato digital para firma: {$contract['titulo']}";

        $body = $this->renderTemplate('signature_link', [
            'cliente_nombre' => $contract['cliente_nombre'],
            'titulo' => $contract['titulo'],
            'link' => $link,
            'expira_at' => date('d/m/Y H:i', strtotime($contract['expira_at']))
        ]);

        return $this->send($contract['cliente_email'], $subject, $body);
    }

    /**
     * Enviar confirmación de firma
     */
    public function sendSignatureConfirmation(array $contract, array $signature, ?string $pdfPath = null): bool
    {
        $subject = "Confirmación de firma: {$contract['titulo']}";

        $body = $this->renderTemplate('signature_confirmation', [
            'cliente_nombre' => $contract['cliente_nombre'] ?? 'Cliente',
            'titulo' => $contract['titulo'] ?? 'Contrato',
            'firmado_at' => isset($signature['firmado_at'])
                ? date('d/m/Y H:i', strtotime($signature['firmado_at']))
                : date('d/m/Y H:i'),
            'numero_documento' => $signature['numero_documento'] ?? $signature['tipo_documento'] ?? 'N/A',
            'has_pdf' => !empty($pdfPath) && file_exists($pdfPath)
        ]);

        // Adjuntar PDF si existe
        $attachments = [];
        if (!empty($pdfPath) && file_exists($pdfPath)) {
            $attachments[] = [
                'path' => $pdfPath,
                'name' => "Contrato_Firmado_{$contract['id']}.pdf"
            ];
        }

        return $this->send($contract['cliente_email'], $subject, $body, $attachments);
    }

    /**
     * Enviar notificación al admin
     */
    public function notifyAdmin(string $adminEmail, string $subject, string $message): bool
    {
        $body = $this->renderTemplate('admin_notification', [
            'subject' => $subject,
            'message' => $message
        ]);

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

    /**
     * Enviar email genérico
     *
     * @param string $to Email del destinatario
     * @param string $subject Asunto del email
     * @param string $body Cuerpo del email (HTML)
     * @param array $attachments Adjuntos opcionales [['path' => 'ruta', 'name' => 'nombre']]
     */
    public function send(string $to, string $subject, string $body, array $attachments = []): bool
    {
        // Si el email no está habilitado, simular éxito
        if (!$this->isEnabled()) {
            $this->logEmail('WARNING', "Email disabled, skipping send", [
                'to' => $to,
                'subject' => $subject,
                'attachments_count' => count($attachments)
            ]);
            $this->logger->info("Email disabled, skipping send to: {$to} - Subject: {$subject}");
            return true;
        }

        $this->logEmail('INFO', 'Attempting to send email', [
            'to' => $to,
            'subject' => $subject,
            'body_length' => strlen($body),
            'attachments_count' => count($attachments)
        ]);

        try {
            $this->mailer->clearAddresses();
            $this->mailer->clearAttachments();

            $this->mailer->addAddress($to);
            $this->mailer->Subject = $subject;
            $this->mailer->Body = $body;
            $this->mailer->AltBody = strip_tags($body);

            // Adjuntar archivos si existen
            foreach ($attachments as $attachment) {
                if (isset($attachment['path']) && file_exists($attachment['path'])) {
                    $fileName = $attachment['name'] ?? basename($attachment['path']);
                    $this->mailer->addAttachment($attachment['path'], $fileName);

                    $this->logEmail('DEBUG', 'Attachment added', [
                        'path' => $attachment['path'],
                        'name' => $fileName
                    ]);
                }
            }

            $this->logEmail('DEBUG', 'Calling PHPMailer send()');

            $result = $this->mailer->send();

            $this->logEmail('SUCCESS', 'Email sent successfully', [
                'to' => $to,
                'subject' => $subject,
                'result' => $result,
                'attachments_sent' => count($attachments)
            ]);

            $this->logger->info("Email sent to: {$to} - Subject: {$subject} - Attachments: " . count($attachments));

            return true;
        } catch (Exception $e) {
            $this->logEmail('ERROR', 'Email send failed: ' . $e->getMessage(), [
                'to' => $to,
                'subject' => $subject,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);

            $this->logger->error("Email error: {$e->getMessage()} - To: {$to}");
            return false;
        }
    }

    /**
     * Renderizar plantilla de email
     */
    private function renderTemplate(string $template, array $data): string
    {
        $templates = [
            'signature_link' => $this->getSignatureLinkTemplate($data),
            'signature_confirmation' => $this->getSignatureConfirmationTemplate($data),
            'admin_notification' => $this->getAdminNotificationTemplate($data)
        ];

        return $templates[$template] ?? '';
    }

    /**
     * Plantilla: Link de firma
     */
    private function getSignatureLinkTemplate(array $data): string
    {
        // Valores por defecto
        $clienteNombre = $data['cliente_nombre'] ?? 'Cliente';
        $titulo = $data['titulo'] ?? 'Contrato';
        $link = $data['link'] ?? '#';
        $expiraAt = $data['expira_at'] ?? date('d/m/Y H:i', strtotime('+24 hours'));

        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #4F46E5; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
        .content { background: #f9fafb; padding: 30px; border: 1px solid #e5e7eb; }
        .button { display: inline-block; background: #4F46E5; color: white; padding: 12px 30px; text-decoration: none; border-radius: 6px; margin: 20px 0; }
        .footer { background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 8px 8px; }
        .warning { background: #fef3c7; border-left: 4px solid #f59e0b; padding: 12px; margin: 15px 0; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>Contrato Digital</h1>
        </div>
        <div class="content">
            <p>Hola <strong>{$clienteNombre}</strong>,</p>

            <p>Has recibido un contrato digital para tu revisión y firma:</p>

            <h3>{$titulo}</h3>

            <p>Para leer y firmar el contrato, haz clic en el siguiente botón:</p>

            <center>
                <a href="{$link}" class="button">Firmar Contrato</a>
            </center>

            <div class="warning">
                <strong>⏰ Importante:</strong> Este link expira el <strong>{$expiraAt}</strong>
            </div>

            <p><strong>¿Qué necesitarás?</strong></p>
            <ul>
                <li>Tu documento de identidad (cédula, pasaporte, etc.)</li>
                <li>Un dispositivo con cámara (celular o computadora)</li>
                <li>Buena iluminación para las fotos</li>
            </ul>

            <p>Si tienes alguna pregunta, no dudes en contactarnos.</p>
        </div>
        <div class="footer">
            <p>Este es un correo automático, por favor no responder.</p>
            <p>&copy; 2026 Sistema de Contratos Digitales</p>
        </div>
    </div>
</body>
</html>
HTML;
    }

    /**
     * Plantilla: Confirmación de firma
     */
    private function getSignatureConfirmationTemplate(array $data): string
    {
        // Valores por defecto
        $titulo = $data['titulo'] ?? 'Contrato';
        $clienteNombre = $data['cliente_nombre'] ?? 'Cliente';
        $firmadoAt = $data['firmado_at'] ?? date('d/m/Y H:i');
        $numeroDocumento = $data['numero_documento'] ?? 'N/A';
        $hasPdf = $data['has_pdf'] ?? false;

        $pdfMessage = $hasPdf
            ? '<p>📎 <strong>Encontrarás adjunto el PDF del contrato firmado</strong> para tu archivo personal.</p>'
            : '<p>Una copia del contrato firmado ha sido archivada de forma segura. Si necesitas una copia, contacta al administrador.</p>';

        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #10b981; color: white; padding: 20px; text-align: center; border-radius: 8px 8px 0 0; }
        .content { background: #f9fafb; padding: 30px; border: 1px solid #e5e7eb; }
        .success { background: #d1fae5; border-left: 4px solid #10b981; padding: 12px; margin: 15px 0; }
        .info-box { background: white; border: 1px solid #e5e7eb; padding: 15px; border-radius: 6px; margin: 15px 0; }
        .attachment { background: #dbeafe; border-left: 4px solid #3b82f6; padding: 12px; margin: 15px 0; }
        .footer { background: #f3f4f6; padding: 15px; text-align: center; font-size: 12px; color: #6b7280; border-radius: 0 0 8px 8px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✓ Contrato Firmado</h1>
        </div>
        <div class="content">
            <p>Hola <strong>{$clienteNombre}</strong>,</p>

            <div class="success">
                <strong>¡Éxito!</strong> Tu contrato ha sido firmado correctamente.
            </div>

            <h3>Detalles de la firma:</h3>

            <div class="info-box">
                <p><strong>Contrato:</strong> {$titulo}</p>
                <p><strong>Fecha y hora:</strong> {$firmadoAt}</p>
                <p><strong>Documento:</strong> {$numeroDocumento}</p>
            </div>

            {$pdfMessage}

            <p>Gracias por utilizar nuestro sistema de contratos digitales.</p>
        </div>
        <div class="footer">
            <p>Este es un correo automático, por favor no responder.</p>
            <p>&copy; 2026 Sistema de Contratos Digitales</p>
        </div>
    </div>
</body>
</html>
HTML;
    }

    /**
     * Plantilla: Notificación al admin
     */
    private function getAdminNotificationTemplate(array $data): string
    {
        // Valores por defecto
        $subject = $data['subject'] ?? 'Notificación';
        $message = $data['message'] ?? '';

        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
        .container { max-width: 600px; margin: 0 auto; padding: 20px; }
        .header { background: #4F46E5; color: white; padding: 20px; border-radius: 8px 8px 0 0; }
        .content { background: #f9fafb; padding: 30px; border: 1px solid #e5e7eb; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>{$subject}</h2>
        </div>
        <div class="content">
            {$message}
        </div>
    </div>
</body>
</html>
HTML;
    }

    /**
     * Log específico para emails en archivo .txt
     */
    private function logEmail(string $level, string $message, array $context = []): void
    {
        $timestamp = gmdate('Y-m-d H:i:s');
        $contextStr = !empty($context) ? ' | ' . json_encode($context, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) : '';

        $logLine = "[{$timestamp}] [{$level}] {$message}{$contextStr}" . PHP_EOL;

        file_put_contents($this->emailLogFile, $logLine, FILE_APPEND | LOCK_EX);
    }
}
