<?php
include 'layouts/session.php';
include 'layouts/main.php';
include 'layouts/dbconn.php';

// Check if customer ID is provided
$customer_id = isset($_GET['customer']) ? intval($_GET['customer']) : 0;
$file_number = isset($_GET['file_number']) ? trim($_GET['file_number']) : '';

// Fetch customer data if customer ID is provided
$customer = null;
if ($customer_id > 0) {
    $customerQuery = "SELECT * FROM customers WHERE customer_id = ?";
    $customerStmt = $conn->prepare($customerQuery);
    $customerStmt->bind_param("i", $customer_id);
    $customerStmt->execute();
    $customerResult = $customerStmt->get_result();
    
    if ($customerResult->num_rows > 0) {
        $customer = $customerResult->fetch_assoc();
    } else {
        $_SESSION['error_message'] = "Customer not found";
        header("Location: all_customers.php");
        exit();
    }
}

// Fetch shipment data if file number is provided
$shipment = null;
if (!empty($file_number)) {
    $shipmentQuery = "SELECT * FROM files WHERE file_number = ?";
    $shipmentStmt = $conn->prepare($shipmentQuery);
    $shipmentStmt->bind_param("s", $file_number);
    $shipmentStmt->execute();
    $shipmentResult = $shipmentStmt->get_result();
    
    if ($shipmentResult->num_rows > 0) {
        $shipment = $shipmentResult->fetch_assoc();
        // If customer ID was not provided, get it from the shipment
        if ($customer_id == 0 && !empty($shipment['customer'])) {
            $customer_id = $shipment['customer'];
            
            // Fetch customer data
            $customerQuery = "SELECT * FROM customers WHERE customer_id = ?";
            $customerStmt = $conn->prepare($customerQuery);
            $customerStmt->bind_param("i", $customer_id);
            $customerStmt->execute();
            $customerResult = $customerStmt->get_result();
            
            if ($customerResult->num_rows > 0) {
                $customer = $customerResult->fetch_assoc();
            }
        }
    } else {
        $_SESSION['error_message'] = "Shipment not found";
        header("Location: index.php");
        exit();
    }
}

// Get all customers for the dropdown
$allCustomersQuery = "SELECT customer_id, first_name, last_name FROM customers WHERE status = 1 ORDER BY first_name, last_name";
$allCustomersResult = $conn->query($allCustomersQuery);

// Get the customer's shipments for the dropdown
$shipments = [];
if ($customer_id > 0) {
    $shipmentsQuery = "SELECT file_number, destination, created_date FROM files WHERE customer = ? ORDER BY created_date DESC";
    $shipmentsStmt = $conn->prepare($shipmentsQuery);
    $shipmentsStmt->bind_param("i", $customer_id);
    $shipmentsStmt->execute();
    $shipmentsResult = $shipmentsStmt->get_result();
    
    while ($row = $shipmentsResult->fetch_assoc()) {
        $shipments[] = $row;
    }
}

// Generate a new invoice number
$currentYear = date('Y');
$currentMonth = date('m');

$invoiceQuery = "SELECT MAX(CAST(SUBSTRING_INDEX(invoice_number, '/', -1) AS UNSIGNED)) as max_num 
                FROM invoices 
                WHERE invoice_number LIKE 'INV/$currentYear$currentMonth/%'";
$invoiceResult = $conn->query($invoiceQuery);
$invoiceRow = $invoiceResult->fetch_assoc();
$nextInvoiceNum = 1;

if ($invoiceRow && !is_null($invoiceRow['max_num'])) {
    $nextInvoiceNum = $invoiceRow['max_num'] + 1;
}

$newInvoiceNumber = "INV/$currentYear$currentMonth/" . str_pad($nextInvoiceNum, 4, '0', STR_PAD_LEFT);

// Process form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Validate required fields
    if (empty($_POST['customer_id']) || empty($_POST['invoice_number']) || empty($_POST['issue_date']) || empty($_POST['due_date'])) {
        $_SESSION['error_message'] = "Please fill in all required fields";
    } else {
        $postCustomerId = intval($_POST['customer_id']);
        $invoiceNumber = trim($_POST['invoice_number']);
        $fileNumber = !empty($_POST['file_number']) ? trim($_POST['file_number']) : null;
        $issueDate = $_POST['issue_date'];
        $dueDate = $_POST['due_date'];
        $notes = trim($_POST['notes']);
        $status = 'pending';
        
        // Validate invoice items
        $items = [];
        $totalAmount = 0;
        
        if (isset($_POST['description']) && is_array($_POST['description'])) {
            for ($i = 0; $i < count($_POST['description']); $i++) {
                $description = trim($_POST['description'][$i]);
                $quantity = floatval($_POST['quantity'][$i]);
                $price = floatval($_POST['price'][$i]);
                
                if (!empty($description) && $quantity > 0 && $price > 0) {
                    $amount = $quantity * $price;
                    $totalAmount += $amount;
                    
                    $items[] = [
                        'description' => $description,
                        'quantity' => $quantity,
                        'price' => $price,
                        'amount' => $amount
                    ];
                }
            }
        }
        
        if (empty($items)) {
            $_SESSION['error_message'] = "Please add at least one invoice item";
        } else {
            // Check if invoice number already exists
            $checkQuery = "SELECT invoice_id FROM invoices WHERE invoice_number = ?";
            $checkStmt = $conn->prepare($checkQuery);
            $checkStmt->bind_param("s", $invoiceNumber);
            $checkStmt->execute();
            $checkResult = $checkStmt->get_result();
            
            if ($checkResult->num_rows > 0) {
                $_SESSION['error_message'] = "Invoice number already exists";
            } else {
                // Start transaction
                $conn->begin_transaction();
                
                try {
                    // Insert invoice record
                    $userId = $_SESSION['user_id'];
                    $insertQuery = "INSERT INTO invoices (user_id, customer_id, invoice_number, file_number, total_amount, name, description, quantity, price, issue_date, due_date, notes, status) 
                                   VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    
                    // We'll use the first item for the main invoice record
                    $firstItem = $items[0];
                    $insertStmt = $conn->prepare($insertQuery);
                    $insertStmt->bind_param("iissdsdiissss", 
                                           $userId, 
                                           $postCustomerId, 
                                           $invoiceNumber, 
                                           $fileNumber, 
                                           $totalAmount,
                                           $firstItem['description'],
                                           $firstItem['description'],
                                           $firstItem['quantity'],
                                           $firstItem['price'],
                                           $issueDate,
                                           $dueDate,
                                           $notes,
                                           $status);
                    
                    if ($insertStmt->execute()) {
                        $invoiceId = $insertStmt->insert_id;
                        
                        // Insert invoice items if more than one
                        if (count($items) > 1) {
                            // Create invoice_items table if it doesn't exist
                            $createTableQuery = "CREATE TABLE IF NOT EXISTS invoice_items (
                                item_id INT AUTO_INCREMENT PRIMARY KEY,
                                invoice_id INT NOT NULL,
                                description VARCHAR(255) NOT NULL,
                                quantity INT NOT NULL,
                                price DECIMAL(10,2) NOT NULL,
                                amount DECIMAL(10,2) NOT NULL,
                                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                                FOREIGN KEY (invoice_id) REFERENCES invoices(invoice_id) ON DELETE CASCADE
                            )";
                            
                            $conn->query($createTableQuery);
                            
                            // Skip the first item as it's already in the main invoice
                            for ($i = 1; $i < count($items); $i++) {
                                $item = $items[$i];
                                $itemQuery = "INSERT INTO invoice_items (invoice_id, description, quantity, price, amount) 
                                             VALUES (?, ?, ?, ?, ?)";
                                $itemStmt = $conn->prepare($itemQuery);
                                $itemStmt->bind_param("isidi", 
                                                    $invoiceId, 
                                                    $item['description'],
                                                    $item['quantity'],
                                                    $item['price'],
                                                    $item['amount']);
                                $itemStmt->execute();
                            }
                        }
                        
                        // Update customer invoice count
                        $updateCountQuery = "UPDATE customers SET invoices_count = invoices_count + 1 WHERE customer_id = ?";
                        $updateCountStmt = $conn->prepare($updateCountQuery);
                        $updateCountStmt->bind_param("i", $postCustomerId);
                        $updateCountStmt->execute();
                        
                        // Get the default currency from settings
                        $currencyQuery = "SELECT setting_value FROM settings WHERE setting_key = 'default_currency'";
                        $currencyResult = $conn->query($currencyQuery);
                        $currency = '$'; // Default fallback
                        
                        if ($currencyResult && $currencyResult->num_rows > 0) {
                            $currencyRow = $currencyResult->fetch_assoc();
                            $currency = $currencyRow['setting_value'];
                        }
                        
                        // Record financial transaction
                        $transactionQuery = "INSERT INTO debt_transactions (customer_id, transaction_date, amount, currency, transaction_type, reference_id, notes, user_id) 
                                           VALUES (?, ?, ?, ?, 'invoice', ?, ?, ?)";
                        $transactionStmt = $conn->prepare($transactionQuery);
                        $transactionDate = date('Y-m-d');
                        $transactionStmt->bind_param("idssssi", 
                                                  $postCustomerId, 
                                                  $transactionDate,
                                                  $totalAmount,
                                                  $currency,
                                                  $invoiceNumber,
                                                  $notes,
                                                  $userId);
                        $transactionStmt->execute();
                        
                        // Update client debt
                        $debtQuery = "SELECT * FROM client_debts WHERE customer_id = ? AND currency = ?";
                        $debtStmt = $conn->prepare($debtQuery);
                        $debtStmt->bind_param("is", $postCustomerId, $currency);
                        $debtStmt->execute();
                        $debtResult = $debtStmt->get_result();
                        
                        if ($debtResult->num_rows > 0) {
                            $updateDebtQuery = "UPDATE client_debts SET total_debt = total_debt + ?, last_updated = NOW() WHERE customer_id = ? AND currency = ?";
                            $updateDebtStmt = $conn->prepare($updateDebtQuery);
                            $updateDebtStmt->bind_param("dis", $totalAmount, $postCustomerId, $currency);
                            $updateDebtStmt->execute();
                        } else {
                            $insertDebtQuery = "INSERT INTO client_debts (customer_id, currency, total_debt) VALUES (?, ?, ?)";
                            $insertDebtStmt = $conn->prepare($insertDebtQuery);
                            $insertDebtStmt->bind_param("isd", $postCustomerId, $currency, $totalAmount);
                            $insertDebtStmt->execute();
                        }
                        
                        // Commit transaction
                        $conn->commit();
                        
                        $_SESSION['success_message'] = "Invoice created successfully: $invoiceNumber";
                        header("Location: view_invoice.php?id=$invoiceId");
                        exit();
                    } else {
                        throw new Exception("Error creating invoice: " . $insertStmt->error);
                    }
                } catch (Exception $e) {
                    // Rollback transaction on error
                    $conn->rollback();
                    $_SESSION['error_message'] = $e->getMessage();
                }
            }
        }
    }
}
?>

<!doctype html>
<html lang="en" data-layout="vertical" data-topbar="light" data-sidebar="dark" data-sidebar-size="lg" data-sidebar-image="none" data-preloader="disable">

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Create Invoice')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <!-- Flatpickr -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
    <style>
        .invoice-item {
            transition: all 0.3s ease;
            border-radius: 4px;
            border: 1px solid #eff0f2;
        }
        
        .invoice-item:hover {
            border-color: #ced4da;
        }
        
        .remove-item {
            transition: all 0.3s ease;
        }
        
        .remove-item:hover {
            color: #dc3545;
            cursor: pointer;
        }
        
        .table-total tr:first-child td {
            border-top: 1px solid #eff0f2;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    <?php includeFileWithVariables('layouts/page-title.php', array('pagetitle' => 'Invoices', 'title' => 'Create New Invoice')); ?>

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

                    <form action="" method="POST" id="invoiceForm">
                        <div class="row">
                            <!-- Invoice Details -->
                            <div class="col-lg-8">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Invoice Details</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="invoice_number" class="form-label">Invoice Number <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control" id="invoice_number" name="invoice_number" value="<?php echo htmlspecialchars($newInvoiceNumber); ?>" required>
                                            </div>
                                            <div class="col-md-6">
                                                <label for="customer_id" class="form-label">Customer <span class="text-danger">*</span></label>
                                                <select class="form-control select2" id="customer_id" name="customer_id" required>
                                                    <option value="">Select Customer</option>
                                                    <?php while ($custRow = $allCustomersResult->fetch_assoc()): 
                                                        $custName = trim($custRow['first_name'] . ' ' . $custRow['last_name']);
                                                        if (empty($custName)) {
                                                            $custName = "Customer #" . $custRow['customer_id'];
                                                        }
                                                        $selected = ($customer && $custRow['customer_id'] == $customer['customer_id']) ? 'selected' : '';
                                                    ?>
                                                    <option value="<?php echo $custRow['customer_id']; ?>" <?php echo $selected; ?>>
                                                        <?php echo htmlspecialchars($custName); ?>
                                                    </option>
                                                    <?php endwhile; ?>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="row mb-3">
                                            <div class="col-md-6">
                                                <label for="file_number" class="form-label">Related Shipment (Optional)</label>
                                                <select class="form-control select2" id="file_number" name="file_number">
                                                    <option value="">Select Shipment</option>
                                                    <?php foreach ($shipments as $shipmentItem): 
                                                        $dateCreated = new DateTime($shipmentItem['created_date']);
                                                        $formattedDate = $dateCreated->format('M d, Y');
                                                        $selected = ($shipment && $shipmentItem['file_number'] == $shipment['file_number']) ? 'selected' : '';
                                                    ?>
                                                    <option value="<?php echo $shipmentItem['file_number']; ?>" <?php echo $selected; ?>>
                                                        <?php echo htmlspecialchars($shipmentItem['file_number'] . ' - ' . $shipmentItem['destination'] . ' (' . $formattedDate . ')'); ?>
                                                    </option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </div>
                                            <div class="col-md-3">
                                                <label for="issue_date" class="form-label">Issue Date <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control flatpickr-input" id="issue_date" name="issue_date" placeholder="Select date" value="<?php echo date('Y-m-d'); ?>" required>
                                            </div>
                                            <div class="col-md-3">
                                                <label for="due_date" class="form-label">Due Date <span class="text-danger">*</span></label>
                                                <input type="text" class="form-control flatpickr-input" id="due_date" name="due_date" placeholder="Select date" value="<?php echo date('Y-m-d', strtotime('+30 days')); ?>" required>
                                            </div>
                                        </div>
                                        
                                        <div class="mb-3">
                                            <label for="notes" class="form-label">Notes</label>
                                            <textarea class="form-control" id="notes" name="notes" rows="3" placeholder="Add any notes or payment instructions"></textarea>
                                        </div>
                                    </div>
                                </div>
                                
                                <!-- Invoice Items -->
                                <div class="card">
                                    <div class="card-header d-flex justify-content-between align-items-center">
                                        <h5 class="card-title mb-0">Invoice Items</h5>
                                        <button type="button" class="btn btn-primary btn-sm" id="addItemBtn">
                                            <i class="ri-add-line align-middle me-1"></i> Add Item
                                        </button>
                                    </div>
                                    <div class="card-body">
                                        <div id="invoice-items">
                                            <!-- Default empty item -->
                                            <div class="invoice-item p-3 mb-3">
                                                <div class="row mb-3">
                                                    <div class="col-md-12">
                                                        <label class="form-label">Description <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control item-description" name="description[]" placeholder="Item description" required>
                                                    </div>
                                                </div>
                                                <div class="row">
                                                    <div class="col-md-4">
                                                        <label class="form-label">Quantity <span class="text-danger">*</span></label>
                                                        <input type="number" class="form-control item-quantity" name="quantity[]" placeholder="Quantity" value="1" min="1" required>
                                                    </div>
                                                    <div class="col-md-4">
                                                        <label class="form-label">Unit Price <span class="text-danger">*</span></label>
                                                        <input type="number" class="form-control item-price" name="price[]" placeholder="0.00" min="0" step="0.01" required>
                                                    </div>
                                                    <div class="col-md-3">
                                                        <label class="form-label">Amount</label>
                                                        <input type="text" class="form-control item-amount" placeholder="0.00" readonly>
                                                    </div>
                                                    <div class="col-md-1 d-flex align-items-end">
                                                        <div class="remove-item text-center d-flex align-items-center justify-content-center" style="height: 38px;">
                                                            <i class="ri-delete-bin-line fs-20"></i>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Customer Info and Total -->
                            <div class="col-lg-4">
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Customer Information</h5>
                                    </div>
                                    <div class="card-body">
                                        <div id="customer-info">
                                            <?php if ($customer): ?>
                                            <h6 class="mb-2"><?php echo htmlspecialchars(trim($customer['first_name'] . ' ' . $customer['last_name'])); ?></h6>
                                            <?php if (!empty($customer['address'])): ?>
                                            <p class="mb-1"><?php echo nl2br(htmlspecialchars($customer['address'])); ?></p>
                                            <?php endif; ?>
                                            <?php if (!empty($customer['city']) || !empty($customer['postal_code'])): ?>
                                            <p class="mb-1">
                                                <?php 
                                                echo htmlspecialchars($customer['city'] ?: ''); 
                                                if (!empty($customer['city']) && !empty($customer['postal_code'])) {
                                                    echo ', ';
                                                }
                                                echo htmlspecialchars($customer['postal_code'] ?: '');
                                                ?>
                                            </p>
                                            <?php endif; ?>
                                            <?php if (!empty($customer['country'])): ?>
                                            <p class="mb-1"><?php echo htmlspecialchars($customer['country']); ?></p>
                                            <?php endif; ?>
                                            <?php if (!empty($customer['phone_number'])): ?>
                                            <p class="mb-1">Phone: <?php echo htmlspecialchars($customer['phone_number']); ?></p>
                                            <?php endif; ?>
                                            <?php if (!empty($customer['email'])): ?>
                                            <p class="mb-1">Email: <?php echo htmlspecialchars($customer['email']); ?></p>
                                            <?php endif; ?>
                                            <?php else: ?>
                                            <div class="text-center py-3">
                                                <div class="avatar-sm mx-auto mb-3">
                                                    <div class="avatar-title bg-light text-secondary rounded-circle">
                                                        <i class="ri-user-3-line fs-24"></i>
                                                    </div>
                                                </div>
                                                <h6 class="text-muted mb-0">Select a customer to view details</h6>
                                            </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>
                                
                                <div class="card">
                                    <div class="card-header">
                                        <h5 class="card-title mb-0">Invoice Summary</h5>
                                    </div>
                                    <div class="card-body">
                                        <table class="table table-borderless table-sm table-total">
                                            <tbody>
                                                <tr>
                                                    <td class="fw-medium">Subtotal</td>
                                                    <td class="text-end" id="subtotal">$0.00</td>
                                                </tr>
                                                <tr>
                                                    <td class="fw-medium">Tax (0%)</td>
                                                    <td class="text-end" id="tax">$0.00</td>
                                                </tr>
                                                <tr class="fw-bold">
                                                    <td>Total</td>
                                                    <td class="text-end" id="total">$0.00</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                                
                                <div class="text-end mt-4">
                                    <a href="<?php echo !empty($customer) ? 'customer_profile.php?id=' . $customer['customer_id'] : 'all_customers.php'; ?>" class="btn btn-light me-2">Cancel</a>
                                    <button type="submit" class="btn btn-primary">Create Invoice</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <!-- Plugins -->
    <script src="https://cdn.jsdelivr.net/npm/flatpickr"></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() {
        // Initialize date pickers
        flatpickr("#issue_date", {
            dateFormat: "Y-m-d",
            maxDate: "today"
        });
        
        flatpickr("#due_date", {
            dateFormat: "Y-m-d",
            minDate: "today"
        });
        
        // Initialize select2
        $('.select2').select2({
            width: '100%'
        });
        
        // Function to calculate item amount
        function calculateItemAmount(itemEl) {
            const quantity = parseFloat(itemEl.querySelector('.item-quantity').value) || 0;
            const price = parseFloat(itemEl.querySelector('.item-price').value) || 0;
            const amount = quantity * price;
            
            itemEl.querySelector('.item-amount').value = amount.toFixed(2);
            
            updateTotals();
        }
        
        // Function to update invoice totals
        function updateTotals() {
            let subtotal = 0;
            
            document.querySelectorAll('.invoice-item').forEach(item => {
                const amount = parseFloat(item.querySelector('.item-amount').value) || 0;
                subtotal += amount;
            });
            
            const tax = 0; // We're not calculating tax for now
            const total = subtotal + tax;
            
            // Get currency symbol from settings
            const currencySymbol = '$'; // Default currency symbol
            
            document.getElementById('subtotal').textContent = currencySymbol + ' ' + subtotal.toFixed(2);
            document.getElementById('tax').textContent = currencySymbol + ' ' + tax.toFixed(2);
            document.getElementById('total').textContent = currencySymbol + ' ' + total.toFixed(2);
        }
        
        // Initialize calculations for default item
        document.querySelectorAll('.invoice-item').forEach(item => {
            calculateItemAmount(item);
            
            // Add event listeners to quantity and price inputs
            item.querySelector('.item-quantity').addEventListener('input', function() {
                calculateItemAmount(item);
            });
            
            item.querySelector('.item-price').addEventListener('input', function() {
                calculateItemAmount(item);
            });
            
            // Add event listener to remove button
            item.querySelector('.remove-item').addEventListener('click', function() {
                if (document.querySelectorAll('.invoice-item').length > 1) {
                    item.remove();
                    updateTotals();
                } else {
                    alert('At least one item is required.');
                }
            });
        });
        
        // Add new item button
        document.getElementById('addItemBtn').addEventListener('click', function() {
            const items = document.getElementById('invoice-items');
            const newItem = document.querySelector('.invoice-item').cloneNode(true);
            
            // Clear input values
            newItem.querySelector('.item-description').value = '';
            newItem.querySelector('.item-quantity').value = '1';
            newItem.querySelector('.item-price').value = '';
            newItem.querySelector('.item-amount').value = '0.00';
            
            // Add event listeners
            newItem.querySelector('.item-quantity').addEventListener('input', function() {
                calculateItemAmount(newItem);
            });
            
            newItem.querySelector('.item-price').addEventListener('input', function() {
                calculateItemAmount(newItem);
            });
            
            newItem.querySelector('.remove-item').addEventListener('click', function() {
                newItem.remove();
                updateTotals();
            });
            
            items.appendChild(newItem);
        });
        
        // Customer change event
        document.getElementById('customer_id').addEventListener('change', function() {
            const customerId = this.value;
            
            if (customerId) {
                // Fetch customer info via AJAX
                fetch('get_customer_info.php?id=' + customerId)
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // Update customer info section
                            let html = `<h6 class="mb-2">${data.name}</h6>`;
                            
                            if (data.address) {
                                html += `<p class="mb-1">${data.address}</p>`;
                            }
                            
                            if (data.city || data.postal_code) {
                                html += `<p class="mb-1">`;
                                if (data.city) html += data.city;
                                if (data.city && data.postal_code) html += ', ';
                                if (data.postal_code) html += data.postal_code;
                                html += `</p>`;
                            }
                            
                            if (data.country) {
                                html += `<p class="mb-1">${data.country}</p>`;
                            }
                            
                            if (data.phone) {
                                html += `<p class="mb-1">Phone: ${data.phone}</p>`;
                            }
                            
                            if (data.email) {
                                html += `<p class="mb-1">Email: ${data.email}</p>`;
                            }
                            
                            document.getElementById('customer-info').innerHTML = html;
                            
                            // Update shipments dropdown
                            const fileSelect = document.getElementById('file_number');
                            fileSelect.innerHTML = '<option value="">Select Shipment</option>';
                            
                            if (data.shipments && data.shipments.length > 0) {
                                data.shipments.forEach(shipment => {
                                    const option = document.createElement('option');
                                    option.value = shipment.file_number;
                                    option.textContent = `${shipment.file_number} - ${shipment.destination} (${shipment.date})`;
                                    fileSelect.appendChild(option);
                                });
                            }
                        }
                    })
                    .catch(error => {
                        console.error('Error fetching customer info:', error);
                    });
            } else {
                // Clear customer info section
                document.getElementById('customer-info').innerHTML = `
                    <div class="text-center py-3">
                        <div class="avatar-sm mx-auto mb-3">
                            <div class="avatar-title bg-light text-secondary rounded-circle">
                                <i class="ri-user-3-line fs-24"></i>
                            </div>
                        </div>
                        <h6 class="text-muted mb-0">Select a customer to view details</h6>
                    </div>
                `;
                
                // Clear shipments dropdown
                document.getElementById('file_number').innerHTML = '<option value="">Select Shipment</option>';
            }
        });
        
        // Form submission validation
        document.getElementById('invoiceForm').addEventListener('submit', function(e) {
            const items = document.querySelectorAll('.invoice-item');
            let valid = true;
            
            items.forEach(item => {
                const description = item.querySelector('.item-description').value.trim();
                const quantity = parseFloat(item.querySelector('.item-quantity').value) || 0;
                const price = parseFloat(item.querySelector('.item-price').value) || 0;
                
                if (!description || quantity <= 0 || price <= 0) {
                    valid = false;
                }
            });
            
            if (!valid) {
                e.preventDefault();
                alert('Please ensure all items have a description, quantity, and price.');
            }
        });
    });
    </script>

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