<?php
/**
 * Service d'envoi d'emails
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Services;

use Core\Database;

class EmailService
{
    private $db;
    private $fromEmail;
    private $fromName;
    private $smtpEnabled;
    
    public function __construct()
    {
        $this->db = Database::getInstance();
        $this->fromEmail = defined('MAIL_FROM_EMAIL') ? MAIL_FROM_EMAIL : 'noreply@mysupport.ml';
        $this->fromName = defined('MAIL_FROM_NAME') ? MAIL_FROM_NAME : APP_NAME;
        $this->smtpEnabled = defined('SMTP_ENABLED') ? SMTP_ENABLED : false;
    }

    /**
     * Envoyer un email
     */
    public function send(string $to, string $subject, string $htmlBody, ?string $textBody = null): bool
    {
        if ($this->smtpEnabled && defined('SMTP_HOST')) {
            return $this->sendViaSMTP($to, $subject, $htmlBody, $textBody);
        }
        
        return $this->sendViaMail($to, $subject, $htmlBody, $textBody);
    }

    /**
     * Envoi via fonction mail() PHP
     */
    private function sendViaMail(string $to, string $subject, string $htmlBody, ?string $textBody): bool
    {
        $boundary = md5(time());
        
        $headers = [
            'From: ' . $this->fromName . ' <' . $this->fromEmail . '>',
            'Reply-To: ' . $this->fromEmail,
            'MIME-Version: 1.0',
            'Content-Type: multipart/alternative; boundary="' . $boundary . '"',
            'X-Mailer: mySupport'
        ];
        
        $body = "--{$boundary}\r\n";
        $body .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
        $body .= $textBody ?: strip_tags($htmlBody);
        $body .= "\r\n\r\n--{$boundary}\r\n";
        $body .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
        $body .= $htmlBody;
        $body .= "\r\n\r\n--{$boundary}--";
        
        return mail($to, $subject, $body, implode("\r\n", $headers));
    }

    /**
     * Envoi via SMTP
     */
    private function sendViaSMTP(string $to, string $subject, string $htmlBody, ?string $textBody): bool
    {
        // Configuration SMTP
        $host = SMTP_HOST;
        $port = defined('SMTP_PORT') ? SMTP_PORT : 587;
        $user = defined('SMTP_USER') ? SMTP_USER : '';
        $pass = defined('SMTP_PASS') ? SMTP_PASS : '';
        $secure = defined('SMTP_SECURE') ? SMTP_SECURE : 'tls';

        try {
            $socket = fsockopen(
                ($secure === 'ssl' ? 'ssl://' : '') . $host,
                $port,
                $errno,
                $errstr,
                30
            );
            
            if (!$socket) {
                error_log("SMTP Error: $errstr ($errno)");
                return $this->sendViaMail($to, $subject, $htmlBody, $textBody);
            }
            
            // Conversation SMTP simplifiée
            $this->smtpRead($socket);
            $this->smtpWrite($socket, "EHLO " . gethostname());
            $this->smtpRead($socket);
            
            if ($secure === 'tls') {
                $this->smtpWrite($socket, "STARTTLS");
                $this->smtpRead($socket);
                stream_socket_enable_crypto($socket, true, STREAM_CRYPTO_METHOD_TLS_CLIENT);
                $this->smtpWrite($socket, "EHLO " . gethostname());
                $this->smtpRead($socket);
            }
            
            if ($user) {
                $this->smtpWrite($socket, "AUTH LOGIN");
                $this->smtpRead($socket);
                $this->smtpWrite($socket, base64_encode($user));
                $this->smtpRead($socket);
                $this->smtpWrite($socket, base64_encode($pass));
                $this->smtpRead($socket);
            }
            
            $this->smtpWrite($socket, "MAIL FROM:<{$this->fromEmail}>");
            $this->smtpRead($socket);
            $this->smtpWrite($socket, "RCPT TO:<{$to}>");
            $this->smtpRead($socket);
            $this->smtpWrite($socket, "DATA");
            $this->smtpRead($socket);
            
            $boundary = md5(time());
            $message = "From: {$this->fromName} <{$this->fromEmail}>\r\n";
            $message .= "To: {$to}\r\n";
            $message .= "Subject: {$subject}\r\n";
            $message .= "MIME-Version: 1.0\r\n";
            $message .= "Content-Type: multipart/alternative; boundary=\"{$boundary}\"\r\n\r\n";
            $message .= "--{$boundary}\r\n";
            $message .= "Content-Type: text/plain; charset=UTF-8\r\n\r\n";
            $message .= ($textBody ?: strip_tags($htmlBody)) . "\r\n\r\n";
            $message .= "--{$boundary}\r\n";
            $message .= "Content-Type: text/html; charset=UTF-8\r\n\r\n";
            $message .= $htmlBody . "\r\n\r\n";
            $message .= "--{$boundary}--\r\n";
            $message .= ".";
            
            $this->smtpWrite($socket, $message);
            $this->smtpRead($socket);
            $this->smtpWrite($socket, "QUIT");
            fclose($socket);
            
            return true;
        } catch (\Exception $e) {
            error_log("SMTP Exception: " . $e->getMessage());
            return $this->sendViaMail($to, $subject, $htmlBody, $textBody);
        }
    }

    private function smtpWrite($socket, $data): void
    {
        fwrite($socket, $data . "\r\n");
    }

    private function smtpRead($socket): string
    {
        $response = '';
        while ($line = fgets($socket, 515)) {
            $response .= $line;
            if (substr($line, 3, 1) === ' ') break;
        }
        return $response;
    }

    // ==========================================
    // TEMPLATES D'EMAILS
    // ==========================================

    /**
     * Email de confirmation de ticket
     */
    public function sendTicketCreated(array $ticket, array $client, array $entreprise): bool
    {
        if (empty($client['email'])) return false;
        
        $subject = "[{$ticket['ticket_number']}] Votre demande a été enregistrée - {$entreprise['nom']}";
        
        $html = $this->getEmailTemplate('ticket_created', [
            'client_nom' => $client['nom'] ?? 'Client',
            'ticket_number' => $ticket['ticket_number'],
            'sujet' => $ticket['sujet'],
            'entreprise_nom' => $entreprise['nom'],
            'entreprise_email' => $entreprise['email'] ?? ''
        ]);
        
        $sent = $this->send($client['email'], $subject, $html);
        $this->logEmail($entreprise['id'], $client['email'], 'ticket_created', $ticket['id'], $sent);
        
        return $sent;
    }

    /**
     * Email de notification aux agents pour nouvelle escalade
     */
    public function sendEscalationAlert(array $escalation, array $agents, array $entreprise): int
    {
        $sentCount = 0;
        $subject = "🚨 Nouvelle demande d'assistance - {$entreprise['nom']}";
        
        foreach ($agents as $agent) {
            if (empty($agent['email'])) continue;
            
            $html = $this->getEmailTemplate('escalation_alert', [
                'agent_nom' => $agent['prenom'] ?? $agent['nom'],
                'client_nom' => $escalation['client_nom'] ?? 'Client',
                'type' => $escalation['type'] ?? 'live_chat',
                'reason' => $escalation['reason'] ?? '',
                'entreprise_nom' => $entreprise['nom'],
                'dashboard_url' => BASE_URL . '/agent'
            ]);
            
            if ($this->send($agent['email'], $subject, $html)) {
                $sentCount++;
            }
        }
        
        return $sentCount;
    }

    /**
     * Email de résolution de ticket
     */
    public function sendTicketResolved(array $ticket, array $client, array $entreprise): bool
    {
        if (empty($client['email'])) return false;
        
        $subject = "[{$ticket['ticket_number']}] Votre demande a été résolue - {$entreprise['nom']}";
        
        $csatToken = $this->generateCSATToken($ticket['conversation_id'] ?? $ticket['id']);
        
        $html = $this->getEmailTemplate('ticket_resolved', [
            'client_nom' => $client['nom'] ?? 'Client',
            'ticket_number' => $ticket['ticket_number'],
            'sujet' => $ticket['sujet'],
            'resolution_notes' => $ticket['resolution_notes'] ?? '',
            'entreprise_nom' => $entreprise['nom'],
            'csat_url' => BASE_URL . '/feedback/' . $csatToken
        ]);
        
        $sent = $this->send($client['email'], $subject, $html);
        $this->logEmail($entreprise['id'], $client['email'], 'ticket_resolved', $ticket['id'], $sent);
        
        return $sent;
    }

    /**
     * Email d'enquête satisfaction (CSAT)
     */
    public function sendCSATSurvey(int $conversationId, array $client, array $entreprise): bool
    {
        if (empty($client['email'])) return false;
        
        $csatToken = $this->generateCSATToken($conversationId);
        $subject = "Votre avis compte ! - {$entreprise['nom']}";
        
        $html = $this->getEmailTemplate('csat_survey', [
            'client_nom' => $client['nom'] ?? 'Client',
            'entreprise_nom' => $entreprise['nom'],
            'csat_url' => BASE_URL . '/feedback/' . $csatToken
        ]);
        
        $sent = $this->send($client['email'], $subject, $html);
        $this->logEmail($entreprise['id'], $client['email'], 'csat_survey', $conversationId, $sent);
        
        return $sent;
    }

    /**
     * Générer un token unique pour le CSAT
     */
    private function generateCSATToken(int $conversationId): string
    {
        $token = bin2hex(random_bytes(16));
        
        // Stocker le token
        $this->db->insert('csat_tokens', [
            'token' => $token,
            'conversation_id' => $conversationId,
            'expires_at' => date('Y-m-d H:i:s', strtotime('+7 days')),
            'created_at' => date('Y-m-d H:i:s')
        ]);
        
        return $token;
    }

    /**
     * Logger l'envoi d'email
     */
    private function logEmail(int $entrepriseId, string $to, string $type, int $referenceId, bool $success): void
    {
        $this->db->insert('email_logs', [
            'entreprise_id' => $entrepriseId,
            'recipient' => $to,
            'type' => $type,
            'reference_id' => $referenceId,
            'status' => $success ? 'sent' : 'failed',
            'created_at' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * Récupérer un template d'email
     */
    private function getEmailTemplate(string $template, array $data): string
    {
        $templates = [
            'ticket_created' => $this->templateTicketCreated($data),
            'escalation_alert' => $this->templateEscalationAlert($data),
            'ticket_resolved' => $this->templateTicketResolved($data),
            'csat_survey' => $this->templateCSATSurvey($data)
        ];
        
        return $templates[$template] ?? '';
    }

    private function templateTicketCreated(array $data): string
    {
        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
        .container { max-width: 600px; margin: 20px auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header { background: linear-gradient(135deg, #06b6d4 0%, #10b981 100%); color: white; padding: 30px; text-align: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .content { padding: 30px; }
        .ticket-box { background: #f0fdfa; border: 2px solid #14b8a6; border-radius: 10px; padding: 20px; text-align: center; margin: 20px 0; }
        .ticket-number { font-size: 28px; font-weight: bold; color: #0d9488; font-family: monospace; }
        .footer { background: #f8fafc; padding: 20px; text-align: center; font-size: 12px; color: #64748b; }
        .btn { display: inline-block; padding: 12px 30px; background: linear-gradient(135deg, #06b6d4 0%, #10b981 100%); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✅ Demande enregistrée</h1>
        </div>
        <div class="content">
            <p>Bonjour <strong>{$data['client_nom']}</strong>,</p>
            <p>Votre demande a bien été enregistrée. Notre équipe va la traiter dans les plus brefs délais.</p>
            
            <div class="ticket-box">
                <p style="margin: 0 0 10px 0; color: #64748b;">Numéro de suivi</p>
                <div class="ticket-number">{$data['ticket_number']}</div>
            </div>
            
            <p><strong>Sujet :</strong> {$data['sujet']}</p>
            
            <p>Conservez ce numéro pour suivre l'avancement de votre demande.</p>
            
            <p>Cordialement,<br>L'équipe {$data['entreprise_nom']}</p>
        </div>
        <div class="footer">
            <p>Cet email a été envoyé automatiquement par {$data['entreprise_nom']}</p>
        </div>
    </div>
</body>
</html>
HTML;
    }

    private function templateEscalationAlert(array $data): string
    {
        $typeLabel = $data['type'] === 'ticket' ? '🎫 Nouveau ticket' : '💬 Demande de chat en direct';
        
        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
        .container { max-width: 600px; margin: 20px auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header { background: linear-gradient(135deg, #f97316 0%, #ef4444 100%); color: white; padding: 30px; text-align: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .content { padding: 30px; }
        .alert-box { background: #fef3c7; border-left: 4px solid #f59e0b; padding: 15px; margin: 20px 0; border-radius: 0 8px 8px 0; }
        .footer { background: #f8fafc; padding: 20px; text-align: center; font-size: 12px; color: #64748b; }
        .btn { display: inline-block; padding: 14px 35px; background: linear-gradient(135deg, #06b6d4 0%, #10b981 100%); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚨 Nouvelle demande d'assistance</h1>
        </div>
        <div class="content">
            <p>Bonjour <strong>{$data['agent_nom']}</strong>,</p>
            
            <div class="alert-box">
                <strong>{$typeLabel}</strong>
                <p style="margin: 10px 0 0 0;">Un client attend votre assistance.</p>
            </div>
            
            <p><strong>Client :</strong> {$data['client_nom']}</p>
            <p><strong>Raison :</strong> {$data['reason']}</p>
            
            <p style="text-align: center;">
                <a href="{$data['dashboard_url']}" class="btn">Accéder au dashboard</a>
            </p>
        </div>
        <div class="footer">
            <p>{$data['entreprise_nom']} - Plateforme mySupport</p>
        </div>
    </div>
</body>
</html>
HTML;
    }

    private function templateTicketResolved(array $data): string
    {
        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
        .container { max-width: 600px; margin: 20px auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header { background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; padding: 30px; text-align: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .content { padding: 30px; }
        .resolved-box { background: #ecfdf5; border: 2px solid #10b981; border-radius: 10px; padding: 20px; margin: 20px 0; }
        .footer { background: #f8fafc; padding: 20px; text-align: center; font-size: 12px; color: #64748b; }
        .btn { display: inline-block; padding: 14px 35px; background: linear-gradient(135deg, #f59e0b 0%, #f97316 100%); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 20px; }
        .stars { font-size: 30px; margin: 15px 0; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>✅ Demande résolue</h1>
        </div>
        <div class="content">
            <p>Bonjour <strong>{$data['client_nom']}</strong>,</p>
            <p>Bonne nouvelle ! Votre demande a été traitée et résolue.</p>
            
            <div class="resolved-box">
                <p style="margin: 0;"><strong>Ticket :</strong> {$data['ticket_number']}</p>
                <p style="margin: 10px 0 0 0;"><strong>Sujet :</strong> {$data['sujet']}</p>
                <p style="margin: 10px 0 0 0;"><strong>Résolution :</strong> {$data['resolution_notes']}</p>
            </div>
            
            <hr style="border: none; border-top: 1px solid #e2e8f0; margin: 25px 0;">
            
            <p style="text-align: center;"><strong>Votre avis compte !</strong></p>
            <p style="text-align: center;">Comment évaluez-vous notre service ?</p>
            
            <p style="text-align: center;">
                <a href="{$data['csat_url']}" class="btn">⭐ Donner mon avis</a>
            </p>
        </div>
        <div class="footer">
            <p>Merci pour votre confiance !<br>{$data['entreprise_nom']}</p>
        </div>
    </div>
</body>
</html>
HTML;
    }

    private function templateCSATSurvey(array $data): string
    {
        return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: 'Segoe UI', Arial, sans-serif; line-height: 1.6; color: #333; margin: 0; padding: 0; background: #f5f5f5; }
        .container { max-width: 600px; margin: 20px auto; background: white; border-radius: 12px; overflow: hidden; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .header { background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%); color: white; padding: 30px; text-align: center; }
        .header h1 { margin: 0; font-size: 24px; }
        .content { padding: 30px; text-align: center; }
        .stars { font-size: 40px; margin: 20px 0; letter-spacing: 10px; }
        .footer { background: #f8fafc; padding: 20px; text-align: center; font-size: 12px; color: #64748b; }
        .btn { display: inline-block; padding: 14px 35px; background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%); color: white; text-decoration: none; border-radius: 8px; font-weight: 600; margin-top: 20px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>⭐ Votre avis compte !</h1>
        </div>
        <div class="content">
            <p>Bonjour <strong>{$data['client_nom']}</strong>,</p>
            <p>Nous espérons que vous avez été satisfait(e) de notre service.</p>
            
            <div class="stars">⭐⭐⭐⭐⭐</div>
            
            <p>Prenez 30 secondes pour nous dire comment nous avons fait.</p>
            <p>Votre retour nous aide à nous améliorer !</p>
            
            <a href="{$data['csat_url']}" class="btn">Donner mon avis</a>
        </div>
        <div class="footer">
            <p>Merci pour votre confiance !<br>{$data['entreprise_nom']}</p>
        </div>
    </div>
</body>
</html>
HTML;
    }
}
