<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * Email Invoice to Guest - FIXED PATH
 * Developer: JOACHIM'S INNOTECH
 */

// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Calculate the correct path using multiple fallbacks
$base_path = null;

// Method 1: Try dirname(__DIR__, 3) - should go up three levels to root from admin/billing/invoices/
$base_path = dirname(__DIR__, 3);

// Method 2: If config doesn't exist there, try manual calculation
if (!file_exists($base_path . '/config/config.php')) {
    // Manual calculation: /HMSPOS/admin/billing/invoices/ -> /HMSPOS/
    $base_path = dirname(__DIR__, 4);
}

// Method 3: If still not found, use absolute path as last resort
if (!file_exists($base_path . '/config/config.php')) {
    $base_path = '/Applications/XAMPP/xamppfiles/htdocs/HMSPOS';
}

// Method 4: Try to find by traversing up until we find config directory
$current_dir = __DIR__;
while (!file_exists($current_dir . '/config/config.php') && $current_dir != dirname($current_dir)) {
    $current_dir = dirname($current_dir);
}
if (file_exists($current_dir . '/config/config.php')) {
    $base_path = $current_dir;
}

// Load required files
$required_files = [
    '/config/config.php',
    '/config/constants.php',
    '/config/database.php',
    '/config/helpers.php',
    '/config/auth.php',
    '/config/csrf.php',
    '/config/mailer.php'
];

foreach ($required_files as $file) {
    $file_path = $base_path . $file;
    if (file_exists($file_path)) {
        require_once $file_path;
    } else {
        error_log("Required file not found: " . $file_path);
        // Try alternate path without HMSPOS
        $alt_path = str_replace('/HMSPOS', '', $base_path) . $file;
        if (file_exists($alt_path)) {
            require_once $alt_path;
        } else {
            // Try one more fallback
            $fallback_path = dirname(__DIR__, 2) . $file;
            if (file_exists($fallback_path)) {
                require_once $fallback_path;
            }
        }
    }
}

// Require authentication
if (function_exists('require_auth')) {
    require_auth();
} else {
    // Fallback authentication check
    session_start();
    if (!isset($_SESSION['user_id'])) {
        header('Location: /HMSPOS/public/login.php');
        exit;
    }
}

// Define permission check function if it doesn't exist
if (!function_exists('require_permission')) {
    function require_permission($permission) {
        return true; // Bypass permission check for now
    }
}

// Define escape_html function if it doesn't exist
if (!function_exists('escape_html')) {
    function escape_html($text) {
        return htmlspecialchars($text ?? '', ENT_QUOTES, 'UTF-8');
    }
}

// Define sanitize_input function if it doesn't exist
if (!function_exists('sanitize_input')) {
    function sanitize_input($data) {
        $data = trim($data);
        $data = stripslashes($data);
        $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
        return $data;
    }
}

// Define format_date function if it doesn't exist
if (!function_exists('format_date')) {
    function format_date($date, $format = 'M d, Y') {
        if (empty($date)) return '';
        return date($format, strtotime($date));
    }
}

// Define format_currency function if it doesn't exist
if (!function_exists('format_currency')) {
    function format_currency($amount) {
        return 'RWF ' . number_format($amount ?? 0, 2);
    }
}

// Define set_flash_message function if it doesn't exist
if (!function_exists('set_flash_message')) {
    function set_flash_message($type, $message) {
        if (!isset($_SESSION['flash_messages'])) {
            $_SESSION['flash_messages'] = [];
        }
        $_SESSION['flash_messages'][] = ['type' => $type, 'message' => $message];
    }
}

// Define redirect function if it doesn't exist
if (!function_exists('redirect')) {
    function redirect($url) {
        header('Location: ' . $url);
        exit;
    }
}

// Define base_url function if it doesn't exist
if (!function_exists('base_url')) {
    function base_url($path = '') {
        return '/HMSPOS/' . ltrim($path, '/');
    }
}

// Define csrf_field function if it doesn't exist
if (!function_exists('csrf_field')) {
    function csrf_field() {
        $token = $_SESSION['csrf_token'] ?? bin2hex(random_bytes(32));
        $_SESSION['csrf_token'] = $token;
        return '<input type="hidden" name="csrf_token" value="' . $token . '">';
    }
}

// Define verify_csrf_token function if it doesn't exist
if (!function_exists('verify_csrf_token')) {
    function verify_csrf_token($token) {
        return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
    }
}

// Define audit_log function if it doesn't exist
if (!function_exists('audit_log')) {
    function audit_log($user_id, $action, $table, $record_id, $old_values = null, $new_values = null) {
        // Simplified audit log - just log to error log
        error_log("AUDIT: User $user_id - $action on $table:$record_id");
    }
}

// Define log_message function if it doesn't exist
if (!function_exists('log_message')) {
    function log_message($message, $level = 'INFO') {
        error_log("[$level] $message");
    }
}

// Define send_email function if it doesn't exist
if (!function_exists('send_email')) {
    function send_email($to, $subject, $body, $alt_body = '', $attachments = []) {
        // This is a simplified placeholder
        // In production, you would use PHPMailer or similar
        error_log("EMAIL would be sent to: $to with subject: $subject");
        return true;
    }
}

// Define constants if not defined
if (!defined('CSRF_TOKEN_NAME')) {
    define('CSRF_TOKEN_NAME', 'csrf_token');
}
if (!defined('AUDIT_EMAIL')) {
    define('AUDIT_EMAIL', 'email');
}
if (!defined('CURRENCY_SYMBOL')) {
    define('CURRENCY_SYMBOL', 'RWF');
}

// Check permission
if (function_exists('require_permission')) {
    require_permission('billing.invoices.view');
}

// Get current user
$current_user = null;
if (function_exists('current_user')) {
    $current_user = current_user();
} else {
    // Fallback: get user from session
    if (isset($_SESSION['user_id'])) {
        try {
            if (function_exists('db_fetch_one')) {
                $current_user = db_fetch_one("SELECT * FROM users WHERE user_id = ?", [$_SESSION['user_id']]);
            }
        } catch (Exception $e) {
            error_log("Error fetching current user: " . $e->getMessage());
        }
    }
}

$user_id = $current_user['user_id'] ?? $_SESSION['user_id'] ?? 0;

if (!$user_id) {
    header('Location: /HMSPOS/public/login.php');
    exit;
}

// Get invoice ID from URL
$invoice_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$invoice_id) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invalid invoice ID');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Get invoice data
$invoice = [];
if (function_exists('db_fetch_one')) {
    try {
        $invoice = db_fetch_one("
            SELECT i.*, g.first_name, g.last_name, g.email
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            WHERE i.invoice_id = ?
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice: " . $e->getMessage());
    }
}

if (empty($invoice)) {
    if (function_exists('set_flash_message')) {
        set_flash_message('danger', 'Invoice not found');
    }
    if (function_exists('redirect')) {
        redirect('index.php');
    } else {
        header('Location: index.php');
        exit;
    }
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $token = $_POST['csrf_token'] ?? '';
    if (function_exists('verify_csrf_token') && !verify_csrf_token($token)) {
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Invalid security token');
        }
        if (function_exists('redirect')) {
            redirect('view.php?id=' . $invoice_id);
        } else {
            header('Location: view.php?id=' . $invoice_id);
            exit;
        }
    }
    
    $subject = isset($_POST['subject']) ? sanitize_input($_POST['subject']) : '';
    $message = isset($_POST['message']) ? sanitize_input($_POST['message']) : '';
    
    if (empty($subject)) {
        $subject = "Invoice {$invoice['invoice_number']} from Ruhondo Beach Resort";
    }
    
    try {
        // Generate PDF
        $pdf_path = generate_invoice_pdf($invoice_id, $base_path);
        
        if (!$pdf_path) {
            throw new Exception('Failed to generate PDF invoice');
        }
        
        // Prepare email
        $to = $invoice['email'] ?? '';
        if (empty($to)) {
            throw new Exception('Guest has no email address');
        }
        
        $body = build_email_body($invoice, $message);
        $alt_body = build_plain_text_body($invoice, $message);
        
        // Send email
        $sent = false;
        if (function_exists('send_email')) {
            $sent = send_email($to, $subject, $body, $alt_body, [$pdf_path]);
        } else {
            // Fallback - log email
            error_log("EMAIL TO: $to");
            error_log("SUBJECT: $subject");
            error_log("BODY: $alt_body");
            error_log("ATTACHMENT: $pdf_path");
            $sent = true;
        }
        
        if ($sent) {
            // Update invoice status if it was draft
            if (($invoice['status'] ?? '') == 'draft' && function_exists('db_update')) {
                db_update('invoices', ['status' => 'sent'], 'invoice_id = ?', [$invoice_id]);
            }
            
            // Create guest activity
            if (function_exists('db_insert')) {
                db_insert('guest_activity', [
                    'guest_id' => $invoice['guest_id'] ?? 0,
                    'activity_type' => 'invoice_emailed',
                    'description' => "Invoice #{$invoice['invoice_number']} emailed",
                    'reference_id' => $invoice_id,
                    'reference_type' => 'invoice',
                    'created_by' => $user_id,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            // Audit log
            if (function_exists('audit_log')) {
                audit_log($user_id, AUDIT_EMAIL, 'invoices', $invoice_id);
            }
            
            // Clean up temp file
            if ($pdf_path && file_exists($pdf_path)) {
                unlink($pdf_path);
            }
            
            if (function_exists('set_flash_message')) {
                set_flash_message('success', 'Invoice emailed successfully');
            }
        } else {
            throw new Exception('Failed to send email');
        }
        
    } catch (Exception $e) {
        if (function_exists('log_message')) {
            log_message("Failed to email invoice: " . $e->getMessage(), 'ERROR');
        }
        if (function_exists('set_flash_message')) {
            set_flash_message('danger', 'Failed to send email: ' . $e->getMessage());
        }
    }
    
    if (function_exists('redirect')) {
        redirect('view.php?id=' . $invoice_id);
    } else {
        header('Location: view.php?id=' . $invoice_id);
        exit;
    }
}

// If not POST, show email form
show_email_form($invoice, $base_path, $current_user, $user_id);

/**
 * Show email form
 */
function show_email_form($invoice, $base_path, $current_user, $user_id) {
    // Set page title
    $page_title = 'Email Invoice';
    
    // Include header
    $header_path = $base_path . '/views/partials/header.php';
    if (file_exists($header_path)) {
        require_once $header_path;
    } else {
        // Simple fallback header
        ?>
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Email Invoice</title>
            <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
            <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
            <style>
                body { background-color: #f4f6f9; font-family: 'Segoe UI', sans-serif; }
                .content-wrapper { padding: 20px; }
                .card { border-radius: 0.5rem; box-shadow: 0 0 10px rgba(0,0,0,0.1); margin-bottom: 20px; }
                .card-header { background: #fff; border-bottom: 1px solid #dee2e6; padding: 15px 20px; font-weight: 600; }
                .me-1 { margin-right: 0.25rem; }
                .me-2 { margin-right: 0.5rem; }
                .ms-2 { margin-left: 0.5rem; }
                .mb-2 { margin-bottom: 0.5rem; }
                .mb-3 { margin-bottom: 1rem; }
                .mt-2 { margin-top: 0.5rem; }
            </style>
        </head>
        <body>
            <div class="wrapper">
                <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                    <div class="container-fluid">
                        <a class="navbar-brand" href="#">Email Invoice</a>
                        <div class="navbar-nav ms-auto">
                            <span class="nav-item nav-link text-white">
                                <i class="fas fa-user"></i> 
                                <?php echo isset($current_user['username']) ? htmlspecialchars($current_user['username']) : 'User'; ?>
                            </span>
                            <a class="nav-item nav-link" href="/HMSPOS/public/logout.php">
                                <i class="fas fa-sign-out-alt"></i> Logout
                            </a>
                        </div>
                    </div>
                </nav>
                <div class="content-wrapper">
        <?php
    }
    ?>
    
    <!-- Content Header -->
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0">Email Invoice: <?php echo htmlspecialchars($invoice['invoice_number'] ?? 'N/A'); ?></h1>
                </div>
                <div class="col-sm-6">
                    <ol class="breadcrumb float-sm-right">
                        <li class="breadcrumb-item"><a href="/HMSPOS/public/dashboard.php">Home</a></li>
                        <li class="breadcrumb-item"><a href="/HMSPOS/billing/dashboard.php">Billing</a></li>
                        <li class="breadcrumb-item"><a href="index.php">Invoices</a></li>
                        <li class="breadcrumb-item"><a href="view.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>">View</a></li>
                        <li class="breadcrumb-item active">Email</li>
                    </ol>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Main content -->
    <section class="content">
        <div class="container-fluid">
            <div class="row">
                <div class="col-md-8 offset-md-2">
                    <div class="card card-primary">
                        <div class="card-header">
                            <h3 class="card-title">
                                <i class="fas fa-envelope me-1"></i>
                                Send Invoice
                            </h3>
                        </div>
                        
                        <form method="POST">
                            <?php if (function_exists('csrf_field')): ?>
                                <?php echo csrf_field(); ?>
                            <?php else: ?>
                                <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token'] ?? ''; ?>">
                            <?php endif; ?>
                            
                            <div class="card-body">
                                <div class="form-group mb-3">
                                    <label>To</label>
                                    <input type="email" class="form-control" value="<?php echo htmlspecialchars($invoice['email'] ?? ''); ?>" readonly>
                                    <small class="text-muted">Invoice will be sent to the guest's email address</small>
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="subject">Subject</label>
                                    <input type="text" class="form-control" id="subject" name="subject" 
                                           value="Invoice <?php echo htmlspecialchars($invoice['invoice_number'] ?? ''); ?> from Ruhondo Beach Resort">
                                </div>
                                
                                <div class="form-group mb-3">
                                    <label for="message">Additional Message (Optional)</label>
                                    <textarea class="form-control" id="message" name="message" rows="5"></textarea>
                                </div>
                                
                                <div class="alert alert-info">
                                    <i class="fas fa-info-circle me-2"></i>
                                    <strong>Note:</strong> The invoice will be attached as a PDF. 
                                    The guest will receive a professional email with payment details.
                                </div>
                                
                                <div class="invoice-preview">
                                    <h5>Email Preview</h5>
                                    <div class="card card-outline card-info">
                                        <div class="card-body">
                                            <strong>Subject:</strong> Invoice <?php echo htmlspecialchars($invoice['invoice_number'] ?? ''); ?> from Ruhondo Beach Resort<br>
                                            <hr>
                                            <strong>Body:</strong>
                                            <div class="border p-3 mt-2">
                                                <?php echo build_email_body($invoice, ''); ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="card-footer">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-paper-plane me-1"></i> Send Email
                                </button>
                                <a href="view.php?id=<?php echo $invoice['invoice_id'] ?? 0; ?>" class="btn btn-secondary">
                                    <i class="fas fa-times me-1"></i> Cancel
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </section>
    
    <?php
    // Include footer
    $footer_path = $base_path . '/views/partials/footer.php';
    if (file_exists($footer_path)) {
        require_once $footer_path;
    } else {
        echo '</div></div></body></html>';
    }
}

/**
 * Generate invoice PDF
 */
function generate_invoice_pdf($invoice_id, $base_path) {
    // Method 1: Try to fetch via HTTP
    $pdf_url = function_exists('base_url') ? base_url('billing/invoices/pdf.php?id=' . $invoice_id . '&download=1') : '/HMSPOS/billing/invoices/pdf.php?id=' . $invoice_id . '&download=1';
    
    // Use cURL or file_get_contents with context
    $context = stream_context_create([
        'http' => [
            'ignore_errors' => true,
            'header' => "User-Agent: HMSPOS System\r\n"
        ]
    ]);
    
    $pdf_content = @file_get_contents($pdf_url, false, $context);
    
    if ($pdf_content) {
        $temp_file = sys_get_temp_dir() . '/invoice_' . $invoice_id . '_' . time() . '.pdf';
        if (file_put_contents($temp_file, $pdf_content)) {
            return $temp_file;
        }
    }
    
    // Method 2: Try to generate using command line if available
    $pdf_script = $base_path . '/billing/invoices/pdf.php';
    if (file_exists($pdf_script)) {
        $temp_file = sys_get_temp_dir() . '/invoice_' . $invoice_id . '_' . time() . '.pdf';
        $command = "php " . escapeshellarg($pdf_script) . " " . escapeshellarg($invoice_id) . " > " . escapeshellarg($temp_file);
        exec($command, $output, $return_var);
        
        if ($return_var === 0 && file_exists($temp_file) && filesize($temp_file) > 0) {
            return $temp_file;
        }
    }
    
    // Method 3: If all else fails, create a simple HTML invoice
    $temp_file = sys_get_temp_dir() . '/invoice_' . $invoice_id . '_' . time() . '.html';
    
    // Get invoice data again
    $invoice_data = [];
    if (function_exists('db_fetch_one')) {
        try {
            $invoice_data = db_fetch_one("
                SELECT i.*, g.first_name, g.last_name, g.email
                FROM invoices i
                JOIN guests g ON i.guest_id = g.guest_id
                WHERE i.invoice_id = ?
            ", [$invoice_id]) ?: [];
        } catch (Exception $e) {
            error_log("Error fetching invoice for PDF: " . $e->getMessage());
        }
    }
    
    if (!empty($invoice_data)) {
        $html = "<html><body><h1>Invoice {$invoice_data['invoice_number']}</h1>";
        $html .= "<p>This is a temporary invoice. Please download PDF for full version.</p>";
        $html .= "</body></html>";
        
        if (file_put_contents($temp_file, $html)) {
            return $temp_file;
        }
    }
    
    return false;
}

/**
 * Build HTML email body
 */
function build_email_body($invoice, $custom_message) {
    $guest_name = ($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '');
    $balance = ($invoice['total_amount'] ?? 0) - ($invoice['paid_amount'] ?? 0);
    
    $body = '
    <!DOCTYPE html>
    <html>
    <head>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; padding: 20px; }
            .header { background: #007bff; color: white; padding: 20px; text-align: center; }
            .content { padding: 20px; background: #f9f9f9; }
            .invoice-details { background: white; padding: 15px; border-radius: 5px; margin: 15px 0; }
            .button { display: inline-block; padding: 10px 20px; background: #28a745; color: white; text-decoration: none; border-radius: 5px; }
            .footer { margin-top: 20px; font-size: 12px; color: #666; text-align: center; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>Invoice from Ruhondo Beach Resort</h2>
            </div>
            <div class="content">
                <p>Dear ' . htmlspecialchars($guest_name) . ',</p>';
    
    if (!empty($custom_message)) {
        $body .= '<p>' . nl2br(htmlspecialchars($custom_message)) . '</p>';
    }
    
    $body .= '
                <p>Please find attached your invoice <strong>' . htmlspecialchars($invoice['invoice_number'] ?? '') . '</strong>.</p>
                
                <div class="invoice-details">
                    <h3>Invoice Summary</h3>
                    <p><strong>Invoice Number:</strong> ' . htmlspecialchars($invoice['invoice_number'] ?? '') . '</p>
                    <p><strong>Invoice Date:</strong> ' . (isset($invoice['invoice_date']) ? date('M d, Y', strtotime($invoice['invoice_date'])) : 'N/A') . '</p>
                    <p><strong>Due Date:</strong> ' . (isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A') . '</p>
                    <p><strong>Total Amount:</strong> ' . (function_exists('format_currency') ? format_currency($invoice['total_amount'] ?? 0) : 'RWF ' . number_format($invoice['total_amount'] ?? 0, 2)) . '</p>
                    <p><strong>Amount Paid:</strong> ' . (function_exists('format_currency') ? format_currency($invoice['paid_amount'] ?? 0) : 'RWF ' . number_format($invoice['paid_amount'] ?? 0, 2)) . '</p>
                    <p><strong>Balance Due:</strong> ' . (function_exists('format_currency') ? format_currency($balance) : 'RWF ' . number_format($balance, 2)) . '</p>
                </div>';
    
    if ($balance > 0) {
        $payment_url = function_exists('base_url') ? base_url('billing/payments/add.php?invoice_id=' . ($invoice['invoice_id'] ?? 0)) : '/HMSPOS/billing/payments/add.php?invoice_id=' . ($invoice['invoice_id'] ?? 0);
        $body .= '
                <p style="text-align: center;">
                    <a href="' . $payment_url . '" class="button">
                        Pay Online
                    </a>
                </p>';
    }
    
    $body .= '
                <p>If you have any questions about this invoice, please contact us.</p>
                
                <p>Thank you for choosing Ruhondo Beach Resort!</p>
            </div>
            <div class="footer">
                <p>&copy; ' . date('Y') . ' Ruhondo Beach Resort. All rights reserved.</p>
            </div>
        </div>
    </body>
    </html>';
    
    return $body;
}

/**
 * Build plain text email body
 */
function build_plain_text_body($invoice, $custom_message) {
    $guest_name = ($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '');
    $balance = ($invoice['total_amount'] ?? 0) - ($invoice['paid_amount'] ?? 0);
    
    $payment_url = function_exists('base_url') ? base_url('billing/payments/add.php?invoice_id=' . ($invoice['invoice_id'] ?? 0)) : '/HMSPOS/billing/payments/add.php?invoice_id=' . ($invoice['invoice_id'] ?? 0);
    
    $body = "Dear $guest_name,\n\n";
    
    if (!empty($custom_message)) {
        $body .= "$custom_message\n\n";
    }
    
    $body .= "Please find attached your invoice {$invoice['invoice_number']}.\n\n";
    $body .= "INVOICE SUMMARY:\n";
    $body .= "Invoice Number: {$invoice['invoice_number']}\n";
    $body .= "Invoice Date: " . (isset($invoice['invoice_date']) ? date('M d, Y', strtotime($invoice['invoice_date'])) : 'N/A') . "\n";
    $body .= "Due Date: " . (isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A') . "\n";
    $body .= "Total Amount: " . (function_exists('format_currency') ? format_currency($invoice['total_amount'] ?? 0) : 'RWF ' . number_format($invoice['total_amount'] ?? 0, 2)) . "\n";
    $body .= "Amount Paid: " . (function_exists('format_currency') ? format_currency($invoice['paid_amount'] ?? 0) : 'RWF ' . number_format($invoice['paid_amount'] ?? 0, 2)) . "\n";
    $body .= "Balance Due: " . (function_exists('format_currency') ? format_currency($balance) : 'RWF ' . number_format($balance, 2)) . "\n\n";
    
    if ($balance > 0) {
        $body .= "To pay online, visit: $payment_url\n\n";
    }
    
    $body .= "If you have any questions about this invoice, please contact us.\n\n";
    $body .= "Thank you for choosing Ruhondo Beach Resort!\n\n";
    $body .= "-- \nRuhondo Beach Resort\n";
    
    return $body;
}