<?php
/**
 * Email System - PHPMailer Integration
 * Digital Marketplace
 * 
 * Complete email system for transactional emails
 */

// Prevent direct access
if (!defined('MARKETPLACE_VERSION')) {
    define('MARKETPLACE_VERSION', '2.0.0');
}

// ============================================
// EMAIL SETTINGS FUNCTIONS
// ============================================

if (!function_exists('get_email_settings')) {
    /**
     * Get email settings from database
     */
    function get_email_settings() {
        global $pdo;
        if (!isset($pdo)) return [];
        
        try {
            $stmt = $pdo->query("SELECT setting_key, setting_value FROM email_settings");
            $settings = [];
            while ($row = $stmt->fetch()) {
                $settings[$row['setting_key']] = $row['setting_value'];
            }
            return $settings;
        } catch (PDOException $e) {
            error_log("Error getting email settings: " . $e->getMessage());
            return [];
        }
    }
}

if (!function_exists('get_email_setting')) {
    /**
     * Get single email setting
     */
    function get_email_setting($key, $default = '') {
        $settings = get_email_settings();
        return $settings[$key] ?? $default;
    }
}

// ============================================
// SMTP MAILER CLASS
// ============================================

if (!class_exists('MarketplaceMailer')) {
    class MarketplaceMailer {
        private $settings;
        private $error;
        
        public function __construct() {
            $this->settings = get_email_settings();
        }
        
        /**
         * Send email using SMTP
         */
        public function send($to, $subject, $body, $attachments = []) {
            // Get SMTP settings
            $smtp_host = $this->settings['smtp_host'] ?? '';
            $smtp_port = $this->settings['smtp_port'] ?? 587;
            $smtp_username = $this->settings['smtp_username'] ?? '';
            $smtp_password = $this->settings['smtp_password'] ?? '';
            $smtp_encryption = $this->settings['smtp_encryption'] ?? 'tls';
            $from_email = $this->settings['smtp_from_email'] ?? $smtp_username;
            $from_name = $this->settings['smtp_from_name'] ?? 'Digital Marketplace';
            
            // Validate settings
            if (empty($smtp_host) || empty($smtp_username) || empty($smtp_password)) {
                $this->error = 'SMTP settings not configured';
                $this->log_email($to, $subject, $body, 'failed', $this->error);
                return false;
            }
            
            // Use PHPMailer if available
            $phpmailer_path = __DIR__ . '/PHPMailer/PHPMailer.php';
            
            if (file_exists($phpmailer_path)) {
                return $this->send_with_phpmailer($to, $subject, $body, $attachments);
            } else {
                // Fallback to mail() function
                return $this->send_with_mail($to, $subject, $body, $from_email, $from_name);
            }
        }
        
        /**
         * Send email using PHPMailer
         */
        private function send_with_phpmailer($to, $subject, $body, $attachments = []) {
            try {
                require_once __DIR__ . '/PHPMailer/PHPMailer.php';
                require_once __DIR__ . '/PHPMailer/SMTP.php';
                require_once __DIR__ . '/PHPMailer/Exception.php';
                
                $mail = new PHPMailer\PHPMailer\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->SMTPSecure = $this->settings['smtp_encryption'] ?? 'tls';
                $mail->Port = $this->settings['smtp_port'] ?? 587;
                
                // Recipients
                $mail->setFrom(
                    $this->settings['smtp_from_email'] ?? $this->settings['smtp_username'],
                    $this->settings['smtp_from_name'] ?? 'Digital Marketplace'
                );
                
                if (is_array($to)) {
                    foreach ($to as $email) {
                        $mail->addAddress($email);
                    }
                } else {
                    $mail->addAddress($to);
                }
                
                // Attachments
                if (!empty($attachments)) {
                    foreach ($attachments as $attachment) {
                        if (file_exists($attachment)) {
                            $mail->addAttachment($attachment);
                        }
                    }
                }
                
                // Content
                $mail->isHTML(true);
                $mail->Subject = $subject;
                $mail->Body = $this->build_html_email($body, $subject);
                $mail->AltBody = strip_tags($body);
                
                $result = $mail->send();
                
                if ($result) {
                    $this->log_email($to, $subject, $body, 'sent');
                } else {
                    $this->log_email($to, $subject, $body, 'failed', $mail->ErrorInfo);
                }
                
                return $result;
                
            } catch (Exception $e) {
                $this->error = $e->getMessage();
                $this->log_email($to, $subject, $body, 'failed', $this->error);
                return false;
            }
        }
        
        /**
         * Send email using mail() function (fallback)
         */
        private function send_with_mail($to, $subject, $body, $from_email, $from_name) {
            $headers = "From: {$from_name} <{$from_email}>\r\n";
            $headers .= "Reply-To: {$from_email}\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: text/html; charset=UTF-8\r\n";
            
            $html_body = $this->build_html_email($body, $subject);
            
            $result = mail($to, $subject, $html_body, $headers);
            
            $this->log_email($to, $subject, $body, $result ? 'sent' : 'failed', $result ? null : 'mail() failed');
            
            return $result;
        }
        
        /**
         * Build HTML email template
         */
        private function build_html_email($content, $title = '') {
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $site_url = BASE_URL;
            $logo_url = get_setting('logo_url', '');
            $primary_color = '#6366f1';
            
            return <<<HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{$title}</title>
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 0; background-color: #f3f4f6; }
        .container { max-width: 600px; margin: 0 auto; background-color: #ffffff; }
        .header { background: {$primary_color}; padding: 30px; text-align: center; }
        .header h1 { color: #ffffff; margin: 0; font-size: 24px; }
        .content { padding: 30px; color: #374151; line-height: 1.6; }
        .content h2 { color: #111827; margin-top: 0; }
        .footer { background-color: #f9fafb; padding: 20px; text-align: center; color: #6b7280; font-size: 14px; }
        .btn { display: inline-block; background: {$primary_color}; color: #ffffff; padding: 12px 24px; text-decoration: none; border-radius: 6px; margin: 10px 0; }
        .btn:hover { background: #4f46e5; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>{$site_name}</h1>
        </div>
        <div class="content">
            {$content}
        </div>
        <div class="footer">
            <p>&copy; " . date('Y') . " {$site_name}. All rights reserved.</p>
            <p><a href="{$site_url}">Visit our website</a></p>
        </div>
    </div>
</body>
</html>
HTML;
        }
        
        /**
         * Log email to database
         */
        private function log_email($to, $subject, $body, $status, $error = null) {
            global $pdo;
            if (!isset($pdo)) return;
            
            try {
                $stmt = $pdo->prepare("INSERT INTO email_log (to_email, subject, body, status, error_message, sent_at) VALUES (?, ?, ?, ?, ?, NOW())");
                $stmt->execute([
                    is_array($to) ? implode(', ', $to) : $to,
                    $subject,
                    substr($body, 0, 10000), // Limit body size
                    $status,
                    $error
                ]);
            } catch (PDOException $e) {
                error_log("Failed to log email: " . $e->getMessage());
            }
        }
        
        /**
         * Get last error
         */
        public function get_error() {
            return $this->error;
        }
    }
}

// ============================================
// EMAIL SENDING FUNCTIONS
// ============================================

if (!function_exists('send_email')) {
    /**
     * Send email wrapper function
     */
    function send_email($to, $subject, $body, $attachments = []) {
        $mailer = new MarketplaceMailer();
        return $mailer->send($to, $subject, $body, $attachments);
    }
}

if (!function_exists('send_welcome_email')) {
    /**
     * Send welcome email to new user
     */
    function send_welcome_email($user_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            
            if (!$user) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $login_url = BASE_URL . '/login.php';
            
            $subject = "Welcome to {$site_name}!";
            $body = <<<HTML
<h2>Welcome {$user['name']}!</h2>
<p>Thank you for joining {$site_name}. We are excited to have you as part of our community.</p>
<p>You can now:</p>
<ul>
    <li>Browse our premium digital products</li>
    <li>Make purchases securely</li>
    <li>Access your downloads instantly</li>
</ul>
<p><a href="{$login_url}" class="btn">Login to Your Account</a></p>
<p>If you have any questions, feel free to contact our support team.</p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            return send_email($user['email'], $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending welcome email: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_order_confirmation')) {
    /**
     * Send order confirmation email
     */
    function send_order_confirmation($order_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            // Get order details
            $stmt = $pdo->prepare("SELECT o.*, u.name as user_name, u.email as user_email 
                                  FROM orders o 
                                  LEFT JOIN users u ON o.user_id = u.id 
                                  WHERE o.id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            if (!$order) return false;
            
            // Get order items
            $stmt = $pdo->prepare("SELECT * FROM order_items WHERE order_id = ?");
            $stmt->execute([$order_id]);
            $items = $stmt->fetchAll();
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $order_url = BASE_URL . '/account/order-view.php?id=' . $order_id;
            
            // Build items HTML
            $items_html = '<table style="width:100%; border-collapse: collapse;">';
            $items_html .= '<tr style="background:#f3f4f6;"><th style="padding:10px; text-align:left;">Product</th><th style="padding:10px; text-align:right;">Price</th></tr>';
            foreach ($items as $item) {
                $items_html .= '<tr style="border-bottom:1px solid #e5e7eb;">';
                $items_html .= '<td style="padding:10px;">' . htmlspecialchars($item['product_name']) . '</td>';
                $items_html .= '<td style="padding:10px; text-align:right;">' . format_price($item['price']) . '</td>';
                $items_html .= '</tr>';
            }
            $items_html .= '</table>';
            
            $subject = "Order Confirmation - {$order['order_number']}";
            $body = <<<HTML
<h2>Thank you for your order!</h2>
<p>Your order has been received and is being processed.</p>
<h3>Order Details:</h3>
<p><strong>Order Number:</strong> {$order['order_number']}</p>
<p><strong>Date:</strong> " . format_date($order['created_at']) . "</p>
<p><strong>Total:</strong> " . format_price($order['total']) . "</p>
<h3>Items Ordered:</h3>
{$items_html}
<p>You can view your order details and download your products from your account.</p>
<p><a href="{$order_url}" class="btn">View Order</a></p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            $email = $order['user_email'] ?? $order['customer_email'];
            return send_email($email, $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending order confirmation: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_payment_received_email')) {
    /**
     * Send payment received email
     */
    function send_payment_received_email($order_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT o.*, u.email as user_email 
                                  FROM orders o 
                                  LEFT JOIN users u ON o.user_id = u.id 
                                  WHERE o.id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            if (!$order) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $order_url = BASE_URL . '/account/order-view.php?id=' . $order_id;
            
            $subject = "Payment Received - {$order['order_number']}";
            $body = <<<HTML
<h2>Payment Received!</h2>
<p>We have received your payment for order <strong>{$order['order_number']}</strong>.</p>
<p><strong>Amount Paid:</strong> " . format_price($order['total']) . "</p>
<p><strong>Payment Method:</strong> " . ucfirst($order['payment_method']) . "</p>
<p>Your order is now being processed. You will receive another email when your order is complete.</p>
<p><a href="{$order_url}" class="btn">View Order</a></p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            $email = $order['user_email'] ?? $order['customer_email'];
            return send_email($email, $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending payment email: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_order_complete_email')) {
    /**
     * Send order complete email with download links
     */
    function send_order_complete_email($order_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT o.*, u.email as user_email 
                                  FROM orders o 
                                  LEFT JOIN users u ON o.user_id = u.id 
                                  WHERE o.id = ?");
            $stmt->execute([$order_id]);
            $order = $stmt->fetch();
            
            if (!$order) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $downloads_url = BASE_URL . '/account/downloads.php';
            
            $subject = "Your Order is Complete - {$order['order_number']}";
            $body = <<<HTML
<h2>Your Order is Complete!</h2>
<p>Great news! Your order <strong>{$order['order_number']}</strong> is now complete.</p>
<p>You can now download your products from your account.</p>
<p><a href="{$downloads_url}" class="btn">Download Your Products</a></p>
<p>Thank you for your purchase!</p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            $email = $order['user_email'] ?? $order['customer_email'];
            return send_email($email, $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending complete email: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_negotiation_response_email')) {
    /**
     * Send negotiation response email
     */
    function send_negotiation_response_email($negotiation_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT n.*, p.name as product_name, u.name as user_name, u.email 
                                  FROM negotiations n 
                                  JOIN products p ON n.product_id = p.id 
                                  JOIN users u ON n.user_id = u.id 
                                  WHERE n.id = ?");
            $stmt->execute([$negotiation_id]);
            $negotiation = $stmt->fetch();
            
            if (!$negotiation) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $product_url = BASE_URL . '/product.php?slug=' . slugify($negotiation['product_name']);
            
            $status_text = ucfirst($negotiation['status']);
            $status_color = $negotiation['status'] === 'accepted' ? '#10b981' : ($negotiation['status'] === 'rejected' ? '#ef4444' : '#f59e0b');
            
            $subject = "Update on Your Price Offer - {$negotiation['product_name']}";
            $body = <<<HTML
<h2>Negotiation Update</h2>
<p>Hello {$negotiation['user_name']},</p>
<p>Your price offer for <strong>{$negotiation['product_name']}</strong> has been <strong style="color:{$status_color}">{$status_text}</strong>.</p>
HTML;
            
            if ($negotiation['status'] === 'accepted') {
                $body .= <<<HTML
<p><strong>Accepted Price:</strong> " . format_price($negotiation['offered_price']) . "</p>
<p>You can now purchase this product at the agreed price by clicking the link below:</p>
<p><a href="{$product_url}?negotiation={$negotiation_id}" class="btn">Purchase Now</a></p>
HTML;
            } elseif ($negotiation['status'] === 'rejected' && $negotiation['admin_message']) {
                $body .= <<<HTML
<p><strong>Message from Admin:</strong></p>
<blockquote style="background:#f3f4f6; padding:15px; border-left:4px solid #6366f1;">" . nl2br(htmlspecialchars($negotiation['admin_message'])) . "</blockquote>
HTML;
            }
            
            $body .= "<p>Best regards,<br>{$site_name} Team</p>";
            
            return send_email($negotiation['email'], $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending negotiation email: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_affiliate_approved_email')) {
    /**
     * Send affiliate approval email
     */
    function send_affiliate_approved_email($affiliate_id) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT a.*, u.name, u.email 
                                  FROM affiliates a 
                                  JOIN users u ON a.user_id = u.id 
                                  WHERE a.id = ?");
            $stmt->execute([$affiliate_id]);
            $affiliate = $stmt->fetch();
            
            if (!$affiliate) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $affiliate_link = BASE_URL . '/register.php?ref=' . $affiliate['affiliate_code'];
            $dashboard_url = BASE_URL . '/account/affiliate.php';
            
            $subject = "Your Affiliate Application is Approved!";
            $body = <<<HTML
<h2>Congratulations!</h2>
<p>Your affiliate application has been approved.</p>
<p>You can now start promoting our products and earn commissions.</p>
<p><strong>Your Affiliate Link:</strong> <a href="{$affiliate_link}">{$affiliate_link}</a></p>
<p><strong>Commission Rate:</strong> {$affiliate['commission_rate']}%</p>
<p><a href="{$dashboard_url}" class="btn">Go to Affiliate Dashboard</a></p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            return send_email($affiliate['email'], $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending affiliate email: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_password_reset_email')) {
    /**
     * Send password reset email
     */
    function send_password_reset_email($user_id, $token) {
        global $pdo;
        if (!isset($pdo)) return false;
        
        try {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();
            
            if (!$user) return false;
            
            $site_name = get_setting('site_name', 'Digital Marketplace');
            $reset_url = BASE_URL . '/reset-password.php?token=' . $token;
            
            $subject = "Password Reset Request - {$site_name}";
            $body = <<<HTML
<h2>Password Reset Request</h2>
<p>Hello {$user['name']},</p>
<p>We received a request to reset your password. Click the link below to reset it:</p>
<p><a href="{$reset_url}" class="btn">Reset Password</a></p>
<p>Or copy and paste this link:</p>
<p style="word-break:break-all;">{$reset_url}</p>
<p>This link will expire in 1 hour.</p>
<p>If you didn't request this, please ignore this email.</p>
<p>Best regards,<br>{$site_name} Team</p>
HTML;
            
            return send_email($user['email'], $subject, $body);
            
        } catch (PDOException $e) {
            error_log("Error sending password reset: " . $e->getMessage());
            return false;
        }
    }
}

if (!function_exists('send_admin_notification')) {
    /**
     * Send notification to admin
     */
    function send_admin_notification($type, $message) {
        $admin_email = get_setting('site_email', 'admin@example.com');
        $site_name = get_setting('site_name', 'Digital Marketplace');
        
        $subject = "[{$site_name}] Admin Notification: {$type}";
        $body = <<<HTML
<h2>Admin Notification</h2>
<p><strong>Type:</strong> {$type}</p>
<p><strong>Message:</strong></p>
<p>{$message}</p>
<p><strong>Time:</strong> " . date('Y-m-d H:i:s') . "</p>
HTML;
        
        return send_email($admin_email, $subject, $body);
    }
}

// ============================================
// EMAIL TEMPLATE FUNCTIONS
// ============================================

if (!function_exists('get_email_template')) {
    /**
     * Get email template from database
     */
    function get_email_template($template_key) {
        global $pdo;
        if (!isset($pdo)) return null;
        
        try {
            $stmt = $pdo->prepare("SELECT * FROM email_templates WHERE template_key = ? AND is_active = 1");
            $stmt->execute([$template_key]);
            return $stmt->fetch();
        } catch (PDOException $e) {
            return null;
        }
    }
}

if (!function_exists('parse_email_template')) {
    /**
     * Parse email template with variables
     */
    function parse_email_template($template, $variables = []) {
        $content = $template['body'] ?? '';
        $subject = $template['subject'] ?? '';
        
        foreach ($variables as $key => $value) {
            $content = str_replace('{{' . $key . '}}', $value, $content);
            $subject = str_replace('{{' . $key . '}}', $value, $subject);
        }
        
        return [
            'subject' => $subject,
            'body' => $content
        ];
    }
}
