<?php
session_start();
include 'layouts/dbconn.php';

// Check if the user is not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

// Check if invoice ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    $_SESSION['error_message'] = "No invoice ID provided";
    header('Location: file_list.php');
    exit();
}

$invoice_id = intval($_GET['id']);

// Get user details
$user_id = $_SESSION['user_id'];
$sql_user_details = "SELECT username, user_role, full_name, email, role_id FROM users WHERE user_id = $user_id";
$result_user_details = $conn->query($sql_user_details);

if ($result_user_details && $row_user_details = $result_user_details->fetch_assoc()) {
    $username = $row_user_details['username'];
    $user_role = $row_user_details['user_role'];
    $full_name = $row_user_details['full_name'];
    $email = $row_user_details['email'];
    $role_id = $row_user_details['role_id'];
}

// Check user permissions
function hasPermission($role_id, $permission) {
    // Define permissions for different roles
    $permissions = [
        '1' => ['view', 'edit', 'delete', 'approve', 'invoice'], // Admin has all permissions
        '2' => ['view', 'edit', 'approve', 'invoice'], // General Manager
        '3' => ['view', 'edit', 'invoice'], // Operations
        '4' => ['view', 'invoice'], // Finance
        '5' => ['view', 'edit'], // Declaration Officer
        '6' => ['view'], // Shipping Line Clerk
        '7' => ['view'], // Transport Supervisor
    ];
    
    if (isset($permissions[$role_id]) && in_array($permission, $permissions[$role_id])) {
        return true;
    }
    
    return false;
}

$can_edit_invoice = hasPermission($role_id, 'invoice');

// Get invoice details
$query = "SELECT i.*, c.first_name as customer_name, c.email as customer_email, c.address as customer_address,
          c.phone_number as customer_phone, f.currency as file_currency, f.id as file_id
          FROM invoices i 
          LEFT JOIN customers c ON i.customer_id = c.customer_id
          LEFT JOIN files f ON i.file_number = f.file_number
          WHERE i.invoice_id = ?";

$stmt = $conn->prepare($query);
$stmt->bind_param('i', $invoice_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    $_SESSION['error_message'] = "Invoice not found";
    header('Location: file_list.php');
    exit();
}

$invoice = $result->fetch_assoc();
$file_number = $invoice['file_number'];
$file_id = $invoice['file_id'];
$currency = $invoice['file_currency'] ?? '$';

// Try to get invoice items from a separate table if it exists
$invoice_items = [];

try {
    // First try to get items from invoice_items table
    $items_query = "SELECT * FROM invoice_items WHERE invoice_id = ? ORDER BY id ASC";
    $items_stmt = $conn->prepare($items_query);
    
    if ($items_stmt) {
        $items_stmt->bind_param('i', $invoice_id);
        $items_stmt->execute();
        $items_result = $items_stmt->get_result();
        
        if ($items_result && $items_result->num_rows > 0) {
            while ($row = $items_result->fetch_assoc()) {
                $invoice_items[] = [
                    'name' => $row['name'],
                    'description' => $row['description'],
                    'quantity' => $row['quantity'],
                    'price' => $row['price'],
                    'total' => $row['quantity'] * $row['price']
                ];
            }
        }
        $items_stmt->close();
    }
} catch (mysqli_sql_exception $e) {
    // Table doesn't exist, we'll use fallback below
    // No need to show error to user, just use fallback
}

// If no items were found (either table doesn't exist or no records),
// fallback to using fields from the main invoice table
if (empty($invoice_items)) {
    $item_name = $invoice['name'] ?? 'Shipping Services';
    $item_description = $invoice['description'] ?? 'Services for shipment ' . $file_number;
    $item_quantity = $invoice['quantity'] ?? 1;
    $item_price = $invoice['price'] ?? $invoice['total_amount'] ?? 0;
    
    $invoice_items[] = [
        'name' => $item_name,
        'description' => $item_description,
        'quantity' => $item_quantity,
        'price' => $item_price,
        'total' => $item_quantity * $item_price
    ];
}

// Function to convert number to words (for total amount)
function numberToWords($number) {
    $hyphen = '-';
    $conjunction = ' and ';
    $separator = ', ';
    $negative = 'negative ';
    $decimal = ' point ';
    $dictionary = array(
        0 => 'zero',
        1 => 'one',
        2 => 'two',
        3 => 'three',
        4 => 'four',
        5 => 'five',
        6 => 'six',
        7 => 'seven',
        8 => 'eight',
        9 => 'nine',
        10 => 'ten',
        11 => 'eleven',
        12 => 'twelve',
        13 => 'thirteen',
        14 => 'fourteen',
        15 => 'fifteen',
        16 => 'sixteen',
        17 => 'seventeen',
        18 => 'eighteen',
        19 => 'nineteen',
        20 => 'twenty',
        30 => 'thirty',
        40 => 'forty',
        50 => 'fifty',
        60 => 'sixty',
        70 => 'seventy',
        80 => 'eighty',
        90 => 'ninety',
        100 => 'hundred',
        1000 => 'thousand',
        1000000 => 'million',
        1000000000 => 'billion',
        1000000000000 => 'trillion',
        1000000000000000 => 'quadrillion',
        1000000000000000000 => 'quintillion'
    );
    
    if (!is_numeric($number)) {
        return false;
    }
    
    if (($number >= 0 && (int)$number < 0) || (int)$number < 0 - PHP_INT_MAX) {
        // overflow
        return false;
    }
    
    if ($number < 0) {
        return $negative . numberToWords(abs($number));
    }
    
    $string = $fraction = null;
    
    if (strpos($number, '.') !== false) {
        list($number, $fraction) = explode('.', $number);
    }
    
    switch (true) {
        case $number < 21:
            $string = $dictionary[$number];
            break;
        case $number < 100:
            $tens = ((int)($number / 10)) * 10;
            $units = $number % 10;
            $string = $dictionary[$tens];
            if ($units) {
                $string .= $hyphen . $dictionary[$units];
            }
            break;
        case $number < 1000:
            $hundreds = $number / 100;
            $remainder = $number % 100;
            $string = $dictionary[(int)$hundreds] . ' ' . $dictionary[100];
            if ($remainder) {
                $string .= $conjunction . numberToWords($remainder);
            }
            break;
        default:
            $baseUnit = pow(1000, floor(log($number, 1000)));
            $numBaseUnits = (int)($number / $baseUnit);
            $remainder = $number % $baseUnit;
            $string = numberToWords($numBaseUnits) . ' ' . $dictionary[$baseUnit];
            if ($remainder) {
                $string .= $remainder < 100 ? $conjunction : $separator;
                $string .= numberToWords($remainder);
            }
            break;
    }
    
    if (null !== $fraction && is_numeric($fraction)) {
        $string .= $decimal;
        $words = array();
        foreach (str_split((string)$fraction) as $number) {
            $words[] = $dictionary[$number];
        }
        $string .= implode(' ', $words);
    }
    
    return $string;
}

// Function to format dates
function formatDate($date) {
    if (empty($date) || $date == '0000-00-00' || $date == '0000-00-00 00:00:00') {
        return 'N/A';
    }
    return date('d M Y', strtotime($date));
}

// Get company settings
$settings_query = "SELECT * FROM settings WHERE setting_key IN ('system_name', 'address', 'tel_1', 'tel_2')";
$settings_result = $conn->query($settings_query);
$settings = [];

if ($settings_result->num_rows > 0) {
    while ($row = $settings_result->fetch_assoc()) {
        $settings[$row['setting_key']] = $row['setting_value'];
    }
}

// Handle invoice status update if form submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status']) && $can_edit_invoice) {
    $new_status = $_POST['status'];
    $update_query = "UPDATE invoices SET status = ? WHERE invoice_id = ?";
    $update_stmt = $conn->prepare($update_query);
    $update_stmt->bind_param('si', $new_status, $invoice_id);
    
    if ($update_stmt->execute()) {
        $_SESSION['success_message'] = "Invoice status updated successfully";
        // Reload the page to show updated status
        header("Location: view_invoice.php?id=$invoice_id");
        exit();
    } else {
        $_SESSION['error_message'] = "Error updating invoice status: " . $conn->error;
    }
}

// Get payment history if exists
$payments = [];
try {
    $payment_query = "SELECT * FROM invoice_payments WHERE invoice_id = ? ORDER BY payment_date DESC";
    $payment_stmt = $conn->prepare($payment_query);
    
    if ($payment_stmt) {
        $payment_stmt->bind_param('i', $invoice_id);
        $payment_stmt->execute();
        $payment_result = $payment_stmt->get_result();
        
        if ($payment_result && $payment_result->num_rows > 0) {
            while ($row = $payment_result->fetch_assoc()) {
                $payments[] = $row;
            }
        }
        $payment_stmt->close();
    }
} catch (mysqli_sql_exception $e) {
    // Table doesn't exist or other error
    // No need to show error to user
}
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'View Invoice')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .invoice-container {
            max-width: 1000px;
            margin: 0 auto;
        }
        .invoice-header {
            margin-bottom: 2rem;
        }
        .invoice-logo {
            text-align: left;
        }
        .invoice-company {
            text-align: left;
        }
        .invoice-title {
            text-align: right;
            font-size: 1.5rem;
            font-weight: 600;
            color: #405189;
        }
        .invoice-details {
            text-align: right;
        }
        .party-details {
            margin-bottom: 2rem;
        }
        .from-details, .to-details {
            padding: 1.5rem;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
            height: 100%;
        }
        .party-title {
            font-weight: 600;
            margin-bottom: 0.5rem;
            color: #495057;
        }
        .invoice-items-table {
            margin-bottom: 2rem;
        }
        .table-header {
            background-color: #f8f9fa;
        }
        .invoice-total-section {
            margin-top: 1rem;
            text-align: right;
        }
        .invoice-total-table {
            width: auto;
            margin-left: auto;
        }
        .invoice-total-row {
            font-weight: 600;
        }
        .invoice-notes {
            margin-top: 2rem;
            padding: 1rem;
            background-color: #f8f9fa;
            border-radius: 0.25rem;
        }
        .amount-in-words {
            font-style: italic;
            margin-top: 1rem;
        }
        .invoice-footer {
            margin-top: 3rem;
            padding-top: 1rem;
            border-top: 1px solid #dee2e6;
            text-align: center;
            color: #6c757d;
            font-size: 0.875rem;
        }
        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.75rem;
            letter-spacing: 1px;
        }
        .status-pending {
            background-color: #fff4de;
            color: #b95000;
        }
        .status-paid {
            background-color: #e0f8e9;
            color: #1f7a54;
        }
        .status-cancelled {
            background-color: #fde8e8;
            color: #cb2431;
        }
        .action-buttons {
            margin-bottom: 1.5rem;
        }
        .payment-history {
            margin-top: 2rem;
        }
        .payment-history-title {
            font-weight: 600;
            margin-bottom: 1rem;
            color: #495057;
            padding-bottom: 0.5rem;
            border-bottom: 1px solid #dee2e6;
        }
        @media print {
            .no-print {
                display: none !important;
            }
            .card {
                border: none !important;
                box-shadow: none !important;
            }
            .container-fluid {
                padding: 0 !important;
            }
            body {
                background-color: white !important;
            }
        }
    </style>
</head>

<body>
    <!-- Begin page -->
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <!-- ============================================================== -->
        <!-- Start right Content here -->
        <!-- ============================================================== -->
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Invoices', 'title' => 'View Invoice')); ?>

                    <?php if (isset($_SESSION['success_message'])): ?>
                    <div class="alert alert-success alert-dismissible fade show no-print" role="alert">
                        <?php echo $_SESSION['success_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['success_message']); ?>
                    <?php endif; ?>

                    <?php if (isset($_SESSION['error_message'])): ?>
                    <div class="alert alert-danger alert-dismissible fade show no-print" role="alert">
                        <?php echo $_SESSION['error_message']; ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                    <?php unset($_SESSION['error_message']); ?>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card">
                                <div class="card-body">
                                    <div class="invoice-container">
                                        <!-- Action Buttons -->
                                        <div class="action-buttons no-print">
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <a href="<?php echo !empty($file_id) ? "view_file.php?id=$file_id" : "file_list.php"; ?>" class="btn btn-secondary">
                                                        <i class="ri-arrow-left-line align-bottom me-1"></i> Back
                                                    </a>
                                                </div>
                                                <div class="col-md-6 text-end">
                                                    <button type="button" class="btn btn-success me-2" onclick="window.print()">
                                                        <i class="ri-printer-line align-bottom me-1"></i> Print Invoice
                                                    </button>
                                                    <?php if ($can_edit_invoice): ?>
                                                    <button type="button" class="btn btn-primary me-2" data-bs-toggle="modal" data-bs-target="#updateStatusModal">
                                                        <i class="ri-exchange-line align-bottom me-1"></i> Update Status
                                                    </button>
                                                    <?php endif; ?>
                                                    <a href="print_invoice.php?id=<?php echo $invoice_id; ?>" class="btn btn-info" target="_blank">
                                                        <i class="ri-file-download-line align-bottom me-1"></i> PDF
                                                    </a>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Invoice Header -->
                                        <div class="invoice-header row">
                                            <div class="col-md-6">
                                                <div class="invoice-logo">
                                                    <h3><?php echo htmlspecialchars($settings['system_name'] ?? 'Royal Freight System'); ?></h3>
                                                </div>
                                                <div class="invoice-company">
                                                    <p><?php echo nl2br(htmlspecialchars($settings['address'] ?? 'P.O.Box-85636-80100, Mombasa')); ?></p>
                                                    <p>Tel: <?php echo htmlspecialchars($settings['tel_1'] ?? ''); ?>
                                                    <?php echo !empty($settings['tel_2']) ? ' / ' . htmlspecialchars($settings['tel_2']) : ''; ?></p>
                                                </div>
                                            </div>
                                            <div class="col-md-6">
                                                <div class="invoice-title">
                                                    INVOICE
                                                </div>
                                                <div class="invoice-details">
                                                    <p><strong>Invoice #:</strong> <?php echo htmlspecialchars($invoice['invoice_number']); ?></p>
                                                    <p><strong>Date:</strong> <?php echo formatDate($invoice['issue_date']); ?></p>
                                                    <p><strong>Due Date:</strong> <?php echo formatDate($invoice['due_date']); ?></p>
                                                    <p>
                                                        <strong>Status:</strong> 
                                                        <span class="status-badge status-<?php echo strtolower($invoice['status']); ?>">
                                                            <?php echo ucfirst($invoice['status']); ?>
                                                        </span>
                                                    </p>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Party Details -->
                                        <div class="party-details row">
                                            <div class="col-md-6 mb-3">
                                                <div class="from-details">
                                                    <div class="party-title">FROM:</div>
                                                    <div>
                                                        <strong><?php echo htmlspecialchars($settings['system_name'] ?? 'Royal Freight System'); ?></strong><br>
                                                        <?php echo nl2br(htmlspecialchars($settings['address'] ?? 'P.O.Box-85636-80100, Mombasa')); ?><br>
                                                        Tel: <?php echo htmlspecialchars($settings['tel_1'] ?? ''); ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <div class="to-details">
                                                    <div class="party-title">BILL TO:</div>
                                                    <div>
                                                        <strong><?php echo htmlspecialchars($invoice['customer_name']); ?></strong><br>
                                                        <?php if (!empty($invoice['customer_address'])): ?>
                                                        <?php echo nl2br(htmlspecialchars($invoice['customer_address'])); ?><br>
                                                        <?php endif; ?>
                                                        <?php if (!empty($invoice['customer_phone'])): ?>
                                                        Tel: <?php echo htmlspecialchars($invoice['customer_phone']); ?><br>
                                                        <?php endif; ?>
                                                        <?php if (!empty($invoice['customer_email'])): ?>
                                                        Email: <?php echo htmlspecialchars($invoice['customer_email']); ?>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Reference Information -->
                                        <div class="row mb-4">
                                            <div class="col-12">
                                                <table class="table table-bordered">
                                                    <tbody>
                                                        <tr>
                                                            <th style="width: 200px;">File Reference:</th>
                                                            <td><?php echo htmlspecialchars($invoice['file_number']); ?></td>
                                                        </tr>
                                                    </tbody>
                                                </table>
                                            </div>
                                        </div>

                                        <!-- Invoice Items -->
                                        <div class="invoice-items-table">
                                            <table class="table table-bordered">
                                                <thead class="table-header">
                                                    <tr>
                                                        <th style="width: 50px;">#</th>
                                                        <th>Item</th>
                                                        <th>Description</th>
                                                        <th style="width: 100px;">Quantity</th>
                                                        <th style="width: 150px;">Unit Price</th>
                                                        <th style="width: 150px;">Total</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($invoice_items as $index => $item): ?>
                                                    <tr>
                                                        <td><?php echo $index + 1; ?></td>
                                                        <td><?php echo htmlspecialchars($item['name']); ?></td>
                                                        <td><?php echo htmlspecialchars($item['description']); ?></td>
                                                        <td class="text-center"><?php echo htmlspecialchars($item['quantity']); ?></td>
                                                        <td class="text-end"><?php echo htmlspecialchars($currency . ' ' . number_format($item['price'], 2)); ?></td>
                                                        <td class="text-end"><?php echo htmlspecialchars($currency . ' ' . number_format($item['total'], 2)); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>

                                        <!-- Invoice Totals -->
                                        <div class="invoice-total-section">
                                            <table class="invoice-total-table table table-bordered">
                                                <tbody>
                                                    <tr>
                                                        <th style="width: 150px;">Subtotal:</th>
                                                        <td style="width: 200px;" class="text-end"><?php echo htmlspecialchars($currency . ' ' . number_format($invoice['total_amount'], 2)); ?></td>
                                                    </tr>
                                                    <tr class="invoice-total-row">
                                                        <th>Total:</th>
                                                        <td class="text-end"><?php echo htmlspecialchars($currency . ' ' . number_format($invoice['total_amount'], 2)); ?></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                            <div class="amount-in-words">
                                                <strong>Amount in words:</strong> <?php echo ucfirst(numberToWords($invoice['total_amount'])) . ' ' . ($currency == '$' ? 'Dollars' : $currency); ?> Only
                                            </div>
                                        </div>

                                        <!-- Payment History (if exists) -->
                                        <?php if (!empty($payments)): ?>
                                        <div class="payment-history">
                                            <div class="payment-history-title">Payment History</div>
                                            <table class="table table-bordered table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>Date</th>
                                                        <th>Reference</th>
                                                        <th>Method</th>
                                                        <th>Amount</th>
                                                        <th>Notes</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <?php foreach ($payments as $payment): ?>
                                                    <tr>
                                                        <td><?php echo formatDate($payment['payment_date']); ?></td>
                                                        <td><?php echo htmlspecialchars($payment['reference_number']); ?></td>
                                                        <td><?php echo htmlspecialchars($payment['payment_method']); ?></td>
                                                        <td class="text-end"><?php echo htmlspecialchars($currency . ' ' . number_format($payment['amount'], 2)); ?></td>
                                                        <td><?php echo htmlspecialchars($payment['notes']); ?></td>
                                                    </tr>
                                                    <?php endforeach; ?>
                                                </tbody>
                                            </table>
                                        </div>
                                        <?php endif; ?>

                                        <!-- Invoice Notes -->
                                        <?php if (!empty($invoice['notes'])): ?>
                                        <div class="invoice-notes">
                                            <h5>Notes / Terms</h5>
                                            <p><?php echo nl2br(htmlspecialchars($invoice['notes'])); ?></p>
                                        </div>
                                        <?php endif; ?>

                                        <!-- Invoice Footer -->
                                        <div class="invoice-footer">
                                            <p>Thank you for your business!</p>
                                            <p>This is a computer generated invoice and does not require a signature.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- container-fluid -->
            </div>
            <!-- End Page-content -->

            <?php include 'layouts/footer.php'; ?>
        </div>
        <!-- end main content-->
    </div>
    <!-- END layout-wrapper -->

    <!-- Status Update Modal -->
    <?php if ($can_edit_invoice): ?>
    <div class="modal fade" id="updateStatusModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Update Invoice Status</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="status" class="form-label">Status</label>
                            <select class="form-select" id="status" name="status">
                                <option value="pending" <?php echo ($invoice['status'] == 'pending') ? 'selected' : ''; ?>>Pending</option>
                                <option value="paid" <?php echo ($invoice['status'] == 'paid') ? 'selected' : ''; ?>>Paid</option>
                                <option value="cancelled" <?php echo ($invoice['status'] == 'cancelled') ? 'selected' : ''; ?>>Cancelled</option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                        <button type="submit" name="update_status" class="btn btn-primary">Update Status</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <!-- Record Payment Modal -->
    <div class="modal fade" id="recordPaymentModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Record Payment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form method="POST" action="record_payment.php">
                    <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="payment_date" class="form-label">Payment Date</label>
                            <input type="date" class="form-control" id="payment_date" name="payment_date" value="<?php echo date('Y-m-d'); ?>" required>
                        </div>
                        <div class="mb-3">
                            <label for="amount" class="form-label">Amount</label>
                            <div class="input-group">
                                <span class="input-group-text"><?php echo htmlspecialchars($currency); ?></span>
                                <input type="number" step="0.01" class="form-control" id="amount" name="amount" 
                                    value="<?php echo htmlspecialchars($invoice['total_amount']); ?>" required>
                            </div>
                        </div>
                        <div class="mb-3">
                            <label for="payment_method" class="form-label">Payment Method</label>
                            <select class="form-select" id="payment_method" name="payment_method" required>
                               <option value="Bank Transfer">Bank Transfer</option>
                               <option value="Cash">Cash</option>
                               <option value="Check">Check</option>
                               <option value="Credit Card">Credit Card</option>
                               <option value="Mobile Money">Mobile Money</option>
                               <option value="Other">Other</option>
                           </select>
                       </div>
                       <div class="mb-3">
                           <label for="reference_number" class="form-label">Reference Number</label>
                           <input type="text" class="form-control" id="reference_number" name="reference_number" 
                               placeholder="Transaction/Check/Receipt number">
                       </div>
                       <div class="mb-3">
                           <label for="notes" class="form-label">Notes</label>
                           <textarea class="form-control" id="notes" name="notes" rows="3" 
                               placeholder="Any additional information about this payment"></textarea>
                       </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <button type="submit" name="record_payment" class="btn btn-success">Record Payment</button>
                   </div>
               </form>
           </div>
       </div>
   </div>
   <?php endif; ?>

   <!-- Send Invoice Modal -->
   <div class="modal fade" id="sendInvoiceModal" tabindex="-1" aria-hidden="true">
       <div class="modal-dialog modal-dialog-centered">
           <div class="modal-content">
               <div class="modal-header">
                   <h5 class="modal-title">Send Invoice</h5>
                   <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
               </div>
               <form method="POST" action="send_invoice.php">
                   <input type="hidden" name="invoice_id" value="<?php echo $invoice_id; ?>">
                   <div class="modal-body">
                       <div class="mb-3">
                           <label for="recipient_email" class="form-label">Recipient Email</label>
                           <input type="email" class="form-control" id="recipient_email" name="recipient_email" 
                               value="<?php echo htmlspecialchars($invoice['customer_email'] ?? ''); ?>" required>
                       </div>
                       <div class="mb-3">
                           <label for="cc_email" class="form-label">CC (Optional)</label>
                           <input type="email" class="form-control" id="cc_email" name="cc_email">
                       </div>
                       <div class="mb-3">
                           <label for="subject" class="form-label">Subject</label>
                           <input type="text" class="form-control" id="subject" name="subject" 
                               value="Invoice <?php echo htmlspecialchars($invoice['invoice_number']); ?> from <?php echo htmlspecialchars($settings['system_name'] ?? 'Royal Freight System'); ?>" required>
                       </div>
                       <div class="mb-3">
                           <label for="message" class="form-label">Message</label>
                           <textarea class="form-control" id="message" name="message" rows="4" required>Dear <?php echo htmlspecialchars($invoice['customer_name']); ?>,

Please find attached invoice <?php echo htmlspecialchars($invoice['invoice_number']); ?> for shipment <?php echo htmlspecialchars($file_number); ?>.

Payment is due by <?php echo formatDate($invoice['due_date']); ?>.

Thank you for your business.

Regards,
<?php echo htmlspecialchars($settings['system_name'] ?? 'Royal Freight System'); ?>
                           </textarea>
                       </div>
                       <div class="mb-3 form-check">
                           <input type="checkbox" class="form-check-input" id="attach_pdf" name="attach_pdf" value="1" checked>
                           <label class="form-check-label" for="attach_pdf">Attach PDF invoice</label>
                       </div>
                   </div>
                   <div class="modal-footer">
                       <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                       <button type="submit" name="send_invoice" class="btn btn-primary">Send Invoice</button>
                   </div>
               </form>
           </div>
       </div>
   </div>

   <?php include 'layouts/vendor-scripts.php'; ?>
   <script src="assets/js/app.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
<script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
   <script>
       document.addEventListener('DOMContentLoaded', function() {
           // Add action buttons based on status
           const actionButtonsContainer = document.querySelector('.action-buttons .col-md-6.text-end');
           const invoiceStatus = "<?php echo $invoice['status']; ?>";
           const canEditInvoice = <?php echo $can_edit_invoice ? 'true' : 'false'; ?>;
           
           if (canEditInvoice) {
               if (invoiceStatus === 'pending') {
                   // Add Record Payment button
                   const recordPaymentBtn = document.createElement('button');
                   recordPaymentBtn.type = 'button';
                   recordPaymentBtn.className = 'btn btn-warning me-2';
                   recordPaymentBtn.setAttribute('data-bs-toggle', 'modal');
                   recordPaymentBtn.setAttribute('data-bs-target', '#recordPaymentModal');
                   recordPaymentBtn.innerHTML = '<i class="ri-money-dollar-circle-line align-bottom me-1"></i> Record Payment';
                   actionButtonsContainer.insertBefore(recordPaymentBtn, actionButtonsContainer.firstChild);
               }
               
               // Add Send Invoice button
               if (invoiceStatus !== 'cancelled') {
                   const sendInvoiceBtn = document.createElement('button');
                   sendInvoiceBtn.type = 'button';
                   sendInvoiceBtn.className = 'btn btn-secondary me-2';
                   sendInvoiceBtn.setAttribute('data-bs-toggle', 'modal');
                   sendInvoiceBtn.setAttribute('data-bs-target', '#sendInvoiceModal');
                   sendInvoiceBtn.innerHTML = '<i class="ri-mail-send-line align-bottom me-1"></i> Email Invoice';
                   actionButtonsContainer.insertBefore(sendInvoiceBtn, actionButtonsContainer.firstChild);
               }
           }
       });
   </script>
</body>
</html>