<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Database;
use App\Core\Logger;

class SupportTicketAlertEmailService
{
    private NotificationChannelService $notifier;

    public function __construct(?NotificationChannelService $notifier = null)
    {
        $this->notifier = $notifier ?? new NotificationChannelService();
    }

    public function notifySuperadminsNewTicket(array $payload): array
    {
        if (!$this->notifier->isChannelEnabled('email')) {
            return [
                'ok' => false,
                'error' => 'Canal email desactivado.',
                'sent' => 0,
                'failed' => 0,
            ];
        }

        $recipients = $this->superadminRecipients();
        if ($recipients === []) {
            return [
                'ok' => false,
                'error' => 'No hay superadministradores con correo válido.',
                'sent' => 0,
                'failed' => 0,
            ];
        }

        $ticketId = max(0, (int) ($payload['ticket_id'] ?? 0));
        $companyName = trim((string) ($payload['empresa_nombre'] ?? 'Empresa'));
        $subjectText = trim((string) ($payload['asunto'] ?? 'Ticket de soporte'));
        $priority = strtolower(trim((string) ($payload['prioridad'] ?? 'media')));
        $createdBy = trim((string) ($payload['creado_por'] ?? 'Usuario empresa'));
        $createdAt = trim((string) ($payload['created_at'] ?? date('Y-m-d H:i:s')));
        $panelUrl = trim((string) ($payload['panel_url'] ?? url('superadmin') . '?seccion=soporte'));

        $priorityLabel = match ($priority) {
            'critica' => 'Crítica',
            'alta' => 'Alta',
            'baja' => 'Baja',
            default => 'Media',
        };

        $subject = 'Nuevo ticket de soporte';
        if ($ticketId > 0) {
            $subject .= ' #' . $ticketId;
        }
        $subject .= ' · ' . $companyName;

        $textMessage = $this->buildTextMessage(
            $ticketId,
            $companyName,
            $subjectText,
            $priorityLabel,
            $createdBy,
            $createdAt,
            $panelUrl
        );
        $htmlMessage = $this->buildHtmlMessage(
            $ticketId,
            $companyName,
            $subjectText,
            $priorityLabel,
            $createdBy,
            $createdAt,
            $panelUrl
        );

        $sent = 0;
        $failed = 0;
        foreach ($recipients as $recipient) {
            $email = strtolower(trim((string) ($recipient['email'] ?? '')));
            if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                continue;
            }

            $result = $this->notifier->sendEmail($email, $subject, $textMessage, $htmlMessage);
            if ((bool) ($result['ok'] ?? false)) {
                $sent++;
                continue;
            }

            $failed++;
            Logger::info('No fue posible enviar alerta de ticket a superadmin', [
                'ticket_id' => $ticketId,
                'email' => $email,
                'error' => (string) ($result['error'] ?? 'Error desconocido'),
            ]);
        }

        return [
            'ok' => $sent > 0,
            'error' => $sent > 0 ? null : 'No fue posible enviar correo a superadmin.',
            'sent' => $sent,
            'failed' => $failed,
        ];
    }

    private function superadminRecipients(): array
    {
        try {
            $stmt = Database::connection()->prepare(
                'SELECT u.nombre, u.email
                 FROM usuarios u
                 INNER JOIN roles r ON r.id = u.rol_id
                 WHERE u.activo = 1
                   AND u.empresa_id IS NULL
                   AND r.slug = "superadmin"
                 ORDER BY u.id ASC'
            );
            $stmt->execute();
            $rows = $stmt->fetchAll() ?: [];

            $unique = [];
            foreach ($rows as $row) {
                $email = strtolower(trim((string) ($row['email'] ?? '')));
                if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                    continue;
                }
                $unique[$email] = [
                    'nombre' => trim((string) ($row['nombre'] ?? 'Superadmin')),
                    'email' => $email,
                ];
            }

            return array_values($unique);
        } catch (\Throwable) {
            return [];
        }
    }

    private function buildTextMessage(
        int $ticketId,
        string $companyName,
        string $subjectText,
        string $priorityLabel,
        string $createdBy,
        string $createdAt,
        string $panelUrl
    ): string {
        $ticketRef = $ticketId > 0 ? ('#' . $ticketId) : 'N/D';

        return trim(
            'Nuevo ticket de soporte en Veltrix POS' . "\n\n"
            . 'Ticket: ' . $ticketRef . "\n"
            . 'Empresa: ' . $companyName . "\n"
            . 'Asunto: ' . $subjectText . "\n"
            . 'Prioridad: ' . $priorityLabel . "\n"
            . 'Creado por: ' . $createdBy . "\n"
            . 'Fecha: ' . $createdAt . "\n\n"
            . 'Revisar en: ' . $panelUrl
        );
    }

    private function buildHtmlMessage(
        int $ticketId,
        string $companyName,
        string $subjectText,
        string $priorityLabel,
        string $createdBy,
        string $createdAt,
        string $panelUrl
    ): string {
        $safeTicket = htmlspecialchars($ticketId > 0 ? ('#' . $ticketId) : 'N/D', ENT_QUOTES, 'UTF-8');
        $safeCompany = htmlspecialchars($companyName, ENT_QUOTES, 'UTF-8');
        $safeSubject = htmlspecialchars($subjectText, ENT_QUOTES, 'UTF-8');
        $safePriority = htmlspecialchars($priorityLabel, ENT_QUOTES, 'UTF-8');
        $safeCreatedBy = htmlspecialchars($createdBy, ENT_QUOTES, 'UTF-8');
        $safeCreatedAt = htmlspecialchars($createdAt, ENT_QUOTES, 'UTF-8');
        $safePanelUrl = htmlspecialchars($panelUrl, ENT_QUOTES, 'UTF-8');
        $safeYear = htmlspecialchars(date('Y'), ENT_QUOTES, 'UTF-8');

        return '<!doctype html>'
            . '<html lang="es"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">'
            . '<title>Nuevo ticket de soporte</title></head>'
            . '<body style="margin:0;padding:0;background:#f4f7fc;font-family:Arial,Helvetica,sans-serif;color:#1f2a3d;">'
            . '<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#f4f7fc;padding:20px 10px;">'
            . '<tr><td align="center">'
            . '<table role="presentation" width="620" cellspacing="0" cellpadding="0" style="max-width:620px;width:100%;background:#ffffff;border-radius:16px;border:1px solid #dbe6f5;overflow:hidden;">'
            . '<tr><td style="padding:22px 24px;background:linear-gradient(135deg,#102a4f 0%,#0f6a95 100%);">'
            . '<div style="font-size:13px;letter-spacing:.08em;text-transform:uppercase;color:#ffffff;font-weight:700;">Veltrix POS</div>'
            . '<h1 style="margin:10px 0 0;font-size:26px;line-height:1.2;color:#ffffff;font-weight:800;">Nuevo ticket recibido</h1>'
            . '</td></tr>'
            . '<tr><td style="padding:20px 24px 10px;">'
            . '<table role="presentation" width="100%" cellspacing="0" cellpadding="0">'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Ticket</td><td align="right" style="padding:0 0 10px;font-size:16px;font-weight:700;color:#1f3354;">' . $safeTicket . '</td></tr>'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Empresa</td><td align="right" style="padding:0 0 10px;font-size:16px;font-weight:700;color:#1f3354;">' . $safeCompany . '</td></tr>'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Asunto</td><td align="right" style="padding:0 0 10px;font-size:14px;font-weight:600;color:#1f3354;">' . $safeSubject . '</td></tr>'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Prioridad</td><td align="right" style="padding:0 0 10px;font-size:14px;font-weight:700;color:#0f6a95;">' . $safePriority . '</td></tr>'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Creado por</td><td align="right" style="padding:0 0 10px;font-size:14px;font-weight:600;color:#1f3354;">' . $safeCreatedBy . '</td></tr>'
            . '<tr><td style="padding:0 0 10px;font-size:14px;color:#6d7f9a;">Fecha</td><td align="right" style="padding:0 0 10px;font-size:14px;font-weight:600;color:#1f3354;">' . $safeCreatedAt . '</td></tr>'
            . '</table>'
            . '</td></tr>'
            . '<tr><td style="padding:8px 24px 24px;">'
            . '<a href="' . $safePanelUrl . '" style="display:inline-block;padding:12px 20px;border-radius:999px;background:linear-gradient(135deg,#1bb6d7 0%,#0a7ea6 100%);color:#ffffff;text-decoration:none;font-weight:700;font-size:14px;">Abrir tickets en superadmin</a>'
            . '</td></tr>'
            . '<tr><td style="padding:12px 24px;background:#f7faff;border-top:1px solid #e2ebf8;font-size:12px;color:#7b8da8;">Veltrix POS · ' . $safeYear . ' · Alerta automática de soporte.</td></tr>'
            . '</table>'
            . '</td></tr></table>'
            . '</body></html>';
    }
}

