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

// Set timezone
date_default_timezone_set('Africa/Nairobi');

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

$user_id = $_SESSION['user_id'];
$invoice_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$invoice_id) {
    header('Location: invoices.php');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'update_invoice') {
    $invoice_date = $_POST['invoice_date'];
    $due_date = $_POST['due_date'];
    $payment_terms = intval($_POST['payment_terms']);
    $notes = $_POST['notes'] ?? '';
    $tax_rate = floatval($_POST['tax_rate']);
    
    // Calculate new totals
    $subtotal = 0;
    $item_updates = json_decode($_POST['item_updates'], true);
    
    // Update invoice items and calculate new subtotal
    foreach ($item_updates as $item_id => $item_data) {
        $quantity = floatval($item_data['quantity']);
        $unit_price = floatval($item_data['unit_price']);
        $line_total = $quantity * $unit_price;
        $subtotal += $line_total;
        
        $update_item_sql = "UPDATE invoice_items SET quantity = ?, unit_price = ?, line_total = ? WHERE item_id = ? AND invoice_id = ?";
        $stmt_item = $conn->prepare($update_item_sql);
        $stmt_item->bind_param("ddiii", $quantity, $unit_price, $line_total, $item_id, $invoice_id);
        $stmt_item->execute();
    }
    
    // Calculate tax and total
    $tax_amount = ($subtotal * $tax_rate) / 100;
    $total_amount = $subtotal + $tax_amount;
    $balance_amount = $total_amount - $invoice['paid_amount']; // Keep existing paid amount
    
    // Update invoice
    $update_sql = "UPDATE invoices SET 
                   invoice_date = ?, due_date = ?, payment_terms = ?, notes = ?, 
                   tax_rate = ?, subtotal = ?, tax_amount = ?, total_amount = ?, balance_amount = ?,
                   updated_by = ?, updated_at = NOW() 
                   WHERE invoice_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("ssisiidddi", 
        $invoice_date, $due_date, $payment_terms, $notes, 
        $tax_rate, $subtotal, $tax_amount, $total_amount, $balance_amount,
        $user_id, $invoice_id
    );
    
    if ($stmt->execute()) {
        // Log activity
        $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, old_values, new_values) 
                   VALUES (?, 'UPDATE', 'invoices', ?, 'invoice_updated', ?)";
        $stmt_log = $conn->prepare($log_sql);
        $details = json_encode(['subtotal' => $subtotal, 'total' => $total_amount]);
        $stmt_log->bind_param("iss", $user_id, $invoice_id, $details);
        $stmt_log->execute();
        
        header("Location: view_invoice.php?id=$invoice_id&success=Invoice updated successfully");
        exit();
    } else {
        $error_message = "Failed to update invoice. Please try again.";
    }
}

// Fetch invoice details
$sql_invoice = "
    SELECT 
        i.*,
        c.customer_code,
        c.company_name,
        c.first_name,
        c.last_name,
        c.customer_type,
        c.email,
        c.phone
    FROM invoices i
    LEFT JOIN customers c ON i.customer_id = c.customer_id
    WHERE i.invoice_id = ?";

$stmt = $conn->prepare($sql_invoice);
$stmt->bind_param("i", $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();

if (!$invoice) {
    header('Location: invoices.php?error=Invoice not found');
    exit();
}

// Check if invoice can be edited (only DRAFT and SENT invoices should be fully editable)
$is_editable = in_array($invoice['status'], ['DRAFT', 'SENT']);

// Fetch invoice items
$sql_items = "
    SELECT 
        ii.*,
        s.tracking_number,
        s.content_description as shipment_description
    FROM invoice_items ii
    LEFT JOIN shipments s ON ii.shipment_id = s.shipment_id
    WHERE ii.invoice_id = ?
    ORDER BY ii.item_id";

$stmt_items = $conn->prepare($sql_items);
$stmt_items->bind_param("i", $invoice_id);
$stmt_items->execute();
$invoice_items = $stmt_items->get_result();

$conn->close();
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Edit Invoice #' . $invoice['invoice_number'])); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <!-- SweetAlert2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.css" rel="stylesheet">
    
    <!-- Remix Icons -->
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    
    <style>
        .edit-form-card {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            border: 1px solid #e3e6f0;
            margin-bottom: 1.5rem;
        }
        
        .invoice-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 2rem;
        }
        
        .customer-info {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1rem;
            border: 1px solid #dee2e6;
        }
        
        .customer-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .item-row {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1rem;
            transition: all 0.3s ease;
        }
        
        .item-row:hover {
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .item-row.readonly {
            background: #f8f9fa;
        }
        
        .form-control:focus {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
        }
        
        .btn-calculate {
            background: linear-gradient(45deg, #667eea, #764ba2);
            border: none;
            color: white;
        }
        
        .btn-calculate:hover {
            background: linear-gradient(45deg, #764ba2, #667eea);
            color: white;
        }
        
        .totals-section {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 1.5rem;
            border: 2px solid #dee2e6;
        }
        
        .total-row {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0.5rem 0;
        }
        
        .total-row.grand-total {
            border-top: 2px solid #667eea;
            padding-top: 1rem;
            margin-top: 1rem;
            font-size: 1.25rem;
            font-weight: 700;
        }
        
        .status-badge {
            padding: 0.35rem 0.75rem;
            border-radius: 15px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .status-draft { background: #f8f9fa; color: #6c757d; }
        .status-sent { background: #cff4fc; color: #055160; }
        .status-paid { background: #d1e7dd; color: #0a3622; }
        .status-partial { background: #fff3cd; color: #664d03; }
        .status-overdue { background: #f8d7da; color: #58151c; }
        .status-cancelled { background: #f1f3f4; color: #3c4043; }
        
        .warning-alert {
            background: linear-gradient(45deg, #f59e0b, #d97706);
            color: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .readonly-notice {
            background: linear-gradient(45deg, #6b7280, #4b5563);
            color: white;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 1.5rem;
        }
        
        @media (max-width: 768px) {
            .invoice-header {
                padding: 1.5rem;
                text-align: center;
            }
            
            .item-row {
                padding: 0.75rem;
            }
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0">
                                    <i class="ri-edit-line me-2"></i>Edit Invoice #<?php echo $invoice['invoice_number']; ?>
                                </h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="invoices.php">Invoices</a></li>
                                        <li class="breadcrumb-item"><a href="view_invoice.php?id=<?php echo $invoice_id; ?>">View</a></li>
                                        <li class="breadcrumb-item active">Edit</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Error Message -->
                    <?php if (isset($error_message)): ?>
                    <div class="row">
                        <div class="col-12">
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="ri-error-warning-line me-2"></i><?php echo $error_message; ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Invoice Header -->
                    <div class="invoice-header">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h2 class="mb-3">Invoice #<?php echo $invoice['invoice_number']; ?></h2>
                                <div class="row">
                                    <div class="col-md-6">
                                        <p class="mb-2"><strong>Created:</strong> <?php echo date('M j, Y', strtotime($invoice['created_at'])); ?></p>
                                        <p class="mb-0"><strong>Current Status:</strong> 
                                            <span class="status-badge status-<?php echo strtolower($invoice['status']); ?>">
                                                <?php echo $invoice['status']; ?>
                                            </span>
                                        </p>
                                    </div>
                                    <div class="col-md-6">
                                        <p class="mb-2"><strong>Current Total:</strong> $<?php echo number_format($invoice['total_amount'], 2); ?></p>
                                        <p class="mb-0"><strong>Balance Due:</strong> $<?php echo number_format($invoice['balance_amount'], 2); ?></p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-end">
                                <a href="view_invoice.php?id=<?php echo $invoice_id; ?>" class="btn btn-light">
                                    <i class="ri-eye-line me-1"></i>View Invoice
                                </a>
                            </div>
                        </div>
                    </div>

                    <!-- Editability Warning -->
                    <?php if (!$is_editable): ?>
                    <div class="readonly-notice">
                        <div class="d-flex align-items-center">
                            <i class="ri-lock-line fs-3 me-3"></i>
                            <div>
                                <h5 class="mb-1">Limited Editing</h5>
                                <p class="mb-0">This invoice has status "<?php echo $invoice['status']; ?>". Only basic details can be modified to maintain data integrity.</p>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <form method="POST" id="editInvoiceForm">
                        <input type="hidden" name="action" value="update_invoice">
                        
                        <div class="row">
                            <!-- Main Form -->
                            <div class="col-xl-8">
                                
                                <!-- Customer Information (Read Only) -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-user-line me-2"></i>Customer Information
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="customer-info">
                                            <div class="d-flex align-items-center">
                                                <div class="customer-avatar me-3">
                                                    <?php 
                                                    if ($invoice['customer_type'] == 'CORPORATE') {
                                                        echo strtoupper(substr($invoice['company_name'] ?? 'C', 0, 2));
                                                    } else {
                                                        echo strtoupper(substr($invoice['first_name'] ?? 'I', 0, 1) . substr($invoice['last_name'] ?? 'N', 0, 1));
                                                    }
                                                    ?>
                                                </div>
                                                <div>
                                                    <h5 class="mb-1">
                                                        <?php 
                                                        echo $invoice['customer_type'] == 'CORPORATE' 
                                                            ? ($invoice['company_name'] ?? 'Company') 
                                                            : ($invoice['first_name'] ?? 'Individual') . ' ' . ($invoice['last_name'] ?? ''); 
                                                        ?>
                                                    </h5>
                                                    <p class="text-muted mb-0">Customer #<?php echo $invoice['customer_code']; ?></p>
                                                </div>
                                                <div class="ms-auto">
                                                    <p class="mb-1"><strong>Email:</strong> <?php echo $invoice['email'] ?? 'Not provided'; ?></p>
                                                    <p class="mb-0"><strong>Phone:</strong> <?php echo $invoice['phone'] ?? 'Not provided'; ?></p>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Invoice Details -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-calendar-line me-2"></i>Invoice Details
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-md-4">
                                                <label for="invoice_date" class="form-label">Invoice Date *</label>
                                                <input type="date" class="form-control" id="invoice_date" name="invoice_date" 
                                                       value="<?php echo $invoice['invoice_date']; ?>" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="due_date" class="form-label">Due Date *</label>
                                                <input type="date" class="form-control" id="due_date" name="due_date" 
                                                       value="<?php echo $invoice['due_date']; ?>" required>
                                            </div>
                                            <div class="col-md-4">
                                                <label for="payment_terms" class="form-label">Payment Terms (Days)</label>
                                                <input type="number" class="form-control" id="payment_terms" name="payment_terms" 
                                                       value="<?php echo $invoice['payment_terms']; ?>" min="0" max="365">
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Invoice Items -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-list-check me-2"></i>Invoice Items
                                        </h5>
                                        <?php if ($is_editable): ?>
                                        <button type="button" class="btn btn-calculate" onclick="calculateTotals()">
                                            <i class="ri-calculator-line me-1"></i>Recalculate
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                    <div class="card-body">
                                        <div id="invoice-items">
                                            <?php while ($item = $invoice_items->fetch_assoc()): ?>
                                            <div class="item-row <?php echo !$is_editable ? 'readonly' : ''; ?>">
                                                <div class="row align-items-center g-3">
                                                    <div class="col-md-5">
                                                        <label class="form-label">Description</label>
                                                        <textarea class="form-control" rows="2" readonly><?php echo htmlspecialchars($item['description']); ?></textarea>
                                                        <?php if ($item['tracking_number']): ?>
                                                        <small class="text-muted">Tracking: <?php echo $item['tracking_number']; ?></small>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label">Quantity</label>
                                                        <input type="number" class="form-control item-quantity" 
                                                               data-item-id="<?php echo $item['item_id']; ?>"
                                                               value="<?php echo $item['quantity']; ?>" 
                                                               step="0.01" min="0"
                                                               <?php echo !$is_editable ? 'readonly' : 'onchange="updateLineTotal(this)"'; ?>>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label">Unit Price</label>
                                                        <input type="number" class="form-control item-price" 
                                                               data-item-id="<?php echo $item['item_id']; ?>"
                                                               value="<?php echo $item['unit_price']; ?>" 
                                                               step="0.01" min="0"
                                                               <?php echo !$is_editable ? 'readonly' : 'onchange="updateLineTotal(this)"'; ?>>
                                                    </div>
                                                    <div class="col-md-2">
                                                        <label class="form-label">Line Total</label>
                                                        <input type="number" class="form-control item-total" 
                                                               data-item-id="<?php echo $item['item_id']; ?>"
                                                               value="<?php echo $item['line_total']; ?>" 
                                                               step="0.01" readonly>
                                                    </div>
                                                    <div class="col-md-1">
                                                        <?php if ($is_editable): ?>
                                                        <label class="form-label">&nbsp;</label>
                                                        <button type="button" class="btn btn-outline-danger btn-sm d-block" 
                                                                onclick="removeItem(<?php echo $item['item_id']; ?>)">
                                                            <i class="ri-delete-bin-line"></i>
                                                        </button>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                            <?php endwhile; ?>
                                        </div>
                                    </div>
                                </div>

                                <!-- Notes -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-file-text-line me-2"></i>Notes & Terms
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <textarea class="form-control" name="notes" rows="4" 
                                                  placeholder="Enter any additional notes or terms..."><?php echo htmlspecialchars($invoice['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>

                            </div>

                            <!-- Sidebar -->
                            <div class="col-xl-4">
                                
                                <!-- Totals Section -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-calculator-line me-2"></i>Invoice Totals
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="totals-section">
                                            
                                            <div class="mb-3">
                                                <label for="tax_rate" class="form-label">Tax Rate (%)</label>
                                                <input type="number" class="form-control" id="tax_rate" name="tax_rate" 
                                                       value="<?php echo $invoice['tax_rate']; ?>" 
                                                       step="0.01" min="0" max="100"
                                                       <?php echo !$is_editable ? 'readonly' : 'onchange="calculateTotals()"'; ?>>
                                            </div>
                                            
                                            <div class="total-row">
                                                <span>Subtotal:</span>
                                                <strong id="subtotal-display">$<?php echo number_format($invoice['subtotal'], 2); ?></strong>
                                            </div>
                                            
                                            <div class="total-row">
                                                <span>Tax Amount:</span>
                                                <strong id="tax-display">$<?php echo number_format($invoice['tax_amount'], 2); ?></strong>
                                            </div>
                                            
                                            <div class="total-row grand-total">
                                                <span>Total Amount:</span>
                                                <strong id="total-display">$<?php echo number_format($invoice['total_amount'], 2); ?></strong>
                                            </div>
                                            
                                            <hr>
                                            
                                            <div class="total-row">
                                                <span>Amount Paid:</span>
                                                <strong class="text-success">$<?php echo number_format($invoice['paid_amount'], 2); ?></strong>
                                            </div>
                                            
                                            <div class="total-row">
                                                <span>Balance Due:</span>
                                                <strong id="balance-display" class="text-warning">$<?php echo number_format($invoice['balance_amount'], 2); ?></strong>
                                            </div>
                                            
                                        </div>
                                    </div>
                                </div>

                                <!-- Action Buttons -->
                                <div class="edit-form-card">
                                    <div class="card-body">
                                        <div class="d-grid gap-2">
                                            <button type="submit" class="btn btn-primary">
                                                <i class="ri-save-line me-1"></i>Save Changes
                                            </button>
                                            <a href="view_invoice.php?id=<?php echo $invoice_id; ?>" class="btn btn-secondary">
                                                <i class="ri-arrow-left-line me-1"></i>Cancel & Return
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <!-- Warning Messages -->
                                <?php if ($invoice['paid_amount'] > 0): ?>
                                <div class="warning-alert">
                                    <div class="d-flex align-items-center">
                                        <i class="ri-alert-line fs-4 me-2"></i>
                                        <div>
                                            <h6 class="mb-1">Payment Warning</h6>
                                            <small>This invoice has received payments. Changes may affect the balance due.</small>
                                        </div>
                                    </div>
                                </div>
                                <?php endif; ?>

                                <!-- Invoice Status Info -->
                                <div class="edit-form-card">
                                    <div class="card-header bg-transparent border-bottom">
                                        <h5 class="card-title mb-0">
                                            <i class="ri-information-line me-2"></i>Invoice Status
                                        </h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row g-3">
                                            <div class="col-12">
                                                <div class="d-flex justify-content-between">
                                                    <span class="text-muted">Current Status:</span>
                                                    <span class="status-badge status-<?php echo strtolower($invoice['status']); ?>">
                                                        <?php echo $invoice['status']; ?>
                                                    </span>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="d-flex justify-content-between">
                                                    <span class="text-muted">Created:</span>
                                                    <strong><?php echo date('M j, Y', strtotime($invoice['created_at'])); ?></strong>
                                                </div>
                                            </div>
                                            <div class="col-12">
                                                <div class="d-flex justify-content-between">
                                                    <span class="text-muted">Last Updated:</span>
                                                    <strong><?php echo $invoice['updated_at'] ? date('M j, Y', strtotime($invoice['updated_at'])) : 'Never'; ?></strong>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                            </div>
                        </div>
                        
                        <input type="hidden" id="item_updates" name="item_updates" value="">
                    </form>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- SweetAlert2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11/dist/sweetalert2.min.js"></script>
    
    <script>
        // Track item changes
        let itemUpdates = {};
        
        // Update line total when quantity or price changes
        function updateLineTotal(element) {
            const itemId = element.dataset.itemId;
            const row = element.closest('.item-row');
            const quantity = parseFloat(row.querySelector('.item-quantity').value) || 0;
            const price = parseFloat(row.querySelector('.item-price').value) || 0;
            const total = quantity * price;
            
            row.querySelector('.item-total').value = total.toFixed(2);
            
            // Track the change
            itemUpdates[itemId] = {
                quantity: quantity,
                unit_price: price,
                line_total: total
            };
            
            // Auto-calculate totals
            calculateTotals();
        }
        
        // Calculate invoice totals
        function calculateTotals() {
            let subtotal = 0;
            
            // Sum all line totals
            document.querySelectorAll('.item-total').forEach(function(input) {
                subtotal += parseFloat(input.value) || 0;
            });
            
            const taxRate = parseFloat(document.getElementById('tax_rate').value) || 0;
            const taxAmount = (subtotal * taxRate) / 100;
            const totalAmount = subtotal + taxAmount;
            const paidAmount = <?php echo $invoice['paid_amount']; ?>;
            const balanceAmount = totalAmount - paidAmount;
            
            // Update displays
            document.getElementById('subtotal-display').textContent = ' + subtotal.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('tax-display').textContent = ' + taxAmount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('total-display').textContent = ' + totalAmount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            document.getElementById('balance-display').textContent = ' + balanceAmount.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2});
            
            // Update balance color
            const balanceElement = document.getElementById('balance-display');
            balanceElement.className = balanceAmount > 0 ? 'text-warning' : 'text-success';
        }
        
        // Remove item
        function removeItem(itemId) {
            Swal.fire({
                title: 'Remove Item',
                text: 'Are you sure you want to remove this item from the invoice?',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes, Remove',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Remove from DOM
                    const itemRow = document.querySelector(`[data-item-id="${itemId}"]`).closest('.item-row');
                    itemRow.remove();
                    
                    // Mark for deletion
                    itemUpdates[itemId] = {
                        quantity: 0,
                        unit_price: 0,
                        line_total: 0
                    };
                    
                    // Recalculate
                    calculateTotals();
                    
                    Swal.fire({
                        title: 'Item Removed',
                        text: 'The item has been removed from the invoice.',
                        icon: 'success',
                        timer: 2000,
                        showConfirmButton: false
                    });
                }
            });
        }
        
        // Form submission
        document.getElementById('editInvoiceForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Collect all item updates
            document.querySelectorAll('.item-quantity').forEach(function(input) {
                const itemId = input.dataset.itemId;
                const row = input.closest('.item-row');
                
                if (!itemUpdates[itemId]) {
                    itemUpdates[itemId] = {
                        quantity: parseFloat(row.querySelector('.item-quantity').value) || 0,
                        unit_price: parseFloat(row.querySelector('.item-price').value) || 0,
                        line_total: parseFloat(row.querySelector('.item-total').value) || 0
                    };
                }
            });
            
            // Set the hidden field
            document.getElementById('item_updates').value = JSON.stringify(itemUpdates);
            
            // Show confirmation
            Swal.fire({
                title: 'Save Changes',
                text: 'Are you sure you want to save these changes to the invoice?',
                icon: 'question',
                showCancelButton: true,
                confirmButtonText: 'Yes, Save Changes',
                cancelButtonText: 'Continue Editing'
            }).then((result) => {
                if (result.isConfirmed) {
                    // Show loading
                    Swal.fire({
                        title: 'Saving Changes...',
                        text: 'Please wait while we update the invoice.',
                        icon: 'info',
                        allowOutsideClick: false,
                        showConfirmButton: false,
                        didOpen: () => {
                            Swal.showLoading();
                        }
                    });
                    
                    // Submit the form
                    this.submit();
                }
            });
        });
        
        // Auto-calculate due date when payment terms change
        document.getElementById('payment_terms').addEventListener('change', function() {
            const invoiceDate = new Date(document.getElementById('invoice_date').value);
            const paymentTerms = parseInt(this.value) || 0;
            const dueDate = new Date(invoiceDate.getTime() + (paymentTerms * 24 * 60 * 60 * 1000));
            
            document.getElementById('due_date').value = dueDate.toISOString().split('T')[0];
        });
        
        // Auto-calculate due date when invoice date changes
        document.getElementById('invoice_date').addEventListener('change', function() {
            const invoiceDate = new Date(this.value);
            const paymentTerms = parseInt(document.getElementById('payment_terms').value) || 0;
            const dueDate = new Date(invoiceDate.getTime() + (paymentTerms * 24 * 60 * 60 * 1000));
            
            document.getElementById('due_date').value = dueDate.toISOString().split('T')[0];
        });
        
        // Initialize tooltips
        document.addEventListener('DOMContentLoaded', function() {
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
            var tooltipList = tooltipTriggerList.map(function(tooltipTriggerEl) {
                return new bootstrap.Tooltip(tooltipTriggerEl);
            });
        });
    </script>

    <!-- App js -->
    <script src="assets/js/app.js"></script>
</body>
</html>