<?php
require_once __DIR__ . '/../models/SiteSettings.php';
require_once __DIR__ . '/../vendor/autoload.php';

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

class EmailHelper {
    private $settings;

    public function __construct() {
        $siteSettings = new SiteSettings();
        $this->settings = $siteSettings->getAllSettings();
    }

    /**
     * Set temporary settings for testing
     */
    public function setTemporarySettings($settings) {
        $this->settings = array_merge($this->settings, $settings);
    }

    /**
     * Send password reset email
     */
    public function sendPasswordResetEmail($email, $token) {
        $siteTitle = $this->settings['site_title'] ?? 'Game Portal';
        $resetLink = "http://{$_SERVER['HTTP_HOST']}/reset-password?email=" . urlencode($email) . "&token=" . urlencode($token);

        $subject = "Reset Your Password - {$siteTitle}";

        $message = "
        <html>
        <head>
            <title>Reset Your Password</title>
        </head>
        <body>
            <div style='max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;'>
                <h2 style='color: #4f46e5;'>Reset Your Password</h2>
                <p>Hello,</p>
                <p>You have requested to reset your password. Please click the link below to reset your password:</p>
                <p><a href='{$resetLink}' style='display: inline-block; padding: 10px 20px; background-color: #4f46e5; color: #ffffff; text-decoration: none; border-radius: 5px;'>Reset Password</a></p>
                <p>If you did not request a password reset, please ignore this email.</p>
                <p>This link will expire in 1 hour.</p>
                <p>Regards,<br>{$siteTitle} Team</p>
            </div>
        </body>
        </html>
        ";

        // Get email settings
        $fromEmail = $this->settings['smtp_from_email'] ?? 'noreply@example.com';
        $fromName = $this->settings['smtp_from_name'] ?? $siteTitle;
        $smtpHost = $this->settings['smtp_host'] ?? '';
        $smtpPort = $this->settings['smtp_port'] ?? '';
        $smtpUsername = $this->settings['smtp_username'] ?? '';
        $smtpPassword = $this->settings['smtp_password'] ?? '';

        // Check if SMTP settings are configured
        if (!empty($smtpHost) && !empty($smtpPort) && !empty($smtpUsername) && !empty($smtpPassword)) {
            // Use PHPMailer with SMTP
            return $this->sendWithPHPMailer($email, $subject, $message, $fromEmail, $fromName);
        } else {
            // Fallback to PHP mail() function
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: {$fromName} <{$fromEmail}>" . "\r\n";

            return mail($email, $subject, $message, $headers);
        }
    }

    /**
     * Send verification email
     */
    public function sendVerificationEmail($email, $userId, $token) {
        $siteTitle = $this->settings['site_title'] ?? 'Game Portal';
        $verifyLink = "http://{$_SERVER['HTTP_HOST']}/verify-email?id=" . urlencode($userId) . "&token=" . urlencode($token);

        $subject = "Verify Your Email - {$siteTitle}";

        $message = "
        <html>
        <head>
            <title>Verify Your Email</title>
        </head>
        <body>
            <div style='max-width: 600px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif;'>
                <h2 style='color: #4f46e5;'>Verify Your Email</h2>
                <p>Hello,</p>
                <p>Thank you for registering. Please click the link below to verify your email address:</p>
                <p><a href='{$verifyLink}' style='display: inline-block; padding: 10px 20px; background-color: #4f46e5; color: #ffffff; text-decoration: none; border-radius: 5px;'>Verify Email</a></p>
                <p><strong>Important:</strong> You must verify your email before you can log in to your account.</p>
                <p>If you don't see this email in your inbox, please check your spam or junk folder.</p>
                <p>If you did not register on our site, please ignore this email.</p>
                <p>Regards,<br>{$siteTitle} Team</p>
            </div>
        </body>
        </html>
        ";

        // Get email settings
        $fromEmail = $this->settings['smtp_from_email'] ?? 'noreply@example.com';
        $fromName = $this->settings['smtp_from_name'] ?? $siteTitle;
        $smtpHost = $this->settings['smtp_host'] ?? '';
        $smtpPort = $this->settings['smtp_port'] ?? '';
        $smtpUsername = $this->settings['smtp_username'] ?? '';
        $smtpPassword = $this->settings['smtp_password'] ?? '';

        // Check if SMTP settings are configured
        if (!empty($smtpHost) && !empty($smtpPort) && !empty($smtpUsername) && !empty($smtpPassword)) {
            // Use PHPMailer with SMTP
            return $this->sendWithPHPMailer($email, $subject, $message, $fromEmail, $fromName);
        } else {
            // Fallback to PHP mail() function
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: {$fromName} <{$fromEmail}>" . "\r\n";

            return mail($email, $subject, $message, $headers);
        }
    }

    /**
     * Send email using PHPMailer with SMTP
     */
    private function sendWithPHPMailer($to, $subject, $message, $fromEmail, $fromName) {
        try {
            // Create a new PHPMailer instance
            $mail = new PHPMailer(true);

            // Server settings
            $mail->isSMTP();
            $mail->Host = $this->settings['smtp_host'];
            $mail->SMTPAuth = true;
            $mail->Username = $this->settings['smtp_username'];
            $mail->Password = $this->settings['smtp_password'];
            $mail->Port = $this->settings['smtp_port'];

            // Enable TLS encryption if port is 587
            if ($this->settings['smtp_port'] == '587') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            }
            // Enable SSL encryption if port is 465
            elseif ($this->settings['smtp_port'] == '465') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            }

            // Set debug level for troubleshooting (0 = off, 1 = client messages, 2 = client and server messages)
            // $mail->SMTPDebug = SMTP::DEBUG_SERVER; // Uncomment for debugging

            // Recipients
            $mail->setFrom($fromEmail, $fromName);
            $mail->addAddress($to);

            // Content
            $mail->isHTML(true);
            $mail->Subject = $subject;
            $mail->Body = $message;

            // Send the email
            return $mail->send();
        } catch (Exception $e) {
            // Log the error
            error_log('PHPMailer Error: ' . ($mail->ErrorInfo ?? $e->getMessage()));

            // Fallback to PHP mail() function
            $headers = "MIME-Version: 1.0" . "\r\n";
            $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
            $headers .= "From: {$fromName} <{$fromEmail}>" . "\r\n";

            return mail($to, $subject, $message, $headers);
        }
    }

    /**
     * Send a test email using SMTP
     */
    public function sendTestEmail($to, $subject, $message) {
        $fromEmail = $this->settings['smtp_from_email'] ?? 'noreply@example.com';
        $fromName = $this->settings['smtp_from_name'] ?? 'Test Email';

        // Force using PHPMailer with SMTP for testing
        return $this->sendWithPHPMailer($to, $subject, $message, $fromEmail, $fromName);
    }

    /**
     * Test SMTP connection with provided settings
     */
    public function testSmtpConnection($smtpSettings) {
        try {
            // Create a new PHPMailer instance
            $mail = new PHPMailer(true);

            // Server settings
            $mail->isSMTP();
            $mail->Host = $smtpSettings['host'];
            $mail->SMTPAuth = true;
            $mail->Username = $smtpSettings['username'];
            $mail->Password = $smtpSettings['password'];
            $mail->Port = $smtpSettings['port'];

            // Enable TLS encryption if port is 587
            if ($smtpSettings['port'] == '587') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            }
            // Enable SSL encryption if port is 465
            elseif ($smtpSettings['port'] == '465') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            }

            // Set timeout for connection test
            $mail->Timeout = 10;
            $mail->SMTPOptions = array(
                'ssl' => array(
                    'verify_peer' => false,
                    'verify_peer_name' => false,
                    'allow_self_signed' => true
                )
            );

            // Test the connection by connecting to SMTP server
            $mail->smtpConnect();
            $mail->smtpClose();

            return [
                'success' => true,
                'message' => 'SMTP connection successful!'
            ];
        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => 'SMTP connection failed: ' . $e->getMessage()
            ];
        }
    }
}
