<?php
namespace TrustBnk\Admin\Lib;

use PDO;

class EmailService {
    private $conn;

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

    private function getSettings() {
        $stmt = $this->conn->query("SELECT * FROM system_settings WHERE id = 1");
        $system = $stmt->fetch();

        $stmt2 = $this->conn->query("SELECT * FROM general_settings WHERE id = 1");
        $general = $stmt2->fetch();

        return [$system, $general];
    }

    public function sendEmail(string $toEmail, string $toName, string $subject, string $html, string $emailType, ?int $userId = null, ?int $adminId = null): bool {
        [$system, $general] = $this->getSettings();

        $fromEmail = $system['from_email'] ?? 'no-reply@example.com';
        $fromName = $system['from_name'] ?? ($general['site_name'] ?? 'Notifications');

        $sent = false;
        $error = '';

        // Respect global email enable/disable
        if ((int)($system['email_enabled'] ?? 0) !== 1) {
            // Log as failed because emails are disabled
            $this->logEmail($userId, $adminId, $emailType, $toEmail, $subject, $html, 'Failed');
            return false;
        }

        // Prefer PHPMailer via Composer if available
        $hasComposer = file_exists(__DIR__ . '/../../vendor/autoload.php');
        $smtpEnabled = (int)($system['smtp_enabled'] ?? 0) === 1;

        if ($smtpEnabled && !$hasComposer) {
            // SMTP requested but PHPMailer not installed
            $error = 'SMTP enabled but PHPMailer (Composer) not installed';
            $this->logEmail($userId, $adminId, $emailType, $toEmail, $subject, $html, 'Failed');
            return false;
        }

        if ($hasComposer) {
            require_once __DIR__ . '/../../vendor/autoload.php';
            try {
                $mailer = new \PHPMailer\PHPMailer\PHPMailer(true);
                if ($smtpEnabled) {
                    $mailer->isSMTP();
                    $mailer->Host = (string)$system['smtp_host'];
                    $mailer->Port = (int)$system['smtp_port'];
                    $mailer->SMTPAuth = true;
                    $mailer->Username = (string)$system['smtp_username'];
                    $mailer->Password = (string)$system['smtp_password'];
                    $encryption = $system['smtp_encryption'] ?? 'ssl';
                    if ($encryption === 'ssl') { $mailer->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; }
                    elseif ($encryption === 'tls') { $mailer->SMTPSecure = \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; }
                }
                $mailer->CharSet = 'UTF-8';
                $mailer->setFrom($fromEmail, $fromName);
                $mailer->addAddress($toEmail, $toName);
                $mailer->isHTML(true);
                $mailer->Subject = $subject;
                $mailer->Body = $html;
                $mailer->AltBody = strip_tags($html);
                $mailer->send();
                $sent = true;
            } catch (\Throwable $t) {
                $error = $t->getMessage();
                $sent = false;
            }
        } else {
            // Fallback: use PHP mail() only if SMTP disabled
            if ($smtpEnabled) {
                $error = 'SMTP enabled but Composer/PHPMailer missing';
                $this->logEmail($userId, $adminId, $emailType, $toEmail, $subject, $html, 'Failed');
                return false;
            }
            try {
                $headers  = "MIME-Version: 1.0\r\n";
                $headers .= "Content-type: text/html; charset=UTF-8\r\n";
                $headers .= "From: {$fromName} <{$fromEmail}>\r\n";
                $sent = @mail($toEmail, $subject, $html, $headers);
            } catch (\Throwable $t) {
                $error = $t->getMessage();
                $sent = false;
            }
        }

        // Log to email_logs
        $this->logEmail($userId, $adminId, $emailType, $toEmail, $subject, $html, $sent ? 'Sent' : 'Failed', $sent);

        if (!$sent && $error) {
            // Optionally store error somewhere else or expose if needed
        }

        return $sent;
    }

    private function logEmail(?int $userId, ?int $adminId, string $emailType, string $recipientEmail, string $subject, string $message, string $status, bool $hasSent = false): void {
        try {
            $stmt = $this->conn->prepare("INSERT INTO email_logs (user_id, admin_id, email_type, recipient_email, subject, message, status, sent_at, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())");
            $stmt->execute([
                $userId,
                $adminId,
                $emailType,
                $recipientEmail,
                $subject,
                $message,
                $status,
                $hasSent ? date('Y-m-d H:i:s') : null
            ]);
        } catch (\Throwable $t) {}
    }
}
?>


