<?php
/**
 * Email Configuration Class
 * Handles email settings and SMTP configuration
 */

class EmailConfig {
    private $config;
    
    public function __construct() {
        $this->loadConfig();
    }
    
    private function loadConfig() {
        global $conn;
        
        // Default configuration - Production Hosting Settings
        $this->config = [
            'smtp_host' => 'mail.kso-chd.online',
            'smtp_port' => 465,
            'smtp_username' => 'info@kso-chd.online',
            'smtp_password' => 'KSO@2025',
            'smtp_encryption' => 'ssl',
            'from_email' => 'info@kso-chd.online',
            'from_name' => 'KSO Chandigarh',
            'smtp_auth' => true,
            'smtp_secure' => 'tls',
            'charset' => 'UTF-8',
            'debug_level' => 0,
            'timeout' => 30,
            'email_enabled' => true,
            'max_retry' => 3,
            'queue_enabled' => true,
            'batch_size' => 50,
            'rate_limit' => 100, // emails per hour
            'email_auto_welcome' => true,
            'email_auto_approval' => true,
            'email_auto_events' => true,
            'email_auto_fees' => true,
            'email_auto_newsletter' => true,
            'email_bounce_handling' => true,
            'email_tracking' => true,
            'email_analytics' => true,
            'email_signature' => '',
            'email_reply_to' => '',
            'email_priority' => 3, // 1=High, 3=Normal, 5=Low
            'email_html' => true,
            'email_attachments' => true,
            'email_max_size' => 25 // MB
        ];
        
        // Load from database settings
        if ($conn) {
            $stmt = $conn->prepare("SELECT setting_key, setting_value FROM settings WHERE setting_key LIKE 'email_%' OR setting_key LIKE 'smtp_%'");
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $key = $row['setting_key'];
                $value = $row['setting_value'];
                
                // Convert string values to appropriate types
                if (in_array($key, ['smtp_port', 'max_retry', 'batch_size', 'rate_limit', 'timeout', 'debug_level', 'email_priority', 'email_max_size'])) {
                    $this->config[$key] = (int)$value;
                } elseif (in_array($key, ['email_enabled', 'smtp_auth', 'queue_enabled', 'email_auto_welcome', 'email_auto_approval', 'email_auto_events', 'email_auto_fees', 'email_auto_newsletter', 'email_bounce_handling', 'email_tracking', 'email_analytics', 'email_html', 'email_attachments'])) {
                    $this->config[$key] = $value === '1' || $value === 'true';
                } else {
                    $this->config[$key] = $value;
                }
            }
        }
    }
    
    public function get($key, $default = null) {
        return $this->config[$key] ?? $default;
    }
    
    public function set($key, $value) {
        $this->config[$key] = $value;
        $this->saveToDatabase($key, $value);
    }
    
    private function saveToDatabase($key, $value) {
        global $conn;
        
        if ($conn) {
            $stmt = $conn->prepare("INSERT INTO settings (setting_key, setting_value, setting_type, description, is_public, created_at, updated_at) VALUES (?, ?, 'string', ?, 0, NOW(), NOW()) ON DUPLICATE KEY UPDATE setting_value = ?, updated_at = NOW()");
            $description = "Email configuration: " . str_replace('_', ' ', $key);
            $stmt->bind_param("ssss", $key, $value, $description, $value);
            $stmt->execute();
        }
    }
    
    public function getAll() {
        return $this->config;
    }
    
    public function isEnabled() {
        return $this->config['email_enabled'] === true || $this->config['email_enabled'] === '1';
    }
    
    public function validate() {
        $required = ['smtp_host', 'smtp_port', 'smtp_username', 'smtp_password', 'from_email', 'from_name'];
        
        foreach ($required as $field) {
            if (empty($this->config[$field])) {
                throw new Exception("Email configuration missing: {$field}");
            }
        }
        
        if (!filter_var($this->config['from_email'], FILTER_VALIDATE_EMAIL)) {
            throw new Exception("Invalid from email address");
        }
        
        if (!empty($this->config['email_reply_to']) && !filter_var($this->config['email_reply_to'], FILTER_VALIDATE_EMAIL)) {
            throw new Exception("Invalid reply-to email address");
        }
        
        if (!in_array($this->config['smtp_encryption'], ['tls', 'ssl', 'none', ''])) {
            throw new Exception("Invalid SMTP encryption type");
        }
        
        if ($this->config['smtp_port'] < 1 || $this->config['smtp_port'] > 65535) {
            throw new Exception("Invalid SMTP port number");
        }
        
        return true;
    }
    
    public function testConnection() {
        if (!$this->isEnabled()) {
            throw new Exception("Email service is disabled");
        }
        
        $this->validate();
        
        // Test SMTP connection
        $mail = new PHPMailer(true);
        
        try {
            $mail->isSMTP();
            $mail->Host = $this->config['smtp_host'];
            $mail->SMTPAuth = $this->config['smtp_auth'];
            $mail->Username = $this->config['smtp_username'];
            $mail->Password = $this->config['smtp_password'];
            $mail->SMTPSecure = $this->config['smtp_encryption'];
            $mail->Port = $this->config['smtp_port'];
            $mail->Timeout = $this->config['timeout'];
            
            $mail->smtpConnect();
            $mail->smtpClose();
            
            return true;
        } catch (Exception $e) {
            throw new Exception("SMTP connection failed: " . $e->getMessage());
        }
    }
    
    public function getTemplateVariables() {
        return [
            'member' => ['first_name', 'last_name', 'kso_id', 'email', 'phone', 'membership_type', 'join_date', 'status'],
            'event' => ['event_name', 'event_date', 'event_time', 'event_location', 'event_description', 'registration_url'],
            'organization' => ['organization_name', 'website_url', 'contact_email', 'contact_phone', 'address'],
            'system' => ['current_date', 'current_time', 'current_year', 'login_url', 'support_url'],
            'fee' => ['amount', 'due_date', 'payment_url', 'invoice_number', 'description']
        ];
    }
    
    public function getEmailStatistics() {
        global $conn;
        
        $stats = [
            'total_sent' => 0,
            'total_failed' => 0,
            'total_pending' => 0,
            'success_rate' => 0,
            'today_sent' => 0,
            'this_month_sent' => 0,
            'templates_usage' => []
        ];
        
        if ($conn) {
            // Get overall statistics
            $stmt = $conn->prepare("SELECT status, COUNT(*) as count FROM email_logs GROUP BY status");
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $stats['total_' . $row['status']] = (int)$row['count'];
            }
            
            // Calculate success rate
            $total = $stats['total_sent'] + $stats['total_failed'];
            if ($total > 0) {
                $stats['success_rate'] = round(($stats['total_sent'] / $total) * 100, 2);
            }
            
            // Get today's sent emails
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM email_logs WHERE status = 'sent' AND DATE(sent_at) = CURDATE()");
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stats['today_sent'] = (int)$row['count'];
            
            // Get this month's sent emails
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM email_logs WHERE status = 'sent' AND MONTH(sent_at) = MONTH(CURRENT_DATE()) AND YEAR(sent_at) = YEAR(CURRENT_DATE())");
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            $stats['this_month_sent'] = (int)$row['count'];
            
            // Get template usage
            $stmt = $conn->prepare("SELECT template_used, COUNT(*) as count FROM email_logs WHERE template_used IS NOT NULL GROUP BY template_used ORDER BY count DESC");
            $stmt->execute();
            $result = $stmt->get_result();
            
            while ($row = $result->fetch_assoc()) {
                $stats['templates_usage'][$row['template_used']] = (int)$row['count'];
            }
        }
        
        return $stats;
    }
    
    public function cleanupOldLogs($days = 30) {
        global $conn;
        
        if ($conn) {
            $stmt = $conn->prepare("DELETE FROM email_logs WHERE sent_at < DATE_SUB(NOW(), INTERVAL ? DAY)");
            $stmt->bind_param("i", $days);
            $stmt->execute();
            
            return $stmt->affected_rows;
        }
        
        return 0;
    }
    
    public function getRateLimitStatus() {
        global $conn;
        
        $status = [
            'current_hour_count' => 0,
            'limit' => $this->config['rate_limit'],
            'remaining' => $this->config['rate_limit'],
            'reset_time' => date('Y-m-d H:00:00', strtotime('+1 hour'))
        ];
        
        if ($conn) {
            $stmt = $conn->prepare("SELECT COUNT(*) as count FROM email_logs WHERE sent_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_assoc();
            
            $status['current_hour_count'] = (int)$row['count'];
            $status['remaining'] = max(0, $this->config['rate_limit'] - $status['current_hour_count']);
        }
        
        return $status;
    }
    
    public function isRateLimited() {
        $status = $this->getRateLimitStatus();
        return $status['remaining'] <= 0;
    }
}

// Include PHPMailer if not already included
if (!class_exists('PHPMailer\PHPMailer\PHPMailer')) {
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/PHPMailer.php';
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/SMTP.php';
    require_once __DIR__ . '/../vendor/phpmailer/phpmailer/src/Exception.php';
}

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