<?php
/**
 * RUHONDO BEACH RESORT HMS + POS System
 * View Invoice Details - 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'
];

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 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_datetime function if it doesn't exist
if (!function_exists('format_datetime')) {
    function format_datetime($datetime, $format = 'M d, Y H:i') {
        if (empty($datetime)) return '';
        return date($format, strtotime($datetime));
    }
}

// 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 constants if not defined
if (!defined('INVOICE_STATUSES')) {
    $statuses = [
        'draft' => 'Draft',
        'sent' => 'Sent',
        'partial' => 'Partially Paid',
        'paid' => 'Paid',
        'overdue' => 'Overdue',
        'cancelled' => 'Cancelled'
    ];
    define('INVOICE_STATUSES', serialize($statuses));
}

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

// Set page title
$page_title = 'Invoice Details';

// 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 with details
$invoice = [];
if (function_exists('db_fetch_one')) {
    try {
        $invoice = db_fetch_one("
            SELECT 
                i.*,
                g.guest_id, g.first_name, g.last_name, g.email, g.phone,
                g.address, g.city, g.country,
                r.booking_code, r.check_in_date, r.check_out_date,
                u.first_name as created_by_first, u.last_name as created_by_last
            FROM invoices i
            JOIN guests g ON i.guest_id = g.guest_id
            LEFT JOIN reservations r ON i.reservation_id = r.reservation_id
            LEFT JOIN users u ON i.created_by = u.user_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;
    }
}

// Get invoice items
$items = [];
if (function_exists('db_fetch_all')) {
    try {
        $items = db_fetch_all("
            SELECT * FROM invoice_items 
            WHERE invoice_id = ?
            ORDER BY item_id
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching invoice items: " . $e->getMessage());
    }
}

// Get payments for this invoice
$payments = [];
if (function_exists('db_fetch_all')) {
    try {
        $payments = db_fetch_all("
            SELECT p.*, pm.method_name
            FROM payments p
            JOIN payment_methods pm ON p.payment_method_id = pm.payment_method_id
            WHERE p.invoice_id = ?
            ORDER BY p.payment_date DESC
        ", [$invoice_id]) ?: [];
    } catch (Exception $e) {
        error_log("Error fetching payments: " . $e->getMessage());
    }
}

// Calculate totals
$total_paid = 0;
foreach ($payments as $payment) {
    if (($payment['status'] ?? '') == 'completed') {
        $total_paid += $payment['amount'] ?? 0;
    }
}
$balance = ($invoice['total_amount'] ?? 0) - $total_paid;

// Check if overdue
$today = new DateTime();
$due_date = new DateTime($invoice['due_date'] ?? date('Y-m-d'));
$days_overdue = $today > $due_date ? $today->diff($due_date)->days : 0;

// Get statuses
$statuses = [];
if (defined('INVOICE_STATUSES')) {
    $statuses = @unserialize(INVOICE_STATUSES) ?: [];
}
if (empty($statuses)) {
    $statuses = [
        'draft' => 'Draft',
        'sent' => 'Sent',
        'partial' => 'Partially Paid',
        'paid' => 'Paid',
        'overdue' => 'Overdue',
        'cancelled' => 'Cancelled'
    ];
}

// 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>Invoice Details</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; }
            .badge-lg { font-size: 1rem; padding: 0.5rem 1rem; }
            .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; }
            .mt-3 { margin-top: 1rem; }
            .text-end { text-align: right; }
        </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="#">Invoice Details</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">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 active">View</li>
                </ol>
            </div>
        </div>
    </div>
</div>

<!-- Main content -->
<section class="content">
    <div class="container-fluid">
        <!-- Action Buttons -->
        <div class="row mb-3">
            <div class="col-12">
                <div class="btn-group">
                    <a href="index.php" class="btn btn-secondary">
                        <i class="fas fa-arrow-left me-1"></i> Back to List
                    </a>
                    
                    <a href="pdf.php?id=<?php echo $invoice_id; ?>" class="btn btn-info" target="_blank">
                        <i class="fas fa-file-pdf"></i> Download PDF
                    </a>
                    
                    <a href="email.php?id=<?php echo $invoice_id; ?>" class="btn btn-primary">
                        <i class="fas fa-envelope"></i> Email Invoice
                    </a>
                    
                    <?php if ($balance > 0): ?>
                        <a href="../payments/add.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-success">
                            <i class="fas fa-dollar-sign"></i> Record Payment
                        </a>
                    <?php endif; ?>
                    
                    <?php if (($invoice['status'] ?? '') == 'draft'): ?>
                        <button type="button" class="btn btn-warning" onclick="sendInvoice()">
                            <i class="fas fa-paper-plane"></i> Send to Guest
                        </button>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Status Alert -->
        <?php if (($invoice['status'] ?? '') == 'overdue'): ?>
            <div class="alert alert-danger">
                <i class="fas fa-exclamation-triangle me-2"></i>
                <strong>Invoice Overdue!</strong> This invoice is <?php echo $days_overdue; ?> days overdue.
                <a href="../payments/add.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-sm btn-danger ms-2">
                    Record Payment Now
                </a>
            </div>
        <?php elseif (($invoice['status'] ?? '') == 'paid'): ?>
            <div class="alert alert-success">
                <i class="fas fa-check-circle me-2"></i>
                <strong>Invoice Paid</strong> - This invoice has been paid in full.
            </div>
        <?php elseif (($invoice['status'] ?? '') == 'partial'): ?>
            <div class="alert alert-warning">
                <i class="fas fa-exclamation-circle me-2"></i>
                <strong>Partial Payment</strong> - Balance due: <?php echo format_currency($balance); ?>
                <a href="../payments/add.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-sm btn-warning ms-2">
                    Record Additional Payment
                </a>
            </div>
        <?php endif; ?>

        <div class="row">
            <!-- Invoice Information -->
            <div class="col-md-4">
                <div class="card card-primary card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-info-circle me-1"></i>
                            Invoice Information
                        </h3>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 120px;">Invoice #:</th>
                                <td><strong><?php echo htmlspecialchars($invoice['invoice_number'] ?? 'N/A'); ?></strong></td>
                            </tr>
                            <tr>
                                <th>Status:</th>
                                <td>
                                    <span class="badge bg-<?php 
                                        $status = $invoice['status'] ?? 'draft';
                                        echo $status == 'paid' ? 'success' : 
                                            ($status == 'partial' ? 'warning' : 
                                            ($status == 'overdue' ? 'danger' : 
                                            ($status == 'sent' ? 'info' : 'secondary')));
                                    ?> badge-lg">
                                        <?php 
                                        echo $statuses[$status] ?? ucfirst($status);
                                        ?>
                                    </span>
                                </td>
                            </tr>
                            <tr>
                                <th>Invoice Date:</th>
                                <td><?php echo isset($invoice['invoice_date']) ? date('M d, Y', strtotime($invoice['invoice_date'])) : 'N/A'; ?></td>
                            </tr>
                            <tr>
                                <th>Due Date:</th>
                                <td>
                                    <?php echo isset($invoice['due_date']) ? date('M d, Y', strtotime($invoice['due_date'])) : 'N/A'; ?>
                                    <?php if (($invoice['status'] ?? '') != 'paid' && $today > $due_date): ?>
                                        <br>
                                        <span class="badge bg-danger"><?php echo $days_overdue; ?> days overdue</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Created By:</th>
                                <td>
                                    <?php echo htmlspecialchars(($invoice['created_by_first'] ?? '') . ' ' . ($invoice['created_by_last'] ?? '')); ?>
                                    <br>
                                    <small class="text-muted"><?php echo isset($invoice['created_at']) ? date('M d, Y H:i', strtotime($invoice['created_at'])) : 'N/A'; ?></small>
                                </td>
                            </tr>
                            <?php if (!empty($invoice['booking_code'])): ?>
                            <tr>
                                <th>Booking:</th>
                                <td>
                                    <a href="/HMSPOS/reservations/view.php?code=<?php echo urlencode($invoice['booking_code']); ?>">
                                        <?php echo htmlspecialchars($invoice['booking_code']); ?>
                                    </a>
                                </td>
                            </tr>
                            <?php endif; ?>
                        </table>
                        
                        <?php if (!empty($invoice['notes'])): ?>
                            <hr>
                            <h6>Notes:</h6>
                            <p class="text-muted"><?php echo nl2br(escape_html($invoice['notes'])); ?></p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Guest Information -->
                <div class="card card-success card-outline">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-user me-1"></i>
                            Guest Information
                        </h3>
                        <div class="card-tools">
                            <a href="/HMSPOS/guests/view.php?id=<?php echo $invoice['guest_id'] ?? 0; ?>" class="btn btn-sm btn-success">
                                View Profile
                            </a>
                        </div>
                    </div>
                    <div class="card-body">
                        <table class="table table-sm">
                            <tr>
                                <th style="width: 100px;">Name:</th>
                                <td><?php echo escape_html(($invoice['first_name'] ?? '') . ' ' . ($invoice['last_name'] ?? '')); ?></td>
                            </tr>
                            <tr>
                                <th>Email:</th>
                                <td>
                                    <?php if (!empty($invoice['email'])): ?>
                                        <a href="mailto:<?php echo htmlspecialchars($invoice['email']); ?>"><?php echo htmlspecialchars($invoice['email']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Phone:</th>
                                <td>
                                    <?php if (!empty($invoice['phone'])): ?>
                                        <a href="tel:<?php echo htmlspecialchars($invoice['phone']); ?>"><?php echo htmlspecialchars($invoice['phone']); ?></a>
                                    <?php else: ?>
                                        <span class="text-muted">Not provided</span>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <tr>
                                <th>Address:</th>
                                <td>
                                    <?php 
                                    $address = array_filter([
                                        $invoice['address'] ?? '',
                                        $invoice['city'] ?? '',
                                        $invoice['country'] ?? ''
                                    ]);
                                    echo $address ? implode('<br>', array_map('escape_html', $address)) : 'Not provided';
                                    ?>
                                </td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Invoice Items -->
            <div class="col-md-8">
                <div class="card">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-list me-1"></i>
                            Invoice Items
                        </h3>
                    </div>
                    
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>Description</th>
                                        <th class="text-center">Quantity</th>
                                        <th class="text-end">Unit Price</th>
                                        <th class="text-end">Total</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($items as $item): ?>
                                    <tr>
                                        <td><?php echo escape_html($item['description'] ?? ''); ?></td>
                                        <td class="text-center"><?php echo $item['quantity'] ?? 0; ?></td>
                                        <td class="text-end"><?php echo format_currency($item['unit_price'] ?? 0); ?></td>
                                        <td class="text-end"><?php echo format_currency($item['total_amount'] ?? 0); ?></td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <th colspan="3" class="text-end">Subtotal:</th>
                                        <th class="text-end"><?php echo format_currency($invoice['subtotal'] ?? 0); ?></th>
                                    </tr>
                                    <tr>
                                        <th colspan="3" class="text-end">Tax:</th>
                                        <th class="text-end"><?php echo format_currency($invoice['tax_amount'] ?? 0); ?></th>
                                    </tr>
                                    <tr class="table-active">
                                        <th colspan="3" class="text-end">Total:</th>
                                        <th class="text-end"><?php echo format_currency($invoice['total_amount'] ?? 0); ?></th>
                                    </tr>
                                    <tr>
                                        <th colspan="3" class="text-end">Paid:</th>
                                        <th class="text-end text-success">- <?php echo format_currency($total_paid); ?></th>
                                    </tr>
                                    <tr class="<?php echo $balance > 0 ? 'table-warning' : 'table-success'; ?>">
                                        <th colspan="3" class="text-end">Balance Due:</th>
                                        <th class="text-end">
                                            <strong><?php echo format_currency($balance); ?></strong>
                                        </th>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- Payment History -->
                <div class="card mt-3">
                    <div class="card-header">
                        <h3 class="card-title">
                            <i class="fas fa-history me-1"></i>
                            Payment History
                        </h3>
                        <?php if ($balance > 0): ?>
                        <div class="card-tools">
                            <a href="../payments/add.php?invoice_id=<?php echo $invoice_id; ?>" class="btn btn-sm btn-success">
                                <i class="fas fa-plus"></i> Add Payment
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="card-body p-0">
                        <?php if (empty($payments)): ?>
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-dollar-sign fa-3x mb-3"></i>
                                <p>No payments recorded yet</p>
                            </div>
                        <?php else: ?>
                            <div class="table-responsive">
                                <table class="table table-striped">
                                    <thead>
                                        <tr>
                                            <th>Date</th>
                                            <th>Payment #</th>
                                            <th>Method</th>
                                            <th class="text-end">Amount</th>
                                            <th>Reference</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($payments as $payment): ?>
                                        <tr>
                                            <td><?php echo isset($payment['payment_date']) ? date('M d, Y H:i', strtotime($payment['payment_date'])) : 'N/A'; ?></td>
                                            <td>
                                                <a href="../payments/view.php?id=<?php echo $payment['payment_id'] ?? 0; ?>">
                                                    <?php echo htmlspecialchars($payment['payment_number'] ?? ''); ?>
                                                </a>
                                            </td>
                                            <td><?php echo htmlspecialchars($payment['method_name'] ?? ''); ?></td>
                                            <td class="text-end"><?php echo format_currency($payment['amount'] ?? 0); ?></td>
                                            <td><?php echo htmlspecialchars($payment['reference_number'] ?? '-'); ?></td>
                                            <td>
                                                <span class="badge bg-<?php echo ($payment['status'] ?? '') == 'completed' ? 'success' : 'warning'; ?>">
                                                    <?php echo ucfirst($payment['status'] ?? ''); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

<!-- Send Invoice Modal -->
<div class="modal fade" id="sendModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-warning">
                <h5 class="modal-title">Send Invoice to Guest</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <form action="send.php" 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; ?>
                <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">
                
                <div class="modal-body">
                    <p>Send invoice to <strong><?php echo htmlspecialchars($invoice['email'] ?? ''); ?></strong>?</p>
                    
                    <div class="form-group mb-3">
                        <label for="email_subject">Subject</label>
                        <input type="text" class="form-control" id="email_subject" name="subject" 
                               value="Invoice <?php echo htmlspecialchars($invoice['invoice_number'] ?? ''); ?> from Ruhondo Beach Resort">
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="email_message">Message (Optional)</label>
                        <textarea class="form-control" id="email_message" name="message" rows="3"></textarea>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                    <button type="submit" class="btn btn-warning">Send Invoice</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
function sendInvoice() {
    // Initialize Bootstrap 5 modal
    const sendModal = new bootstrap.Modal(document.getElementById('sendModal'));
    sendModal.show();
}
</script>

<style>
.badge-lg {
    font-size: 1rem;
    padding: 0.5rem 1rem;
}
</style>

<?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>';
}
?>