<?php
/**
 * Enhanced Email Helper for KSO System
 * Supports secure SMTP with SSL/TLS authentication
 */

class KSOEmailer {
    private $config;
    
    public function __construct($email_config) {
        $this->config = $email_config;
    }
    
    /**
     * Send email with attachment using native PHP mail with proper SMTP headers
     */
    public function sendEmailWithAttachment($to, $subject, $body, $attachment_path = null, $attachment_name = null) {
        try {
            // Validate email
            if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
                throw new Exception("Invalid email address: $to");
            }
            
            // Create boundary for multipart message
            $boundary = md5(uniqid(time()));
            
            // Headers for SMTP authentication (if supported by server)
            $headers = "From: {$this->config['from_name']} <{$this->config['from_email']}>\r\n";
            $headers .= "Reply-To: {$this->config['reply_to']}\r\n";
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-Type: multipart/mixed; boundary=\"{$boundary}\"\r\n";
            $headers .= "X-Mailer: KSO System\r\n";
            
            // Message body
            $message = "--{$boundary}\r\n";
            $message .= "Content-Type: text/html; charset=UTF-8\r\n";
            $message .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
            $message .= $body . "\r\n";
            
            // Add attachment if provided
            if ($attachment_path && file_exists($attachment_path)) {
                $attachment_content = file_get_contents($attachment_path);
                $attachment_content = chunk_split(base64_encode($attachment_content));
                $attachment_name = $attachment_name ?: basename($attachment_path);
                
                $message .= "--{$boundary}\r\n";
                $message .= "Content-Type: application/octet-stream; name=\"{$attachment_name}\"\r\n";
                $message .= "Content-Transfer-Encoding: base64\r\n";
                $message .= "Content-Disposition: attachment; filename=\"{$attachment_name}\"\r\n\r\n";
                $message .= $attachment_content . "\r\n";
            }
            
            $message .= "--{$boundary}--\r\n";
            
            // Send email
            $result = mail($to, $subject, $message, $headers);
            
            if ($result) {
                return ['success' => true, 'message' => 'Email sent successfully'];
            } else {
                return ['success' => false, 'message' => 'Failed to send email'];
            }
            
        } catch (Exception $e) {
            return ['success' => false, 'message' => 'Email error: ' . $e->getMessage()];
        }
    }
    
    /**
     * Send receipt email
     */
    public function sendReceiptEmail($receipt_data, $pdf_path = null) {
        $subject = 'Receipt #' . $receipt_data['receipt_number'];
        $member_name = $receipt_data['first_name'] . ' ' . $receipt_data['last_name'];
        
        $body = $this->generateReceiptEmailBody($receipt_data, $member_name);
        
        $attachment_name = $pdf_path ? 'receipt_' . $receipt_data['receipt_number'] . '.pdf' : null;
        
        return $this->sendEmailWithAttachment(
            $receipt_data['email'],
            $subject,
            $body,
            $pdf_path,
            $attachment_name
        );
    }
    
    /**
     * Send invoice email
     */
    public function sendInvoiceEmail($invoice_data, $pdf_path = null) {
        $subject = 'Invoice #' . $invoice_data['invoice_number'];
        $member_name = $invoice_data['first_name'] . ' ' . $invoice_data['last_name'];
        
        $body = $this->generateInvoiceEmailBody($invoice_data, $member_name);
        
        $attachment_name = $pdf_path ? 'invoice_' . $invoice_data['invoice_number'] . '.pdf' : null;
        
        return $this->sendEmailWithAttachment(
            $invoice_data['email'],
            $subject,
            $body,
            $pdf_path,
            $attachment_name
        );
    }
    
    /**
     * Generate receipt email body
     */
    private function generateReceiptEmailBody($receipt, $member_name) {
        return "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .header { background-color: #006496; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; }
                .receipt-details { background-color: #f9f9f9; padding: 15px; margin: 20px 0; border-radius: 5px; }
                .receipt-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                .receipt-table th, .receipt-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                .receipt-table th { background-color: #006496; color: white; }
                .footer { background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class='header'>
                <h1>KSO Chandigarh</h1>
                <p>Receipt Confirmation</p>
            </div>
            
            <div class='content'>
                <p>Dear {$member_name},</p>
                <p>Thank you for your payment. Please find your receipt details below:</p>
                
                <div class='receipt-details'>
                    <table class='receipt-table'>
                        <tr>
                            <th>Receipt Number</th>
                            <td>{$receipt['receipt_number']}</td>
                        </tr>
                        <tr>
                            <th>Date</th>
                            <td>" . date('F j, Y', strtotime($receipt['created_at'])) . "</td>
                        </tr>
                        <tr>
                            <th>Amount</th>
                            <td>₹" . number_format($receipt['amount'], 2) . "</td>
                        </tr>
                        <tr>
                            <th>Payment Method</th>
                            <td>" . ucfirst($receipt['payment_method'] ?? 'Cash') . "</td>
                        </tr>
                        <tr>
                            <th>Transaction Type</th>
                            <td>" . ucfirst(str_replace('_', ' ', $receipt['transaction_type'])) . "</td>
                        </tr>
                    </table>
                </div>
                
                <p>This receipt has been generated electronically and is valid without signature.</p>
                
                <p>If you have any questions about this receipt, please contact us at:</p>
                <ul>
                    <li>Email: info@kso-chd.online</li>
                    <li>Phone: +91-XXXXX-XXXXX</li>
                </ul>
            </div>
            
            <div class='footer'>
                <p>This is an automated message from KSO Chandigarh Management System.</p>
                <p>Please do not reply to this email. For queries, contact us at info@kso-chd.online</p>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Generate invoice email body
     */
    private function generateInvoiceEmailBody($invoice, $member_name) {
        // Calculate days until due
        $due_date = new DateTime($invoice['due_date']);
        $today = new DateTime();
        $interval = $today->diff($due_date);
        $days_to_due = $interval->days;
        $overdue = $today > $due_date;
        
        $due_status = $overdue ? 
            "<span style='color: red; font-weight: bold;'>OVERDUE by {$days_to_due} days</span>" : 
            "<span style='color: green;'>Due in {$days_to_due} days</span>";
        
        return "
        <html>
        <head>
            <style>
                body { font-family: Arial, sans-serif; color: #333; }
                .header { background-color: #006496; color: white; padding: 20px; text-align: center; }
                .content { padding: 20px; }
                .invoice-details { background-color: #f9f9f9; padding: 15px; margin: 20px 0; border-radius: 5px; }
                .invoice-table { width: 100%; border-collapse: collapse; margin: 20px 0; }
                .invoice-table th, .invoice-table td { border: 1px solid #ddd; padding: 8px; text-align: left; }
                .invoice-table th { background-color: #006496; color: white; }
                .payment-info { background-color: #e8f4f8; padding: 15px; margin: 20px 0; border-radius: 5px; }
                .footer { background-color: #f5f5f5; padding: 15px; text-align: center; font-size: 12px; color: #666; }
            </style>
        </head>
        <body>
            <div class='header'>
                <h1>KSO Chandigarh</h1>
                <p>Invoice #{$invoice['invoice_number']}</p>
            </div>
            
            <div class='content'>
                <p>Dear {$member_name},</p>
                <p>Please find your invoice details below. {$due_status}</p>
                
                <div class='invoice-details'>
                    <table class='invoice-table'>
                        <tr>
                            <th>Invoice Number</th>
                            <td>{$invoice['invoice_number']}</td>
                        </tr>
                        <tr>
                            <th>Invoice Date</th>
                            <td>" . date('F j, Y', strtotime($invoice['created_at'])) . "</td>
                        </tr>
                        <tr>
                            <th>Due Date</th>
                            <td>" . date('F j, Y', strtotime($invoice['due_date'])) . "</td>
                        </tr>
                        <tr>
                            <th>Total Amount</th>
                            <td><strong>₹" . number_format($invoice['total_amount'], 2) . "</strong></td>
                        </tr>
                        <tr>
                            <th>Status</th>
                            <td style='color: " . ($invoice['status'] === 'paid' ? 'green' : 'red') . ";'>
                                <strong>" . ucfirst($invoice['status']) . "</strong>
                            </td>
                        </tr>
                    </table>
                </div>
                
                <div class='payment-info'>
                    <h3>Payment Instructions:</h3>
                    <ul>
                        <li><strong>Online Payment:</strong> Log in to your member portal for secure online payment</li>
                        <li><strong>Bank Transfer:</strong> Contact administration for bank details</li>
                        <li><strong>Cash/Check:</strong> Visit our office during business hours</li>
                        <li><strong>UPI/Digital Payment:</strong> Contact us for UPI details</li>
                    </ul>
                </div>
                
                <p>Please reference invoice number <strong>{$invoice['invoice_number']}</strong> when making payment.</p>
                
                <p>If you have any questions about this invoice, please contact us at:</p>
                <ul>
                    <li>Email: info@kso-chd.online</li>
                    <li>Phone: +91-XXXXX-XXXXX</li>
                </ul>
            </div>
            
            <div class='footer'>
                <p>This is an automated message from KSO Chandigarh Management System.</p>
                <p>Please do not reply to this email. For queries, contact us at info@kso-chd.online</p>
            </div>
        </body>
        </html>";
    }
    
    /**
     * Test email configuration
     */
    public function testEmailConfig() {
        $test_body = "
        <html>
        <body>
            <h2>KSO Email Configuration Test</h2>
            <p>This is a test email to verify the email configuration.</p>
            <p>If you receive this email, the configuration is working correctly.</p>
            <p>Server: {$this->config['smtp_host']}</p>
            <p>Port: {$this->config['smtp_port']}</p>
            <p>From: {$this->config['from_email']}</p>
            <p>Time: " . date('Y-m-d H:i:s') . "</p>
        </body>
        </html>";
        
        return $this->sendEmailWithAttachment(
            'test@kso-chd.online',
            'KSO Email Test',
            $test_body
        );
    }
}

// Global email helper function
function sendKSOEmail($to, $subject, $body, $attachment_path = null, $attachment_name = null) {
    global $email_config;
    
    $emailer = new KSOEmailer($email_config);
    return $emailer->sendEmailWithAttachment($to, $subject, $body, $attachment_path, $attachment_name);
}

// Helper function for receipt emails
function sendReceiptEmailHelper($receipt_data, $pdf_path = null) {
    global $email_config;
    
    $emailer = new KSOEmailer($email_config);
    return $emailer->sendReceiptEmail($receipt_data, $pdf_path);
}

// Helper function for invoice emails
function sendInvoiceEmailHelper($invoice_data, $pdf_path = null) {
    global $email_config;
    
    $emailer = new KSOEmailer($email_config);
    return $emailer->sendInvoiceEmail($invoice_data, $pdf_path);
}
?>
