<?php
/**
 * Mailer Class - SMTP Email Sender for WeaverSM
 * Uses PHPMailer for reliable email delivery
 */

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

class Mailer {
    private $mail;
    private $settings;
    
    public function __construct() {
        // Load email settings from database
        $this->loadSettings();
        
        // Initialize PHPMailer
        $this->mail = new PHPMailer(true);
        $this->configure();
    }
    
    /**
     * Load SMTP settings from database
     */
    private function loadSettings() {
        $defaults = [
            'mail_driver' => 'smtp',
            'mail_host' => '',
            'mail_port' => '587',
            'mail_username' => '',
            'mail_password' => '',
            'mail_encryption' => 'tls',
            'mail_from_address' => '',
            'mail_from_name' => SITE_NAME
        ];
        
        try {
            $pdo = getDBConnection();
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM site_settings WHERE setting_key LIKE 'mail_%'");
            $this->settings = $defaults;
            
            while ($row = $stmt->fetch()) {
                $this->settings[$row['setting_key']] = $row['setting_value'];
            }
        } catch (Exception $e) {
            $this->settings = $defaults;
        }
    }
    
    /**
     * Configure PHPMailer with SMTP settings
     */
    private function configure() {
        try {
            // Server settings
            if ($this->settings['mail_driver'] === 'smtp') {
                $this->mail->isSMTP();
                $this->mail->Host = $this->settings['mail_host'];
                $this->mail->SMTPAuth = true;
                $this->mail->Username = $this->settings['mail_username'];
                $this->mail->Password = $this->settings['mail_password'];
                $this->mail->Port = (int)$this->settings['mail_port'];
                
                // Encryption
                if ($this->settings['mail_encryption'] === 'tls') {
                    $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
                } elseif ($this->settings['mail_encryption'] === 'ssl') {
                    $this->mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
                }
                
                // Timeout settings
                $this->mail->Timeout = 30;
                $this->mail->SMTPKeepAlive = false;
            } else {
                $this->mail->isMail();
            }
            
            // Default from
            $fromAddress = $this->settings['mail_from_address'] ?: $this->settings['mail_username'];
            $fromName = $this->settings['mail_from_name'] ?: SITE_NAME;
            
            if ($fromAddress) {
                $this->mail->setFrom($fromAddress, $fromName);
            }
            
            // HTML email
            $this->mail->isHTML(true);
            $this->mail->CharSet = 'UTF-8';
            
        } catch (Exception $e) {
            error_log("Mailer config error: " . $e->getMessage());
        }
    }
    
    /**
     * Check if SMTP is configured
     */
    public function isConfigured() {
        return !empty($this->settings['mail_host']) && !empty($this->settings['mail_username']);
    }
    
    /**
     * Send an email
     */
    public function send($to, $subject, $htmlBody, $plainBody = '') {
        if (!$this->isConfigured()) {
            error_log("Mailer not configured - email not sent to: $to");
            return false;
        }
        
        try {
            // Clear previous recipients
            $this->mail->clearAddresses();
            $this->mail->clearAttachments();
            
            // Recipient
            $this->mail->addAddress($to);
            
            // Content
            $this->mail->Subject = $subject;
            $this->mail->Body = $htmlBody;
            $this->mail->AltBody = $plainBody ?: strip_tags($htmlBody);
            
            $this->mail->send();
            return true;
            
        } catch (Exception $e) {
            error_log("Mailer error: " . $this->mail->ErrorInfo);
            return false;
        }
    }
    
    /**
     * Send password reset code email
     */
    public function sendPasswordResetCode($email, $name, $code) {
        $siteName = SITE_NAME;
        $siteUrl = SITE_URL;
        
        $subject = "Password Reset Code - $siteName";
        
        $htmlBody = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0; padding:0; background-color:#0A1628; font-family:'Segoe UI',Arial,sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#0A1628; padding:40px 20px;">
        <tr>
            <td align="center">
                <table width="100%" cellpadding="0" cellspacing="0" style="max-width:500px; background-color:#0F2744; border-radius:16px; overflow:hidden;">
                    <!-- Header -->
                    <tr>
                        <td style="background: linear-gradient(135deg, #1E3A5F 0%, #0F2744 100%); padding:30px; text-align:center;">
                            <h1 style="margin:0; color:#F5A623; font-size:28px;">🔐 $siteName</h1>
                        </td>
                    </tr>
                    <!-- Content -->
                    <tr>
                        <td style="padding:40px 30px;">
                            <p style="color:#E5E7EB; font-size:16px; margin:0 0 20px;">Hi <strong style="color:#F5A623;">$name</strong>,</p>
                            <p style="color:#9CA3AF; font-size:15px; line-height:1.6; margin:0 0 30px;">You requested to reset your password. Use the code below to proceed:</p>
                            
                            <!-- Code Box -->
                            <div style="background:#0A1628; border:2px solid #F5A623; border-radius:12px; padding:25px; text-align:center; margin:0 0 30px;">
                                <p style="color:#9CA3AF; font-size:12px; margin:0 0 10px; text-transform:uppercase; letter-spacing:1px;">Your Reset Code</p>
                                <p style="color:#F5A623; font-size:36px; font-weight:700; letter-spacing:8px; margin:0;">$code</p>
                            </div>
                            
                            <p style="color:#9CA3AF; font-size:14px; line-height:1.6; margin:0 0 10px;">⏱️ This code expires in <strong style="color:#EF4444;">15 minutes</strong>.</p>
                            <p style="color:#9CA3AF; font-size:14px; line-height:1.6; margin:0;">If you didn't request this, please ignore this email.</p>
                        </td>
                    </tr>
                    <!-- Footer -->
                    <tr>
                        <td style="background:#0A1628; padding:20px 30px; text-align:center; border-top:1px solid #1E3A5F;">
                            <p style="color:#6B7280; font-size:12px; margin:0;">© 2024 $siteName. All rights reserved.</p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
HTML;

        $plainBody = <<<TEXT
Hi $name,

You requested to reset your password for $siteName.

Your reset code is: $code

This code expires in 15 minutes.

If you didn't request this, please ignore this email.

- $siteName Team
TEXT;

        return $this->send($email, $subject, $htmlBody, $plainBody);
    }
    
    /**
     * Send welcome email to new user
     */
    public function sendWelcomeEmail($email, $name) {
        $siteName = SITE_NAME;
        $siteUrl = SITE_URL;
        
        $subject = "Welcome to $siteName!";
        
        $htmlBody = <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body style="margin:0; padding:0; background-color:#0A1628; font-family:'Segoe UI',Arial,sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#0A1628; padding:40px 20px;">
        <tr>
            <td align="center">
                <table width="100%" cellpadding="0" cellspacing="0" style="max-width:500px; background-color:#0F2744; border-radius:16px; overflow:hidden;">
                    <tr>
                        <td style="background: linear-gradient(135deg, #1E3A5F 0%, #0F2744 100%); padding:30px; text-align:center;">
                            <h1 style="margin:0; color:#F5A623; font-size:28px;">🎉 Welcome to $siteName!</h1>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:40px 30px;">
                            <p style="color:#E5E7EB; font-size:16px; margin:0 0 20px;">Hi <strong style="color:#F5A623;">$name</strong>,</p>
                            <p style="color:#9CA3AF; font-size:15px; line-height:1.6; margin:0 0 20px;">Welcome aboard! Your account has been successfully created.</p>
                            <p style="color:#9CA3AF; font-size:15px; line-height:1.6; margin:0 0 30px;">You can now access all our services including SMS verification and social media marketing.</p>
                            
                            <div style="text-align:center;">
                                <a href="$siteUrl/login.php" style="display:inline-block; background:#F5A623; color:#0A1628; text-decoration:none; padding:14px 30px; border-radius:8px; font-weight:600; font-size:16px;">Get Started</a>
                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td style="background:#0A1628; padding:20px 30px; text-align:center; border-top:1px solid #1E3A5F;">
                            <p style="color:#6B7280; font-size:12px; margin:0;">© 2024 $siteName. All rights reserved.</p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
HTML;

        return $this->send($email, $subject, $htmlBody);
    }
    
    /**
     * Send order confirmation email
     */
    public function sendOrderConfirmation($email, $name, $orderType, $orderDetails) {
        $siteName = SITE_NAME;
        $subject = "Order Confirmation - $siteName";
        
        $detailsHtml = '';
        foreach ($orderDetails as $key => $value) {
            $label = ucwords(str_replace('_', ' ', $key));
            $detailsHtml .= "<tr><td style='color:#9CA3AF; padding:8px 0; border-bottom:1px solid #1E3A5F;'>$label</td><td style='color:#E5E7EB; padding:8px 0; border-bottom:1px solid #1E3A5F; text-align:right;'>$value</td></tr>";
        }
        
        $htmlBody = <<<HTML
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"></head>
<body style="margin:0; padding:0; background-color:#0A1628; font-family:'Segoe UI',Arial,sans-serif;">
    <table width="100%" cellpadding="0" cellspacing="0" style="background-color:#0A1628; padding:40px 20px;">
        <tr>
            <td align="center">
                <table width="100%" cellpadding="0" cellspacing="0" style="max-width:500px; background-color:#0F2744; border-radius:16px; overflow:hidden;">
                    <tr>
                        <td style="background: linear-gradient(135deg, #1E3A5F 0%, #0F2744 100%); padding:30px; text-align:center;">
                            <h1 style="margin:0; color:#F5A623; font-size:24px;">✅ Order Confirmed</h1>
                        </td>
                    </tr>
                    <tr>
                        <td style="padding:30px;">
                            <p style="color:#E5E7EB; font-size:16px; margin:0 0 20px;">Hi <strong style="color:#F5A623;">$name</strong>,</p>
                            <p style="color:#9CA3AF; font-size:15px; margin:0 0 20px;">Your $orderType order has been placed successfully!</p>
                            
                            <table width="100%" style="margin-bottom:20px;">
                                $detailsHtml
                            </table>
                        </td>
                    </tr>
                    <tr>
                        <td style="background:#0A1628; padding:20px; text-align:center; border-top:1px solid #1E3A5F;">
                            <p style="color:#6B7280; font-size:12px; margin:0;">© 2024 $siteName</p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
HTML;

        return $this->send($email, $subject, $htmlBody);
    }
    
    /**
     * Test SMTP connection
     */
    public static function testConnection($host, $port, $username, $password, $encryption) {
        $mail = new PHPMailer(true);
        
        try {
            $mail->isSMTP();
            $mail->Host = $host;
            $mail->SMTPAuth = true;
            $mail->Username = $username;
            $mail->Password = $password;
            $mail->Port = (int)$port;
            
            if ($encryption === 'tls') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
            } elseif ($encryption === 'ssl') {
                $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;
            }
            
            $mail->Timeout = 10;
            $mail->SMTPDebug = 0;
            
            // Try to connect
            if ($mail->smtpConnect()) {
                $mail->smtpClose();
                return ['success' => true, 'message' => 'SMTP connection successful!'];
            } else {
                return ['success' => false, 'message' => 'Could not connect to SMTP server'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}