<?php
namespace App\Services;

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

class EmailService {
    private $pdo;
    private $smtpConfig = null;
    private $error = '';

    public function __construct(\PDO $pdo) {
        $this->pdo = $pdo;
    }

    private function loadSmtpConfig(): ?array {
        if ($this->smtpConfig !== null) return $this->smtpConfig;
        try {
            $this->smtpConfig = $this->pdo->query("SELECT * FROM smtp_settings WHERE is_active = 1 ORDER BY id DESC LIMIT 1")->fetch();
            return $this->smtpConfig;
        } catch (\PDOException $e) {
            error_log("[EmailService] SMTP load failed: " . $e->getMessage());
            return null;
        }
    }

    private function createMailer(): PHPMailer {
        $smtp = $this->loadSmtpConfig();
        $mail = new PHPMailer(true);
        if ($smtp) {
            $mail->isSMTP();
            $mail->Host = $smtp['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $smtp['username'];
            $mail->Password = decrypt_secret($smtp['password_encrypted']);
            $mail->SMTPSecure = $smtp['encryption'] === 'ssl' ? PHPMailer::ENCRYPTION_SMTPS : PHPMailer::ENCRYPTION_STARTTLS;
            $mail->Port = (int)$smtp['port'];
            $mail->CharSet = 'UTF-8';
        }
        return $mail;
    }

    private function wrapWithBranding(string $body): string {
        $name = get_setting('academy_name', 'CIX Orbit Academy');
        $slogan = get_setting('slogan', 'Learn. Build. Automate. Grow.');
        $year = date('Y');
        return '<!DOCTYPE html><html><head><meta charset="UTF-8"><style>body{font-family:Segoe UI,sans-serif;background:#f4f4f4;margin:0;padding:20px;}.wrapper{max-width:600px;margin:0 auto;background:#fff;border-radius:8px;overflow:hidden;border:1px solid #ddd;}.header{background:#000;padding:25px;text-align:center;}.header h2{color:#ff6b00;margin:0;font-size:20px;}.header p{color:#b0b0b0;margin:5px 0 0;font-size:12px;}.content{padding:30px;color:#333;line-height:1.7;}.content h3{color:#ff6b00;}.content a{color:#ff6b00;}.footer{background:#1a1a1a;padding:20px;text-align:center;color:#666;font-size:11px;}.footer p{margin:3px 0;}.btn{display:inline-block;padding:12px 30px;background:#ff6b00;color:#fff;text-decoration:none;border-radius:6px;font-weight:bold;margin:10px 0;}.bank-table{width:100%;border-collapse:collapse;margin:15px 0;}.bank-table td,.bank-table th{padding:8px 12px;border:1px solid #eee;text-align:left;font-size:13px;}.bank-table th{background:#f5f5f5;}</style></head><body><div class="wrapper"><div class="header"><h2>' . htmlspecialchars($name) . '</h2><p>' . htmlspecialchars($slogan) . '</p></div><div class="content">' . $body . '</div><div class="footer"><p>&copy; ' . $year . ' CIX Connect. All rights reserved.</p><p>Academic: academic@cixconnect.co.za | WhatsApp: 083 759 8075</p><p>Office: 012 004 0207</p></div></div></body></html>';
    }

    public function send(string $to, string $subject, string $body, ?string $fromName = null, ?string $fromEmail = null): bool {
        try {
            $mail = $this->createMailer();
            $smtp = $this->loadSmtpConfig();
            $mail->setFrom($fromEmail ?: ($smtp['from_email'] ?? 'noreply@cixconnect.co.za'), $fromName ?: ($smtp['from_name'] ?? 'CIX Orbit Academy'));
            $mail->addAddress($to);
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $this->wrapWithBranding($body);
            $mail->AltBody = strip_tags($body);
            $mail->send();
            $this->logEmail($to, $subject, 'sent');
            return true;
        } catch (Exception $e) {
            $this->error = $e->getMessage();
            error_log("[EmailService] Send failed: " . $e->getMessage());
            $this->logEmail($to, $subject, 'failed', $e->getMessage());
            return false;
        }
    }

    public function sendTemplate(string $to, string $templateCode, array $variables = []): bool {
        $tpl = parse_email_template($templateCode, $variables);
        if (!$tpl) {
            error_log("[EmailService] Template not found: $templateCode");
            return false;
        }
        return $this->send($to, $tpl['subject'], $tpl['body']);
    }

    public function testConnection(): array {
        $smtp = $this->loadSmtpConfig();
        if (!$smtp) return ['success' => false, 'error' => 'No SMTP settings configured'];
        try {
            $mail = $this->createMailer();
            $mail->setFrom($smtp['from_email'], 'Test');
            $mail->addAddress($smtp['from_email']);
            $mail->Subject = 'CIX Orbit Academy - SMTP Test';
            $mail->Body = '<h3>SMTP Test Successful</h3><p>Your email configuration is working correctly.</p>';
            $mail->isHTML(true);
            $mail->send();
            return ['success' => true, 'message' => 'Test email sent successfully'];
        } catch (Exception $e) {
            $this->error = $e->getMessage();
            return ['success' => false, 'error' => $e->getMessage()];
        }
    }

    public function sendBulk(array $recipients, string $subject, string $body): array {
        $results = ['sent' => 0, 'failed' => 0, 'errors' => []];
        foreach ($recipients as $email) {
            if ($this->send($email, $subject, $body)) {
                $results['sent']++;
            } else {
                $results['failed']++;
                $results['errors'][] = $email;
            }
        }
        return $results;
    }

    public function getTemplates(): array {
        return $this->pdo->query("SELECT * FROM email_templates ORDER BY code")->fetchAll();
    }

    public function updateTemplate(int $id, string $subject, string $body): bool {
        $stmt = $this->pdo->prepare("UPDATE email_templates SET subject = ?, body = ?, updated_at = NOW() WHERE id = ?");
        return $stmt->execute([$subject, $body, $id]);
    }

    public function getTemplate(string $code): ?array {
        $stmt = $this->pdo->prepare("SELECT * FROM email_templates WHERE code = ?");
        $stmt->execute([$code]);
        return $stmt->fetch() ?: null;
    }

    private function logEmail(string $to, string $subject, string $status, string $error = '') {
        try {
            $this->pdo->prepare("INSERT INTO activity_logs (activity_type, description, metadata) VALUES ('email_sent', ?, ?)")
                ->execute([$status . ': ' . $subject . ' to ' . $to, json_encode(['to' => $to, 'subject' => $subject, 'status' => $status, 'error' => $error])]);
        } catch (\Exception $e) {
            error_log("[EmailService] Log failed: " . $e->getMessage());
        }
    }

    public function getError(): string { return $this->error; }
}
