<?php
// Assumes $conn (database connection) and $_SESSION['user_id'] are available.
// NOTE: Ensure 'config/db_connection.php' is properly included in admin_dashboard.php 
// and $conn is a valid mysqli connection object.

$status_message = '';
$user_id = $_SESSION['user_id'] ?? 1; // Default to ID 1 for safety
$generated_content = null;

// --- Fixed Invoice/Letterpad Components ---
$company_name = "Cyberlog";
$company_address = "1/6, Block: New-C, Mirpur-1, Dhaka-1216";
$company_email = "info@cyberlog.com.bd";
$company_website = "www.cyberlog.com.bd";
$company_phone = "+013576990884"; 

// Image/Logo Paths 
$logo_path = "Cyberlog Blue Logo Transparent.png"; 
$signature_path = "Signature of Hridoy Mustofa.png"; 

// Fixed Billing Details 
$bill_to_company = "Cyberlog Ltd.";
$bill_to_details = "1/6, Block: New- C, Mirpur-1, Dhaka-1216, Bangladesh<br>
Phone: {$company_phone}<br>
Email: {$company_email}";


// --- FUNCTION: Builds the Expense List HTML ---
function get_expense_list_html(
    $invoice_no, 
    $invoice_date, 
    $items_data, 
    $subtotal, 
    $advance_payment, 
    $grand_total
) {
    global $company_name, $company_address, $company_email, $company_website, $bill_to_details, $bill_to_company, $logo_path, $signature_path;
    
    // Header for the expense list (Invoice)
    $header_html = "
        <div style='display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 20px;'>
            <div style='flex-grow: 1;'>
                <img src='{$logo_path}' alt='{$company_name} Logo' style='max-width: 180px; height: auto; margin-bottom: 10px; filter: drop-shadow(0 0 1px #008000);'>
                <div style='border-bottom: 4px solid #008000; width: 100%; margin-top: -10px;'>&nbsp;</div>
            </div>
            <div style='text-align: right; font-size: 12px; color: #555;'>
                <p style='margin: 0 0 5px 0;'>{$company_address} <span style='color: #E74C3C;'>&#x1F4CD;</span></p>
                <p style='margin: 0 0 5px 0;'>{$company_email} <span style='color: #E74C3C;'>&#x2709;</span></p>
                <p style='margin: 0;'>{$company_website} <span style='color: #E74C3C;'>&#x1F310;</span></p>
            </div>
        </div>
    ";

    // Main Invoice Details Section
    $details_html = "
        <div style='margin-bottom: 30px; padding: 15px; background-color: #f0f8ff; border: 1px solid #dcdcdc; display: flex; justify-content: space-between; align-items: flex-start;'>
            <div style='width: 45%;'>
                <strong style='color: #E74C3C;'>Invoice No:</strong> <span style='color: #333;'>{$invoice_no}</span>
                <hr style='border: 0; border-top: 1px solid #ccc; margin: 10px 0;'>
                <p style='font-size: 14px; margin-bottom: 5px;'><strong style='color: #2c3e50;'>Bill To:</strong> {$bill_to_company}</p>
                <p style='font-size: 12px; line-height: 1.5; margin: 0; padding-left: 10px;'>{$bill_to_details}</p>
            </div>
             <div style='width: 45%; text-align: right;'>
                <strong style='color: #E74C3C;'>Invoice Date:</strong> <span style='color: #333;'>{$invoice_date}</span>
            </div>
        </div>
    ";
    
    // Expense Items Table
    $items_table_html = "
        <table style='width: 100%; border-collapse: collapse; margin-bottom: 40px;'>
            <thead>
                <tr style='background-color: #f2f2f2;'>
                    <th style='border: 1px solid #333; padding: 8px; width: 5%; text-align: center;'>#</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 45%; text-align: left;'>Description</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 15%; text-align: right;'>Unit Price (BDT)</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 10%; text-align: center;'>Quantity</th>
                    <th style='border: 1px solid #333; padding: 8px; width: 25%; text-align: right;'>Total (BDT)</th>
                </tr>
            </thead>
            <tbody>
    ";
    
    $item_counter = 1;
    foreach ($items_data as $item) {
        $items_table_html .= "
            <tr>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>{$item_counter}</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>".htmlspecialchars($item['description'])."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($item['unit_price'], 2)."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>".htmlspecialchars($item['quantity'])."</td>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($item['total_bdt'], 2)."</td>
            </tr>
        ";
        $item_counter++;
    }
    
    // Add up to 6 rows for structure
    for ($i = $item_counter; $i <= 6; $i++) {
         $items_table_html .= "
            <tr>
                <td style='border: 1px solid #ccc; padding: 8px; text-align: center;'>{$i}</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
                <td style='border: 1px solid #ccc; padding: 8px;'>&nbsp;</td>
            </tr>
        ";
    }

    $items_table_html .= "
            </tbody>
        </table>
    ";
    
    // Summary and Signature Section
    $summary_and_signature_html = "
        <div style='display: flex; justify-content: space-between; align-items: flex-end;'>
            
            <div style='width: 35%; border-top: 2px solid #E74C3C; padding: 10px 0; text-align: center;'>
                <img src='{$signature_path}' alt='Signature' style='max-width: 100px; height: auto; margin-bottom: 5px; opacity: 0.8;'>
                <p style='margin: 5px 0; font-weight: bold; border-top: 1px solid #333; display: inline-block; padding-top: 5px;'>Hridoy Mustofa</p>
                <p style='margin: 0; font-size: 12px;'>Founder & CEO</p>
                <p style='margin: 0; font-size: 14px; font-weight: bold; color: #008000;'>{$company_name}</p>
            </div>

            <div style='width: 40%;'>
                <table style='width: 100%; border-collapse: collapse; margin-left: auto; font-size: 14px;'>
                    <tr>
                        <td style='border: 1px solid #ccc; padding: 8px; font-weight: bold;'>Subtotal</td>
                        <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($subtotal, 2)." BDT</td>
                    </tr>
                    <tr>
                        <td style='border: 1px solid #ccc; padding: 8px; font-weight: bold;'>Advance Payment (50%)</td>
                        <td style='border: 1px solid #ccc; padding: 8px; text-align: right;'>".number_format($advance_payment, 2)." BDT</td>
                    </tr>
                    <tr>
                        <td style='border: 1px solid #333; padding: 8px; font-weight: bold; background-color: #e0f2f1;'>Grand Total</td>
                        <td style='border: 1px solid #333; padding: 8px; text-align: right; font-weight: bold; background-color: #e0f2f1;'>".number_format($grand_total, 2)." BDT</td>
                    </tr>
                </table>
            </div>
        </div>
        
        <div style='width: 100%; margin-top: 40px; border-bottom: 10px solid #008000;'>&nbsp;</div>
    ";
    
    return "
        <div class='letter-page'>
            {$header_html}
            {$details_html}
            {$items_table_html}
            {$summary_and_signature_html}
        </div>
    ";
}


// --- NEW: Logic to load a specific Expense List for viewing ---
if (isset($_GET['view_expense_id']) && is_numeric($_GET['view_expense_id'])) {
    $view_id = (int)$_GET['view_expense_id'];
    
    // 1. Fetch Main Expense Data
    $sql_main = "SELECT * FROM expense_lists WHERE expense_id = ? AND created_by = ?";
    if ($stmt_main = $conn->prepare($sql_main)) {
        $stmt_main->bind_param("ii", $view_id, $user_id);
        $stmt_main->execute();
        $result_main = $stmt_main->get_result();
        $expense_record = $result_main->fetch_assoc();
        $stmt_main->close();

        if ($expense_record) {
            // 2. Fetch Line Items
            $sql_items = "SELECT description, unit_price, quantity, total_bdt FROM expense_list_items WHERE expense_id = ?";
            $items_data = [];
            if ($stmt_items = $conn->prepare($sql_items)) {
                $stmt_items->bind_param("i", $view_id);
                $stmt_items->execute();
                $result_items = $stmt_items->get_result();
                while ($row = $result_items->fetch_assoc()) {
                    $items_data[] = $row;
                }
                $stmt_items->close();
            }

            // 3. Generate HTML content for the viewer
            $generated_content = get_expense_list_html(
                htmlspecialchars($expense_record['invoice_no']), 
                date('F j, Y', strtotime($expense_record['invoice_date'])), 
                $items_data, 
                $expense_record['subtotal'], 
                $expense_record['advance_payment'], 
                $expense_record['grand_total']
            );
            
            $status_message = "<div class='alert alert-info'>Viewing Expense List: **{$expense_record['invoice_no']}** from ".date('M j, Y', strtotime($expense_record['invoice_date']))."</div>";
        } else {
             $status_message = "<div class='alert alert-error'>Expense record not found or you are unauthorized to view it.</div>";
        }
    }
}


// --- Logic to Handle Form Submission (Generate & Save) ---
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['generate_expense_list'])) {
    // 1. Sanitize & Prepare Inputs (Same as previous response)
    // ... (rest of the form submission logic for saving to DB and setting $generated_content) ...
    
    $invoice_no = $conn->real_escape_string($_POST['invoice_no'] ?? '');
    $invoice_date = $conn->real_escape_string($_POST['invoice_date'] ?? date('Y-m-d'));
    
    $descriptions = $_POST['description'] ?? [];
    $unit_prices = $_POST['unit_price'] ?? [];
    $quantities = $_POST['quantity'] ?? [];
    $advance = (float)($_POST['advance_payment'] ?? 0);

    $items_data = [];
    $subtotal = 0.00;
    
    foreach ($descriptions as $i => $desc) {
        $desc = trim($conn->real_escape_string($desc));
        $u_price = (float)($unit_prices[$i] ?? 0);
        $qty = (int)($quantities[$i] ?? 1);
        
        if (!empty($desc) && $u_price > 0 && $qty > 0) {
            $total = $u_price * $qty;
            $subtotal += $total;
            $items_data[] = [
                'description' => $desc,
                'unit_price' => $u_price,
                'quantity' => $qty,
                'total_bdt' => $total
            ];
        }
    }
    
    $grand_total = $subtotal - $advance;

    if (empty($items_data)) {
        $status_message = "<div class='alert alert-error'>Please add at least one expense item with a price greater than zero.</div>";
    } else {
        // --- Database Logic: Save to DB ---
        $conn->begin_transaction();
        $last_expense_id = null;
        
        $sql_main = "INSERT INTO expense_lists (invoice_no, invoice_date, bill_to_company, bill_to_address, subtotal, advance_payment, grand_total, created_by) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
        
        if ($stmt_main = $conn->prepare($sql_main)) {
            $bill_details_str = str_replace('<br>', "\n", $bill_to_details); // Store readable address
            $stmt_main->bind_param("ssssdddi", $invoice_no, $invoice_date, $bill_to_company, $bill_details_str, $subtotal, $advance, $grand_total, $user_id);
            
            if ($stmt_main->execute()) {
                $last_expense_id = $stmt_main->insert_id;
                $all_items_saved = true;
                
                $sql_items = "INSERT INTO expense_list_items (expense_id, description, unit_price, quantity, total_bdt) 
                              VALUES (?, ?, ?, ?, ?)";
                
                if ($stmt_items = $conn->prepare($sql_items)) {
                    foreach ($items_data as $item) {
                        $desc = $item['description'];
                        $u_price = $item['unit_price'];
                        $qty = $item['quantity'];
                        $total = $item['total_bdt'];
                        
                        $stmt_items->bind_param("isddb", $last_expense_id, $desc, $u_price, $qty, $total);
                        if (!$stmt_items->execute()) {
                            $all_items_saved = false;
                            break;
                        }
                    }
                    $stmt_items->close();
                } else {
                    $all_items_saved = false;
                    $status_message = "<div class='alert alert-error'>Item Database preparation error: " . $conn->error . "</div>";
                }
                
                if ($all_items_saved) {
                    $conn->commit();
                    $status_message = "<div class='alert alert-success'>Expense List **{$invoice_no}** generated and saved successfully!</div>";
                } else {
                    $conn->rollback();
                    if (empty($status_message)) {
                        $status_message = "<div class='alert alert-error'>Failed to save all expense line items. Transaction rolled back.</div>";
                    }
                }
            } else {
                $conn->rollback();
                $status_message = "<div class='alert alert-error'>Database error (Main Record): " . $stmt_main->error . "</div>";
            }
            $stmt_main->close();
        } else {
            $status_message = "<div class='alert alert-error'>Database preparation error (Main Record): " . $conn->error . "</div>";
        }

        // Generate HTML Content for the Draft Viewer if successful
        if (strpos($status_message, 'success') !== false) {
            $generated_content = get_expense_list_html(
                htmlspecialchars($invoice_no), 
                date('F j, Y', strtotime($invoice_date)), 
                $items_data, 
                $subtotal, 
                $advance, 
                $grand_total
            );
        }
    }
}
?>

<style>
	
	/* --- New Styles for Aligned Buttons --- */
	.button-group-aligned {
		margin-top: 30px;
		display: flex; 
		/* *** KEY CHANGE: Use space-between to push items to opposite ends *** */
		justify-content: space-between; 
		align-items: center; /* Vertically align items in the middle */
		width: 100%; 
	}

	.right-aligned-buttons {
		display: flex; /* Make this a flex container too */
		gap: 10px;     /* Spacing between Reset and Cancel */
	}

	.action-button {
		min-width: 150px; /* Keep this for consistent button size */
		text-align: center;
		padding: 12px 20px; 
		border: none;
		border-radius: 5px;
		cursor: pointer;
		font-size: 16px;
		text-decoration: none;
		font-weight: bold;
		transition: background-color 0.3s;
		display: inline-block; 
	}

	/* Lighter/Modern Button Colors (No change) */
	.primary-btn {
		background-color: #5d9cec; 
		color: white;
	}
	.primary-btn:hover {
		background-color: #4a89dc; 
	}

	.warning-btn {
		background-color: #ffcc66; 
		color: #333; 
	}
	.warning-btn:hover {
		background-color: #f6b300;
	}

	.secondary-btn {
		background-color: #aab8c2; 
		color: white;
	}
	.secondary-btn:hover {
		background-color: #8c97a1;
	}

	

    /* ... (Styles from previous response, including @media print) ... */
    .expense-list-table { width: 100%; border-collapse: collapse; margin-top: 15px; }
    .expense-list-table th, .expense-list-table td { border: 1px solid #ccc; padding: 8px; text-align: left; }
    .expense-list-table th { background-color: #f2f2f2; font-weight: bold; }
    .expense-list-table input[type="text"], .expense-list-table input[type="number"] { width: 100%; padding: 5px; border: 1px solid #ddd; box-sizing: border-box; }
    .total-summary { margin-top: 20px; text-align: right; }
    .total-summary label { display: inline-block; width: 200px; margin-right: 10px; font-weight: normal; text-align: left; }
    .total-summary input { width: 150px; text-align: right; display: inline-block; }
    .letter-page { padding: 20px; background: white; border: 1px solid #ddd; box-shadow: 0 0 10px rgba(0,0,0,0.05); min-height: 800px; box-sizing: border-box; }
    .alert-error { background-color: #fbecec; border: 1px solid #e74c3c; color: #e74c3c; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-success { background-color: #e8f5e9; border: 1px solid #2ecc71; color: #2ecc71; padding: 10px; border-radius: 5px; margin-bottom: 10px; }
    .alert-info { background-color: #ebf5fb; border: 1px solid #3498db; color: #3498db; padding: 10px; border-radius: 5px; margin-bottom: 10px; }

    @media print {
        body > *:not(.print-container) { display: none; }
        .print-container { display: block; width: 100%; margin: 0; padding: 0; }
        .letter-page { box-shadow: none; border: none; min-height: auto; position: relative; }
    }
</style>

<div class="form-card">
    <h3>Create New Expense List / Invoice</h3>
    <?php echo $status_message; ?>

    <form action="admin_dashboard.php?page=expense" method="post" id="expenseForm">
        
        <div style="display: flex; gap: 20px;">
            <div style="flex: 1;">
                <label for="invoice_no">Invoice No.</label>
                <input type="text" name="invoice_no" id="invoice_no" required 
                       placeholder="e.g., 10002025-007" 
                       value="<?php echo htmlspecialchars($_POST['invoice_no'] ?? ''); ?>">
            </div>
            <div style="flex: 1;">
                <label for="invoice_date">Invoice Date</label>
                <input type="date" name="invoice_date" id="invoice_date" required 
                       value="<?php echo htmlspecialchars($_POST['invoice_date'] ?? date('Y-m-d')); ?>">
            </div>
        </div>
        
        <label style="margin-top: 25px;">Expense Items (Editable List)</label>
        <table class="expense-list-table" id="expense_items_table">
            <thead>
                <tr>
                    <th style="width: 50%;">Description</th>
                    <th style="width: 15%;">Unit Price (BDT)</th>
                    <th style="width: 10%;">Qty</th>
                    <th style="width: 20%;">Total (BDT)</th>
                    <th style="width: 5%;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                // Logic to display existing or default rows (same as previous response)
                $default_rows = (isset($_POST['generate_expense_list']) && !empty($items_data)) ? count($items_data) : 3;
                $current_items = (isset($_POST['generate_expense_list']) && !empty($items_data)) ? $items_data : [];

                for ($i = 0; $i < max(3, $default_rows); $i++): 
                    $item = $current_items[$i] ?? ['description' => '', 'unit_price' => '', 'quantity' => '1', 'total_bdt' => '0.00'];
                ?>
                    <tr data-index="<?php echo $i; ?>">
                        <td><input type="text" name="description[]" value="<?php echo htmlspecialchars($item['description']); ?>" placeholder="Item description" <?php echo ($i==0) ? 'required' : ''; ?>></td>
                        <td><input type="number" name="unit_price[]" value="<?php echo htmlspecialchars($item['unit_price']); ?>" step="0.01" min="0" oninput="calculateTotal()"></td>
                        <td><input type="number" name="quantity[]" value="<?php echo htmlspecialchars($item['quantity']); ?>" min="1" oninput="calculateTotal()"></td>
                        <td><input type="text" name="item_total[]" value="<?php echo number_format($item['total_bdt'], 2); ?>" readonly></td>
                        <td><button type="button" onclick="removeRow(this)" style="background-color: #e74c3c; padding: 5px; color: white;">-</button></td>
                    </tr>
                <?php endfor; ?>
            </tbody>
        </table>

        <button type="button" onclick="addRow()" style="background-color: #2ecc71; color: white; margin-bottom: 20px;">+ Add Item</button>

        <div class="total-summary">
            <label for="subtotal_display">Subtotal (BDT)</label>
            <input type="text" id="subtotal_display" value="0.00" readonly style="font-weight: bold; margin-bottom: 10px;"><br>
            
            <label for="advance_payment">Advance Payment (50%)</label>
            <input type="number" name="advance_payment" id="advance_payment" value="<?php echo htmlspecialchars($_POST['advance_payment'] ?? '0.00'); ?>" step="0.01" min="0" oninput="calculateTotal()" style="margin-bottom: 10px;"><br>

            <label for="grand_total_display">Grand Total (BDT)</label>
            <input type="text" id="grand_total_display" value="0.00" readonly style="font-weight: bold; background-color: #ecf0f1;">
        </div>
        
        <div class="button-group-aligned">
            <button type="submit" name="generate_expense_list" class="action-button primary-btn">
                Generate & Save 
            </button>
            
            <div class="right-aligned-buttons">
                <button type="reset" class="action-button warning-btn">
                    Reset 
                </button>
                <a href="admin_dashboard.php?page=manage_templates" class="action-button secondary-btn">
                    Cancel
                </a>
            </div>
        </div>
    </form>
</div>

<?php if (isset($generated_content)): ?>
<div class="form-card print-container-wrapper" style="margin-top: 20px;">
    <h3>Generated Expense List Draft & Download</h3>
    <p>Review the draft below. Click Download to generate a printable PDF.</p>
    
    <div style="text-align: center; margin-bottom: 20px;">
        <button onclick="downloadPdf('<?php echo htmlspecialchars($_POST['invoice_no'] ?? ('Expense_Draft_' . date('Ymd'))); ?>')" 
                style="background-color: #e74c3c; color: white; padding: 10px 30px; border: none; border-radius: 5px;">
            <i class="fas fa-file-pdf"></i> Download as PDF
        </button>
        <button onclick="window.location.href='admin_dashboard.php?page=expense';" 
                style="background-color: #5d9cec; color: white; padding: 10px 30px; border: none; border-radius: 5px; margin-left: 10px;">
            + Create New
        </button>
    </div>
    
    <div id="print_area" class="print-container">
        <?php echo $generated_content; ?>
    </div>
</div>
<?php endif; ?>

<div class="form-card" style="margin-top: 40px;">
    <h3>Saved Expense List History</h3>
    
    <?php
    $sql_history = "SELECT expense_id, invoice_no, invoice_date, grand_total, created_at FROM expense_lists WHERE created_by = ? ORDER BY created_at DESC LIMIT 20";
    $expense_history = [];
    
    if ($stmt_history = $conn->prepare($sql_history)) {
        $stmt_history->bind_param("i", $user_id);
        $stmt_history->execute();
        $result_history = $stmt_history->get_result();
        while ($row = $result_history->fetch_assoc()) {
            $expense_history[] = $row;
        }
        $stmt_history->close();
    }
    
    if (empty($expense_history)):
    ?>
        <div class="alert alert-info">No expense lists found for your account yet. Create one above!</div>
    <?php else: ?>
        <table class="expense-list-table">
            <thead>
                <tr>
                    <th style="width: 5%;">ID</th>
                    <th style="width: 30%;">Invoice No.</th>
                    <th style="width: 15%;">Date</th>
                    <th style="width: 25%; text-align: right;">Total (BDT)</th>
                    <th style="width: 25%; text-align: center;">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($expense_history as $expense): ?>
                <tr>
                    <td><?php echo htmlspecialchars($expense['expense_id']); ?></td>
                    <td><?php echo htmlspecialchars($expense['invoice_no']); ?></td>
                    <td><?php echo date('M d, Y', strtotime($expense['invoice_date'])); ?></td>
                    <td style="text-align: right; font-weight: bold;"><?php echo number_format($expense['grand_total'], 2); ?></td>
                    <td style="text-align: center;">
                        <a href="admin_dashboard.php?page=expense&view_expense_id=<?php echo $expense['expense_id']; ?>" 
                           class="button" style="background-color: #3498db; padding: 5px 10px; color: white; text-decoration: none; border-radius: 3px; font-size: 0.9em;">
                            View/Download
                        </a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
    
</div>

<script>
    // --- JavaScript for Dynamic Table and Calculations (Same as previous response) ---
    document.addEventListener('DOMContentLoaded', function() {
        calculateTotal(); 
    });

    function addRow() {
        // ... (function remains the same) ...
        const tableBody = document.querySelector('#expense_items_table tbody');
        const newRow = tableBody.insertRow();
        const index = tableBody.rows.length -1;
        newRow.setAttribute('data-index', index);
        
        newRow.innerHTML = `
            <td><input type="text" name="description[]" placeholder="Item description"></td>
            <td><input type="number" name="unit_price[]" value="" step="0.01" min="0" oninput="calculateTotal()"></td>
            <td><input type="number" name="quantity[]" value="1" min="1" oninput="calculateTotal()"></td>
            <td><input type="text" name="item_total[]" value="0.00" readonly></td>
            <td><button type="button" onclick="removeRow(this)" style="background-color: #e74c3c; padding: 5px; color: white;">-</button></td>
        `;
        
        if(tableBody.rows.length > 0) {
            tableBody.rows[0].querySelector('input[name="description[]"]').setAttribute('required', 'required');
        }
    }

    function removeRow(button) {
        const tableBody = document.querySelector('#expense_items_table tbody');
        if (tableBody.rows.length > 1) { 
            button.closest('tr').remove();
            calculateTotal(); 
        } else {
            alert("You must have at least one expense item.");
        }
    }

    function calculateTotal() {
        const tableBody = document.querySelector('#expense_items_table tbody');
        let subtotal = 0.00;
        
        Array.from(tableBody.rows).forEach(row => {
            const priceInput = row.querySelector('input[name="unit_price[]"]');
            const qtyInput = row.querySelector('input[name="quantity[]"]');
            const totalInput = row.querySelector('input[name="item_total[]"]');
            
            const price = parseFloat(priceInput.value) || 0;
            const qty = parseInt(qtyInput.value) || 0;
            
            const itemTotal = price * qty;
            
            totalInput.value = itemTotal.toFixed(2);
            subtotal += itemTotal;
        });
        
        const advancePayment = parseFloat(document.getElementById('advance_payment').value) || 0.00;
        const grandTotal = subtotal - advancePayment;
        
        document.getElementById('subtotal_display').value = subtotal.toFixed(2);
        document.getElementById('grand_total_display').value = grandTotal.toFixed(2);
    }
    
    // --- PDF Download Fix (Same as previous response) ---
    function downloadPdf(filename) {
        const printContent = document.getElementById('print_area').innerHTML;
        const printWindow = window.open('', '', 'height=600,width=800');
        printWindow.document.write('<html><head><title>' + filename + '</title>');
        
        // --- IMPORTANT: Include all CSS styles necessary for a proper PDF layout ---
        printWindow.document.write(`
            <style>
                body { font-family: Arial, sans-serif; margin: 0; padding: 0; }
                .letter-page {
                    position: relative;
                    padding: 20px; 
                    background: white;
                    min-height: 100vh;
                    box-sizing: border-box;
                    width: 100%;
                }
                .letter-page img { max-width: 180px; height: auto; }
                .letter-page table { width: 100%; border-collapse: collapse; }
                .letter-page table th, .letter-page table td { 
                    border: 1px solid #333; 
                    padding: 8px; 
                    font-size: 12px;
                }
                .letter-page table thead tr { background-color: #f2f2f2; }
                .letter-page > div:last-of-type > div:first-child { 
                    border-top: 2px solid #E74C3C !important;
                }
                .letter-page * { position: relative !important; }

            </style>
        `);
        printWindow.document.write('</head><body>');
        printWindow.document.write(printContent);
        printWindow.document.write('</body></html>');
        printWindow.document.close();
        
        printWindow.focus();
        printWindow.print();
    }
</script>