<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/helpers.php';
require_once __DIR__ . '/../src/InvoiceModels.php';
require_once __DIR__ . '/../src/Client.php';
require_once __DIR__ . '/../src/Proposal.php';
require_once __DIR__ . '/../src/Contract.php';
require_once __DIR__ . '/../src/db.php';
require_once __DIR__ . '/../src/Auth/AuthManager.php';
require_once __DIR__ . '/../src/ActivityLog.php';
require_once __DIR__ . '/../src/secure_workspace.php';
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../src/Permissions/require_permission.php';

// Check permission
requirePermission('invoices_create');

use Dompdf\Dompdf;
use Dompdf\Options;

// TCPDF class for PDF generation
class InvoicePDF extends TCPDF {
    public function Header() {
        // Leave empty for custom header
    }
    
    public function Footer() {
        // Leave empty for custom footer
    }
}

// Start session for multi-step wizard state
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$errors = [];
$successMessage = $_GET['success'] ?? null;
$errorMessage = $_GET['error'] ?? null;
$currentStep = (int) ($_GET['step'] ?? 1);
$invoiceData = [];

// Load invoice data from session or URL parameter
if (isset($_GET['data'])) {
    $invoiceData = json_decode($_GET['data'], true) ?? [];
    // Save to session for persistence
    $_SESSION['invoice_data'] = $invoiceData;
} elseif (isset($_SESSION['invoice_data'])) {
    // Load from session if no URL data
    $invoiceData = $_SESSION['invoice_data'];
}

// Clear session data when starting fresh (step 1 with no data)
if ($currentStep == 1 && empty($_GET['data']) && isset($_SESSION['invoice_data'])) {
    unset($_SESSION['invoice_data']);
    $invoiceData = [];
}

// Get workspace for redirects and store in session
$workspace = $_GET['workspace'] ?? $_SESSION['workspace'] ?? 'default';
$_SESSION['workspace'] = $workspace;

// Validate that required data exists for each step
if ($currentStep > 1 && empty($invoiceData['client_id'])) {
    redirect('/invoice_create.php?workspace=' . urlencode($workspace), ['error' => 'Please select a client first']);
}

if ($currentStep > 2 && empty($invoiceData['items'])) {
    redirect('/invoice_create.php?workspace=' . urlencode($workspace) . '&step=2', ['error' => 'Please add items to the invoice first']);
}

// Get data for forms
$clients = Client::all();
$proposals = Proposal::all();
$contracts = Contract::all();
$invoiceItems = ItemTemplate::all();
$taxBrackets = TaxBracket::getActive();
$settings = InvoiceSettings::get() ?? [];

// Get company for this workspace
$pdo = getPDO();
$stmt = $pdo->prepare('SELECT * FROM companies WHERE username = ?');
$stmt->execute([$workspace]);
$company = $stmt->fetch();

if (!$company) {
    throw new Exception('Company not found for workspace: ' . $workspace);
}

// Generate preview invoice number (for display purposes only)
require_once __DIR__ . '/../src/Invoice.php';
$previewInvoiceNumber = Invoice::generateInvoiceNumber($company['id']);
$invoiceNumber = ''; // Will be generated during final save

// Recalculate tax when loading step 4 to ensure tax info is available for preview
if ($currentStep === 4 && !empty($invoiceData['items'])) {
    // Create a copy of items to avoid reference issues
    $items = $invoiceData['items'];
    $processedItems = [];
    
    // Calculate tax
    $taxTotal = 0;
    if (!($invoiceData['tax_exempt'] ?? false)) {
        if (($invoiceData['tax_method'] ?? 'per_item') === 'per_item') {
            foreach ($items as $item) {
                // Create a fresh copy of the item to avoid reference issues
                $processedItem = $item;
                
                // Initialize tax fields
                $processedItem['tax_amount'] = 0;
                $processedItem['tax_bracket_name'] = '';
                $processedItem['tax_rate'] = 0;
                
                if ($item['item_id']) {
                    try {
                        $itemId = (int)$item['item_id'];
                        if ($itemId > 0) {
                            $invoiceItem = ItemTemplate::find($itemId);
                            
                            if ($invoiceItem && $invoiceItem['is_taxable'] && $invoiceItem['default_tax_bracket_id']) {
                                $taxBracket = null;
                                foreach ($taxBrackets as $tax) {
                                    if ($tax['id'] == $invoiceItem['default_tax_bracket_id']) {
                                        $taxBracket = $tax;
                                        break;
                                    }
                                }
                                
                                if ($taxBracket) {
                                    // Calculate tax: (unit_price × quantity) × tax_rate
                                    $subtotalForTax = $item['unit_price'] * $item['quantity'];
                                    $itemTax = $subtotalForTax * ($taxBracket['rate']);
                                    
                                    // Apply discount to tax if discount is applied
                                    if (!empty($item['discount_percent']) && $item['discount_percent'] > 0) {
                                        $itemTax = $itemTax * (1 - ($item['discount_percent'] / 100));
                                    }
                                    
                                    $taxTotal += $itemTax;
                                    
                                    // Store tax information in item
                                    $processedItem['tax_amount'] = $itemTax;
                                    $processedItem['tax_bracket_name'] = $taxBracket['name'];
                                    $processedItem['tax_bracket_rate'] = $taxBracket['rate'];
                                    $processedItem['tax_bracket_id'] = $taxBracket['id'];
                                }
                            }
                        }
                    } catch (Exception $e) {
                        // Skip tax calculation for invalid items
                    }
                }
                
                $processedItems[] = $processedItem;
            }
        } elseif (!empty($invoiceData['invoice_level_tax_bracket_id'])) {
            // For invoice-level tax, keep items as they are
            $processedItems = $items;
            foreach ($taxBrackets as $tax) {
                if ($tax['id'] == $invoiceData['invoice_level_tax_bracket_id']) {
                    $taxTotal = $invoiceData['subtotal'] * $tax['rate'];
                    break;
                }
            }
        }
    } else {
        // Tax exempt - keep items as they are
        $processedItems = $items;
    }
    
    // Update the invoice data with processed items
    $invoiceData['items'] = $processedItems;
    $invoiceData['tax_total'] = $taxTotal;
    $invoiceData['total'] = $invoiceData['subtotal'] + $taxTotal;
}

// Handle POST requests
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'save_step') {
        $step = (int) ($_POST['step'] ?? 1);
        
        if ($step === 1) {
            // Save Client & Basic Info
            $clientId = (int) ($_POST['client_id'] ?? 0);
            $proposalId = (int) ($_POST['proposal_id'] ?? 0) ?: null;
            $contractId = (int) ($_POST['contract_id'] ?? 0) ?: null;
            
            if (empty($clientId)) {
                $errors[] = 'Please select a client.';
            } else {
                $invoiceData['client_id'] = $clientId;
                $invoiceData['proposal_id'] = $proposalId;
                $invoiceData['contract_id'] = $contractId;
                $invoiceData['issue_date'] = sanitizeText($_POST['invoice_date'] ?? date('Y-m-d'));
                $invoiceData['due_date'] = sanitizeText($_POST['due_date'] ?? date('Y-m-d', strtotime('+30 days')));
                $invoiceData['payment_terms'] = sanitizeText($_POST['payment_terms'] ?? $settings['default_payment_terms'] ?? 'Due on Receipt');
                $invoiceData['invoice_subject'] = sanitizeText($_POST['invoice_subject'] ?? '');
                $invoiceData['display_name_option'] = sanitizeText($_POST['display_name_option'] ?? 'client_name');
                $invoiceData['custom_display_name'] = sanitizeText($_POST['custom_display_name'] ?? '');
                
                // Get client info first
                $client = Client::find($clientId);
                $invoiceData['client_info'] = $client;
                
                // Calculate the actual display name based on form selection
                $displayName = '';
                switch ($invoiceData['display_name_option']) {
                    case 'company_name':
                        $displayName = $client['company'] ?? $client['name'];
                        break;
                    case 'custom':
                        $displayName = $invoiceData['custom_display_name'] ?: $client['name'];
                        break;
                    case 'client_name':
                    default:
                        $displayName = $client['name'];
                        break;
                }
                $invoiceData['display_name'] = $displayName;
                
                // Get proposal info if linked
                if ($proposalId) {
                    $proposal = Proposal::find($proposalId);
                    $invoiceData['proposal_info'] = $proposal;
                }
                
                // Get contract info if linked
                if ($contractId) {
                    $contract = Contract::find($contractId);
                    $invoiceData['contract_info'] = $contract;
                }
                
                if (empty($errors)) {
                    $_SESSION['invoice_data'] = $invoiceData;
                    $_SESSION['workspace'] = $workspace;
                    redirect('/invoice_create.php?workspace=' . urlencode($workspace) . '&step=2');
                }
            }
        } elseif ($step === 2) {
            // Save Items
            $invoiceData = json_decode($_POST['invoice_data'] ?? '{}', true);
            $items = $_POST['items'] ?? [];
            
            if (empty($items)) {
                $errors[] = 'Please add at least one item.';
            } else {
                $processedItems = [];
                $subtotal = 0;
                $seenItemIds = []; // Track seen item IDs to prevent duplicates
                
                foreach ($items as $itemData) {
                    if (!empty($itemData['item_name']) || !empty($itemData['description'])) {
                        // Check for duplicate inventory items
                        $itemId = $itemData['item_id'] ?? null;
                        if ($itemId && in_array($itemId, $seenItemIds)) {
                            continue; // Skip duplicate
                        }
                        if ($itemId) {
                            $seenItemIds[] = $itemId;
                        }
                        
                        $quantity = (float) ($itemData['quantity'] ?? 1);
                        $unitPrice = (float) ($itemData['unit_price'] ?? 0);
                        $discount = (float) ($itemData['discount_percent'] ?? 0);
                        
                        $lineSubtotal = $quantity * $unitPrice;
                        $discountAmount = $lineSubtotal * ($discount / 100);
                        $taxableAmount = $lineSubtotal - $discountAmount;
                        
                        $processedItems[] = [
                            'item_id' => $itemData['item_id'] ?? null,
                            'item_name' => $itemData['item_name'] ?? '',
                            'description' => $itemData['description'] ?? '',
                            'quantity' => $quantity,
                            'unit_price' => $unitPrice,
                            'discount_percent' => $discount,
                            'subtotal' => $lineSubtotal,
                            'taxable_amount' => $taxableAmount,
                            'tax_amount' => 0, // Will be calculated
                            'total' => $taxableAmount
                        ];
                        
                        $subtotal += $taxableAmount;
                    }
                }
                
                $invoiceData['items'] = $processedItems;
                $invoiceData['subtotal'] = $subtotal;
                
                if (empty($errors)) {
                    $_SESSION['invoice_data'] = $invoiceData;
                    redirect('/invoice_create.php?workspace=' . urlencode($workspace) . '&step=3');
                }
            }
        } elseif ($step === 3) {
            // Save Tax & Notes
            $invoiceData = json_decode($_POST['invoice_data'] ?? '{}', true);
            
            $invoiceData['tax_exempt'] = isset($_POST['tax_exempt']);
            $invoiceData['tax_exemption_reason'] = sanitizeText($_POST['tax_exemption_reason'] ?? '');
            $invoiceData['tax_method'] = sanitizeText($_POST['tax_method'] ?? 'per_item');
            $invoiceData['invoice_level_tax_bracket_id'] = (int) ($_POST['invoice_level_tax_bracket_id'] ?? 0) ?: null;
            $invoiceData['notes'] = sanitizeText($_POST['notes'] ?? '');
            
            // Calculate tax
            $taxTotal = 0;
            if (!$invoiceData['tax_exempt']) {
                if ($invoiceData['tax_method'] === 'per_item') {
                    foreach ($invoiceData['items'] as &$item) {
                        // Initialize tax fields
                        $item['tax_amount'] = 0;
                        $item['tax_bracket_name'] = '';
                        $item['tax_rate'] = 0;
                        
                        if ($item['item_id']) {
                            try {
                                $itemId = (int)$item['item_id'];
                                if ($itemId > 0) {
                                    $invoiceItem = ItemTemplate::find($itemId);
                                    if ($invoiceItem && $invoiceItem['is_taxable'] && $invoiceItem['default_tax_bracket_id']) {
                                        $taxBracket = null;
                                        foreach ($taxBrackets as $tax) {
                                            if ($tax['id'] == $invoiceItem['default_tax_bracket_id']) {
                                                $taxBracket = $tax;
                                                break;
                                            }
                                        }
                                        if ($taxBracket) {
                                            // Calculate tax: (unit_price × quantity) × tax_rate
                                            $subtotalForTax = $item['unit_price'] * $item['quantity'];
                                            $itemTax = $subtotalForTax * ($taxBracket['rate']);
                                            
                                            // Apply discount to tax if discount is applied
                                            if (!empty($item['discount_percent']) && $item['discount_percent'] > 0) {
                                                $itemTax = $itemTax * (1 - ($item['discount_percent'] / 100));
                                            }
                                            
                                            $taxTotal += $itemTax;
                                            
                                            // Store tax information in item
                                            $item['tax_amount'] = $itemTax;
                                            $item['tax_bracket_name'] = $taxBracket['name'];
                                            $item['tax_bracket_rate'] = $taxBracket['rate'];
                                            $item['tax_bracket_id'] = $taxBracket['id'];
                                        }
                                    }
                                }
                            } catch (Exception $e) {
                                // Skip tax calculation for invalid items
                                continue;
                            }
                        }
                    }
                } elseif ($invoiceData['invoice_level_tax_bracket_id']) {
                    foreach ($taxBrackets as $tax) {
                        if ($tax['id'] == $invoiceData['invoice_level_tax_bracket_id']) {
                            $taxTotal = $invoiceData['subtotal'] * $tax['rate'];
                            break;
                        }
                    }
                }
            }
            
            $invoiceData['tax_total'] = $taxTotal;
            $invoiceData['total'] = $invoiceData['subtotal'] + $taxTotal;
            
            if (empty($errors)) {
                $_SESSION['invoice_data'] = $invoiceData;
                redirect('/invoice_create.php?workspace=' . urlencode($workspace) . '&step=4');
            }
        } elseif ($step === 4) {
            // Final Save
            $invoiceData = json_decode($_POST['invoice_data'] ?? '{}', true);
            
            $pdo = getPDO();
            
            // Start transaction
            $pdo->beginTransaction();
            
            try {
                // Generate and insert invoice number, with retry on duplicate key
                require_once __DIR__ . '/../src/Invoice.php';
                $maxAttempts = 3;
                $attempt = 0;
                $inserted = false;
                $stmt = $pdo->prepare("INSERT INTO invoices (company_id, client_id, invoice_number, issue_date, due_date, status, subtotal, tax_amount, total, notes, terms, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)");

                // Base invoice number (without suffix)
                $baseInvoiceNumber = Invoice::generateInvoiceNumber($company['id']);

                while (!$inserted && $attempt < $maxAttempts) {
                    $attempt++;

                    // Append a short suffix on retries to avoid unique constraint collisions
                    $suffix = $attempt === 1 ? '' : ('-' . $attempt);
                    $invoiceNumber = $baseInvoiceNumber . $suffix;
                    error_log("Using invoice number for company ID {$company['id']}: {$invoiceNumber} (attempt {$attempt})");

                    try {
                        $result = $stmt->execute([
                            $company['id'],
                            !empty($invoiceData['client_id']) && is_numeric($invoiceData['client_id']) ? $invoiceData['client_id'] : null,
                            $invoiceNumber,
                            $invoiceData['issue_date'],
                            $invoiceData['due_date'],
                            'draft',
                            isset($invoiceData['subtotal']) ? (float) $invoiceData['subtotal'] : 0.0,
                            isset($invoiceData['tax_total']) ? (float) $invoiceData['tax_total'] : 0.0,
                            isset($invoiceData['total']) ? (float) $invoiceData['total'] : 0.0,
                            $invoiceData['notes'] ?? null,
                            $invoiceData['terms'] ?? null
                        ]);

                        if (!$result) {
                            error_log('Invoice insertion failed: ' . implode(', ', $stmt->errorInfo()));
                            throw new Exception('Failed to insert invoice');
                        }

                        $inserted = true;
                    } catch (PDOException $e) {
                        $errorInfo = $e->errorInfo;
                        // SQLSTATE 23000 + MySQL error 1062 = duplicate key
                        $isDuplicate = isset($errorInfo[0], $errorInfo[1]) && $errorInfo[0] === '23000' && (int) $errorInfo[1] === 1062;
                        if ($isDuplicate && $attempt < $maxAttempts) {
                            error_log('Duplicate invoice_number detected, retrying with suffixed number...');
                            continue;
                        }
                        throw $e;
                    }
                }

                if (!$inserted) {
                    throw new Exception('Failed to insert invoice after multiple attempts');
                }
                
                $invoiceId = $pdo->lastInsertId();
                
                // Insert invoice items
                foreach ($invoiceData['items'] as $index => $item) {
                $stmt = $pdo->prepare("INSERT INTO invoice_items (invoice_id, company_id, description, sku, is_taxable, quantity, unit_price, tax_rate, default_tax_bracket_id, total, sort_order, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)");
                $stmt->execute([
                    $invoiceId,
                    $company['id'],
                    $item['description'],
                    $item['sku'] ?? null,
                    $item['is_taxable'] ?? 1,
                    $item['quantity'],
                    $item['unit_price'],
                    $item['tax_rate'] ?? 0,
                    $item['tax_bracket_id'] ?? null,
                    $item['total'],
                    $index // sort_order
                ]);
            }
                
            // Debug: Check if invoice was created successfully
                if (empty($invoiceId)) {
                    throw new Exception('Failed to create invoice - no ID returned');
                }
                
            } // End of try block for invoice creation
            
            catch (Exception $e) {
                if (isset($pdo) && $pdo->inTransaction()) {
                    $pdo->rollBack();
                }
                error_log('Invoice creation error: ' . $e->getMessage());
                $errors[] = 'Failed to create invoice: ' . $e->getMessage();
            }
                
            // Commit transaction (only if no errors)
            if (empty($errors)) {
                $pdo->commit();

                // Log invoice creation (best-effort, after commit)
                // Use workspace_log so member roles are correctly attributed
                try {
                    workspace_log(
                        'invoice_created',
                        'invoice',
                        (int) $invoiceId,
                        $invoiceNumber,
                        null,
                        [
                            'client_id' => $invoiceData['client_id'] ?? null,
                            'total' => $invoiceData['total'] ?? null,
                            'issue_date' => $invoiceData['issue_date'] ?? null,
                        ]
                    );
                } catch (Throwable $e) {
                    // Ignore logging failures
                }
                
                try {
                    // Generate PDF using the template
                    $settings = InvoiceSettings::get() ?? [];
                    
                    // Debug: Log what we're generating
                    error_log("Generating PDF for invoice ID: $invoiceId, invoice number: $invoiceNumber");
                    
                    // Load the invoice template
                    ob_start();
                    include __DIR__ . '/../templates/invoice_template.php';
                $html = ob_get_clean();
                
                // Debug: Check what's in the HTML
                error_log("Generated HTML contains invoice number: " . (strpos($html, $invoiceNumber) !== false ? 'YES' : 'NO'));
                error_log("HTML length: " . strlen($html));
                    
                // Create temporary HTML file
                $tempHtmlFile = sys_get_temp_dir() . '/invoice_' . $invoiceId . '.html';
                file_put_contents($tempHtmlFile, $html);
                
                // Generate PDF using Puppeteer Node.js script
                $pdfFilename = 'invoice_' . $invoiceId . '_' . date('Y-m-d_H-i-s') . '.pdf';
                $pdfPath = '/storage/companies/' . $company['id'] . '/invoices/' . $pdfFilename;
                $fullPath = __DIR__ . '/../storage/companies/' . $company['id'] . '/invoices/' . $pdfFilename;
                
                // Create storage directory if needed
                $storageDir = dirname($fullPath);
                if (!is_dir($storageDir)) {
                    mkdir($storageDir, 0777, true);
                }
                    
                    // Call Node.js script to generate PDF
                $nodeScript = __DIR__ . '/../src/generate_pdf.js';
                $command = "node '$nodeScript' '$tempHtmlFile' '$fullPath' 2>&1";
                
                $output = shell_exec($command);
                
                // Clean up temporary HTML file
                unlink($tempHtmlFile);
                
                // Check if PDF was generated successfully
                if (!file_exists($fullPath) || filesize($fullPath) === 0) {
                    throw new Exception('PDF generation failed: ' . $output);
                }
                
                // Update invoice with PDF path
                error_log("Attempting to update invoice $invoiceId with PDF path: $pdfPath");
                $pdo = getPDO(); // Get fresh connection after commit
                $stmt = $pdo->prepare('UPDATE invoices SET pdf_path = ? WHERE id = ?');
                if (!$stmt->execute([$pdfPath, $invoiceId])) {
                    error_log('Failed to update invoice PDF path: ' . implode(', ', $stmt->errorInfo()));
                    error_log('Invoice ID: ' . $invoiceId . ', PDF Path: ' . $pdfPath);
                } else {
                    error_log('Successfully updated invoice PDF path for invoice ' . $invoiceId);
                }
                
                // Clear session data after successful creation
                unset($_SESSION['invoice_data']);
                redirect('/invoice_success.php?workspace=' . urlencode($workspace));
                
                } catch (Exception $e) {
                    error_log('PDF generation error: ' . $e->getMessage());
                    $errors[] = 'Failed to generate PDF: ' . $e->getMessage();
                }
            } else {
                // If there were errors during invoice creation, redirect back with errors
                redirect('/invoice_create.php?workspace=' . urlencode($workspace) . '&step=4', ['errors' => $errors]);
            }
                
        }
    }
}

// Fallback: Try to update PDF path if it wasn't updated above
if (isset($invoiceId) && !empty($pdfPath)) {
    try {
        $pdo = getPDO();
        $stmt = $pdo->prepare('UPDATE invoices SET pdf_path = ? WHERE id = ? AND (pdf_path IS NULL OR pdf_path = "")');
        $stmt->execute([$pdfPath, $invoiceId]);
    } catch (Exception $e) {
        error_log('Fallback PDF path update failed: ' . $e->getMessage());
    }
}

// Validate step
if ($currentStep < 1 || $currentStep > 4) {
    $currentStep = 1;
}

// Prepare items for display
$invoiceItemsList = [];
foreach ($invoiceItems as $item) {
    $invoiceItemsList[] = [
        'id' => $item['id'],
        'name' => $item['description'],
        'description' => $item['description'],
        'unit_price' => $item['unit_price'],
        'sku' => $item['sku'],
        'is_taxable' => $item['is_taxable'],
        'default_tax_bracket_id' => $item['default_tax_bracket_id']
    ];
}

// Theme (dark by default)
$currentTheme = $_GET['theme'] ?? 'dark';
$currentTheme = in_array($currentTheme, ['light', 'dark'], true) ? $currentTheme : 'dark';

$workspaceSlug = $_GET['workspace'] ?? null;
$workspaceQuery = $workspaceSlug ? '?workspace=' . urlencode((string) $workspaceSlug) : '';
?>
<!DOCTYPE html>
<html lang="en" data-theme="<?= h($currentTheme) ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Create Invoice · Keelance</title>
    <link rel="icon" type="image/png" href="/assets/favicon.png">
    <link rel="stylesheet" href="/assets/styles/app.build.css">
</head>
<body>
<?php require_once __DIR__ . '/navigation.php'; renderNavigationNew('Invoices', $currentTheme); ?>

<div class="main-container">
    <?php
    require_once __DIR__ . '/components/headers/page-header.php';

    $actions = [
        [
            'label' => 'All invoices',
            'url' => '/invoices.php',
            'type' => 'secondary',
            'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z',
            'append_workspace' => true,
        ],
    ];

    renderPageHeader(
        breadcrumbs: [
            ['label' => 'Invoices', 'url' => '/invoices.php', 'icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z'],
        ],
        currentPage: 'Create invoice',
        actions: $actions,
        workspaceQuery: $workspaceQuery
    );
    ?>

    <div class="dash-container">
        <div class="dash-section">
            <section class="card" style="margin-bottom: 0;">
                <div style="display: flex; flex-direction: column; gap: 12px;">
                    <div style="display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px;">
                        <div>
                            <p class="section-title">Invoice builder</p>
                            <h2 style="font-size: 12px; font-weight: 500; color: var(--text-primary); margin: 4px 0;">Create invoice</h2>
                            <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Generate a new invoice in 4 compact steps.</p>
                        </div>
                        <div style="font-size: 11px; color: var(--text-secondary); background: var(--bg-surface); border: 1px solid var(--border-default); padding: 6px 10px; border-radius: 6px;">
                            <?= h($settings['currency'] ?? 'USD') ?> Currency
                        </div>
                    </div>
                </div>
            </section>
        </div>

        <div class="dash-section">
            <div class="wizard-stepper">
                <?php
                $steps = [
                    ['label' => 'Client & Basic Info', 'description' => 'Select client and set basic details'],
                    ['label' => 'Items', 'description' => 'Add invoice items'],
                    ['label' => 'Tax & Notes', 'description' => 'Configure tax and add notes'],
                    ['label' => 'Review & Create', 'description' => 'Preview and save invoice'],
                ];
                foreach ($steps as $index => $stepData):
                    $stepNumber = $index + 1;
                    $isActive = $currentStep >= $stepNumber;
                ?>
                    <div class="wizard-step">
                        <div class="wizard-step__circle <?= $isActive ? 'is-active' : '' ?>"><?= $stepNumber ?></div>
                        <div>
                            <div class="wizard-step__label <?= $isActive ? 'is-active' : '' ?>"><?= h($stepData['label']) ?></div>
                            <div class="wizard-step__description"><?= h($stepData['description']) ?></div>
                        </div>
                    </div>
                    <?php if ($stepNumber < count($steps)): ?>
                        <div class="wizard-step__connector <?= $currentStep > $stepNumber ? 'is-filled' : '' ?>"></div>
                    <?php endif; ?>
                <?php endforeach; ?>
            </div>
        </div>

        <?php if ($successMessage): ?>
            <div class="dash-section">
                <div class="status-banner success">
                    <span><?= h($successMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($errorMessage): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <span><?= h($errorMessage) ?></span>
                </div>
            </div>
        <?php endif; ?>
        
        <?php if ($errors): ?>
            <div class="dash-section">
                <div class="status-banner error">
                    <ul class="status-list">
                        <?php foreach ($errors as $error): ?>
                            <li><?= h($error) ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>
            </div>
        <?php endif; ?>

    <!-- Step 1: Client & Basic Info -->
    <?php if ($currentStep === 1): ?>
        <div class="dash-section">
        <form method="POST">
            <input type="hidden" name="action" value="save_step">
            <input type="hidden" name="step" value="1">
            
            <section class="card" style="margin-bottom: 20px;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle);">
                    <p class="section-title">Client & Basic Info</p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Select client and configure invoice details</p>
                </div>
                <div style="padding: 20px;">
                    <!-- Client Selection -->
                    <div style="margin-bottom: 24px;">
                        <h3 style="font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border-subtle);">Client Information</h3>
                        <div class="form-grid" style="grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px;">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Client *</label>
                            <div class="input-with-icon" style="position: relative;">
                                <svg style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-tertiary); pointer-events: none;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                                </svg>
                                <input type="text" id="clientDisplay" readonly onclick="showClientSelector()"
                                       value="<?= !empty($invoiceData['client_id']) ? h($invoiceData['client_info']['name']) : '' ?>"
                                       class="input" style="padding-left: 36px; padding-right: 36px; cursor: pointer;"
                                       placeholder="Search and select client">
                                <input type="hidden" name="client_id" id="clientId" value="<?= $invoiceData['client_id'] ?? '' ?>">
                                <button type="button" onclick="showClientSelector()" class="btn-icon" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); padding: 6px;">
                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Display on Invoice As</label>
                            <select name="display_name_option" id="displayNameOption" onchange="updateDisplayNameField()" class="input">
                                <option value="">Select a client first</option>
                            </select>
                        </div>
                        
                        <div id="customDisplayNameDiv" style="<?= ($invoiceData['display_name_option'] ?? 'client_name') !== 'custom' ? 'display: none;' : '' ?>">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Custom Display Name</label>
                            <input type="text" name="custom_display_name" id="customDisplayName" 
                                   value="<?= h($invoiceData['custom_display_name'] ?? '') ?>" 
                                   placeholder="Enter custom display name" class="input">
                        </div>
                    </div>
                    </div>
                    
                    <!-- Linked Documents -->
                    <div style="margin-bottom: 24px;">
                        <h3 style="font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border-subtle);">Link to Existing Documents (Optional)</h3>
                        <div class="form-grid" style="grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px;">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Link Proposal</label>
                            <div class="input-with-icon" style="position: relative;">
                                <svg style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-tertiary); pointer-events: none;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                </svg>
                                <input type="text" id="proposalDisplay" readonly onclick="showProposalSelector()"
                                       value="<?= !empty($invoiceData['proposal_id']) ? h($invoiceData['proposal_info']['title']) : '' ?>"
                                       class="input" style="padding-left: 36px; padding-right: 36px; cursor: pointer;"
                                       placeholder="Search and select proposal">
                                <input type="hidden" name="proposal_id" id="proposalId" value="<?= $invoiceData['proposal_id'] ?? '' ?>">
                                <button type="button" onclick="showProposalSelector()" class="btn-icon" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); padding: 6px;">
                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Link Contract</label>
                            <div class="input-with-icon" style="position: relative;">
                                <svg style="position: absolute; left: 10px; top: 50%; transform: translateY(-50%); width: 14px; height: 14px; color: var(--text-tertiary); pointer-events: none;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                                </svg>
                                <input type="text" id="contractDisplay" readonly onclick="showContractSelector()"
                                       value="<?= !empty($invoiceData['contract_id']) ? h($invoiceData['contract_info']['title']) : '' ?>"
                                       class="input" style="padding-left: 36px; padding-right: 36px; cursor: pointer;"
                                       placeholder="Search and select contract">
                                <input type="hidden" name="contract_id" id="contractId" value="<?= $invoiceData['contract_id'] ?? '' ?>">
                                <button type="button" onclick="showContractSelector()" class="btn-icon" style="position: absolute; right: 8px; top: 50%; transform: translateY(-50%); padding: 6px;">
                                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        
                    </div>
                    </div>
                    
                    <!-- Invoice Details -->
                    <div>
                        <h3 style="font-size: 12px; font-weight: 600; color: var(--text-secondary); margin-bottom: 12px; padding-bottom: 8px; border-bottom: 1px solid var(--border-subtle);">Invoice Details</h3>
                        <div class="form-grid" style="grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px;">
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Invoice Number</label>
                            <input type="text" value="<?= $previewInvoiceNumber ?? 'INV-' . date('Y-m-') . '001' ?>" readonly class="input" style="background: var(--bg-surface); color: var(--text-tertiary);">
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Invoice Subject</label>
                            <input type="text" name="invoice_subject" value="<?= h($invoiceData['invoice_subject'] ?? '') ?>" 
                                   placeholder="e.g., Web Development Services" class="input">
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Invoice Date *</label>
                            <input type="date" name="invoice_date" value="<?= h($invoiceData['issue_date'] ?? date('Y-m-d')) ?>" required class="input">
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Due Date *</label>
                            <input type="date" name="due_date" value="<?= h($invoiceData['due_date'] ?? date('Y-m-d', strtotime('+30 days'))) ?>" required class="input">
                        </div>
                        
                        <div>
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Payment Terms</label>
                            <select name="payment_terms" class="input">
                                <option value="Due on Receipt" <?= ($invoiceData['payment_terms'] ?? '') === 'Due on Receipt' ? 'selected' : '' ?>>Due on Receipt</option>
                                <option value="Net 15" <?= ($invoiceData['payment_terms'] ?? '') === 'Net 15' ? 'selected' : '' ?>>Net 15</option>
                                <option value="Net 30" <?= ($invoiceData['payment_terms'] ?? '') === 'Net 30' ? 'selected' : '' ?>>Net 30</option>
                                <option value="Net 60" <?= ($invoiceData['payment_terms'] ?? '') === 'Net 60' ? 'selected' : '' ?>>Net 60</option>
                                <?php 
                                $customTerms = json_decode($settings['custom_payment_terms'] ?? '[]', true);
                                if ($customTerms): foreach ($customTerms as $term): ?>
                                    <option value="<?= h($term) ?>" <?= ($invoiceData['payment_terms'] ?? '') === $term ? 'selected' : '' ?>><?= h($term) ?></option>
                                <?php endforeach; endif; ?>
                            </select>
                        </div>
                    </div>
                    </div>
                </div>
            </section>

            <div style="display: flex; justify-content: flex-end; gap: 12px;">
                <button type="submit" class="btn-primary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
                    </svg>
                    Next Step
                </button>
            </div>
        </form>
        </div>
    <?php endif; ?>

    <!-- Step 2: Items -->
    <?php if ($currentStep === 2): ?>
        <div class="dash-section">
        <form method="POST">
            <input type="hidden" name="action" value="save_step">
            <input type="hidden" name="step" value="2">
            <input type="hidden" name="invoice_data" value="<?= h(json_encode($invoiceData)) ?>">
            
            <section class="card" style="margin-bottom: 20px;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between;">
                    <div>
                        <p class="section-title">Invoice Items</p>
                        <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Add products or services to this invoice</p>
                    </div>
                    <button type="button" onclick="showItemSelector()" class="btn-secondary" style="padding: 6px 12px; font-size: 11px;">
                        <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                        </svg>
                        From Inventory
                    </button>
                </div>
                <div style="padding: 20px;">
                    <div id="invoiceItemsContainer" style="display: flex; flex-direction: column; gap: 12px;">
                        <?php if (!empty($invoiceData['items'])): ?>
                            <?php foreach ($invoiceData['items'] as $index => $item): ?>
                                <?php 
                                // Get item details if it's from inventory
                                $itemName = '';
                                $itemDesc = '';
                                
                                if (!empty($item['item_id'])) {
                                    // Get from inventory
                                    foreach ($invoiceItemsList as $invItem) {
                                        if ($invItem['id'] == $item['item_id']) {
                                            $itemName = $invItem['description'] ?? '';
                                            $itemDesc = $invItem['description'] ?? '';
                                            break;
                                        }
                                    }
                                } else {
                                    // Custom item - use saved data
                                    $itemName = $item['item_name'] ?? '';
                                    $itemDesc = $item['description'] ?? '';
                                }
                                ?>
                                <div class="invoice-item" data-item-id="<?= $index ?>" style="background: var(--bg-surface); border: 1px solid var(--border-default); border-radius: 6px; padding: 12px;">
                                    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 12px;">
                                        <div style="font-size: 11px; font-weight: 600; color: var(--text-secondary);">Item #<?= $index + 1 ?></div>
                                        <button type="button" onclick="removeInvoiceItem(<?= $index ?>)" class="btn-icon" style="padding: 4px; color: var(--color-danger);">
                                            <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                            </svg>
                                        </button>
                                    </div>
                                    
                                    <div style="display: grid; grid-template-columns: 2fr 1fr 1fr 1fr 1fr; gap: 8px;">
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px;">Item Name</label>
                                            <input type="hidden" name="items[<?= $index ?>][item_id]" value="<?= $item['item_id'] ?? '' ?>">
                                            <input type="text" name="items[<?= $index ?>][item_name]" value="<?= h($itemName) ?>" 
                                                   class="input" style="font-size: 11px; padding: 6px 8px;"
                                                   placeholder="Item name" onchange="updateLineTotal(<?= $index ?>)">
                                            <input type="text" name="items[<?= $index ?>][description]" value="<?= h($itemDesc) ?>" 
                                                   class="input" style="font-size: 11px; padding: 6px 8px; margin-top: 4px;"
                                                   placeholder="Description">
                                        </div>
                                        
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px;">Qty</label>
                                            <input type="number" name="items[<?= $index ?>][quantity]" value="<?= $item['quantity'] ?? 1 ?>" min="0" step="0.01"
                                                   class="input" style="font-size: 11px; padding: 6px 8px;"
                                                   placeholder="1" onchange="updateLineTotal(<?= $index ?>)">
                                        </div>
                                        
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px;">Price</label>
                                            <input type="number" name="items[<?= $index ?>][unit_price]" value="<?= $item['unit_price'] ?? 0 ?>" min="0" step="0.01"
                                                   class="input" style="font-size: 11px; padding: 6px 8px;"
                                                   placeholder="0" onchange="updateLineTotal(<?= $index ?>)">
                                        </div>
                                        
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px;">Disc %</label>
                                            <input type="number" name="items[<?= $index ?>][discount_percent]" value="<?= $item['discount_percent'] ?? 0 ?>" min="0" max="100" step="0.01"
                                                   class="input" style="font-size: 11px; padding: 6px 8px;"
                                                   placeholder="0" onchange="updateLineTotal(<?= $index ?>)">
                                        </div>
                                        
                                        <div>
                                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 4px;">Total</label>
                                            <input type="text" readonly id="total-<?= $index ?>"
                                                   value="<?= h($settings['currency'] ?? 'USD') ?> <?= number_format(($item['quantity'] ?? 1) * ($item['unit_price'] ?? 0) * (1 - ($item['discount_percent'] ?? 0) / 100), 2) ?>"
                                                   class="input" style="font-size: 11px; padding: 6px 8px; background: var(--bg-surface); font-weight: 600;">
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <div style="margin-top: 16px; text-align: center;">
                        <button type="button" onclick="addInvoiceItem()" class="btn-secondary">
                            <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path>
                            </svg>
                            Add Custom Item
                        </button>
                    </div>
                </div>
            </section>

            <div style="display: flex; justify-content: space-between; gap: 12px;">
                <a href="/invoice_create.php?step=1<?= $workspaceQuery ?>" class="btn-secondary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12"></path>
                    </svg>
                    Previous
                </a>
                <button type="submit" class="btn-primary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
                    </svg>
                    Next Step
                </button>
            </div>
        </form>
        </div>
    <?php endif; ?>

    <!-- Step 3: Tax & Notes -->
    <?php if ($currentStep === 3): ?>
        <div class="dash-section">
        <form method="POST">
            <input type="hidden" name="action" value="save_step">
            <input type="hidden" name="step" value="3">
            <input type="hidden" name="invoice_data" value="<?= h(json_encode($invoiceData)) ?>">
            
            <section class="card" style="margin-bottom: 20px;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle);">
                    <p class="section-title">Tax Settings</p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Configure tax calculation for this invoice</p>
                </div>
                <div style="padding: 20px;">
                    <div style="display: flex; flex-direction: column; gap: 16px;">
                        <div class="checkbox-field">
                            <input type="checkbox" name="tax_exempt" id="tax_exempt" <?= $invoiceData['tax_exempt'] ?? false ? 'checked' : '' ?>>
                            <label for="tax_exempt">Tax Exempt</label>
                        </div>
                        
                        <div id="taxExemptionReason" style="<?= ($invoiceData['tax_exempt'] ?? false) ? '' : 'display: none;' ?>">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Tax Exemption Reason</label>
                            <input type="text" name="tax_exemption_reason" value="<?= h($invoiceData['tax_exemption_reason'] ?? '') ?>"
                                   class="input" placeholder="Reason for tax exemption">
                        </div>
                        
                        <div id="taxMethodSection" style="<?= ($invoiceData['tax_exempt'] ?? false) ? 'display: none;' : '' ?>">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 8px;">Tax Method</label>
                            <div style="display: flex; gap: 16px;">
                                <div class="checkbox-field">
                                    <input type="radio" name="tax_method" id="tax_per_item" value="per_item" <?= ($invoiceData['tax_method'] ?? 'per_item') === 'per_item' ? 'checked' : '' ?>>
                                    <label for="tax_per_item">Per Item</label>
                                </div>
                                <div class="checkbox-field">
                                    <input type="radio" name="tax_method" id="tax_invoice_level" value="invoice_level" <?= ($invoiceData['tax_method'] ?? 'per_item') === 'invoice_level' ? 'checked' : '' ?>>
                                    <label for="tax_invoice_level">Invoice Level</label>
                                </div>
                            </div>
                        </div>
                        
                        <div id="invoiceLevelTax" style="<?= (($invoiceData['tax_method'] ?? 'per_item') === 'invoice_level' && !($invoiceData['tax_exempt'] ?? false)) ? '' : 'display: none;' ?>">
                            <label style="display: block; font-size: 11px; font-weight: 600; color: var(--text-secondary); margin-bottom: 6px;">Invoice Level Tax Bracket</label>
                            <select name="invoice_level_tax_bracket_id" class="input">
                                <option value="">Select tax bracket</option>
                                <?php foreach ($taxBrackets as $tax): ?>
                                    <option value="<?= $tax['id'] ?>" <?= ($invoiceData['invoice_level_tax_bracket_id'] ?? '') == $tax['id'] ? 'selected' : '' ?>>
                                        <?= h($tax['name']) ?> (<?= number_format($tax['rate'] * 100, 2) ?>%)
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                    </div>
                </div>
            </section>

            <section class="card" style="margin-bottom: 20px;">
                <div style="padding: 16px 20px; border-bottom: 1px solid var(--border-subtle);">
                    <p class="section-title">Additional Notes</p>
                    <p style="font-size: 11px; color: var(--text-tertiary); margin-top: 4px;">Add payment instructions or other details</p>
                </div>
                <div style="padding: 20px;">
                    <textarea name="notes" rows="4" class="input" style="resize: vertical; min-height: 80px;"
                              placeholder="Add any notes or payment instructions..."><?= h($invoiceData['notes'] ?? '') ?></textarea>
                </div>
            </section>

            <div style="display: flex; justify-content: space-between; gap: 12px;">
                <a href="/invoice_create.php?step=2<?= $workspaceQuery ?>" class="btn-secondary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12"></path>
                    </svg>
                    Previous
                </a>
                <button type="submit" class="btn-primary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"></path>
                    </svg>
                    Review Invoice
                </button>
            </div>
        </form>
        </div>
    <?php endif; ?>

    <!-- Step 4: Review & Create -->
    <?php if ($currentStep === 4): ?>
        <div class="dash-section">
        <form method="POST">
            <input type="hidden" name="action" value="save_step">
            <input type="hidden" name="step" value="4">
            <input type="hidden" name="invoice_data" value="<?= h(json_encode($invoiceData)) ?>">
            
            <section class="card invoice-preview-card">
                <div class="invoice-preview-card__header">
                    <p class="section-title">Invoice Preview</p>
                    <p class="invoice-preview-card__subtitle">Review your invoice before generating</p>
                </div>
                
                <div class="invoice-preview-wrapper">
                    <div class="invoice-preview-paper">
                    <?php
                    // Prepare data for the enhanced template
                    $templateData = [
                        'id' => 'PREVIEW',
                        'invoice_number' => $invoiceNumber,
                        'issue_date' => $invoiceData['issue_date'] ?? date('Y-m-d'),
                        'due_date' => $invoiceData['due_date'] ?? date('Y-m-d', strtotime('+30 days')),
                        'invoice_subject' => $invoiceData['invoice_subject'] ?? '',
                        'project_id' => $invoiceData['project_id'] ?? '',
                        'proposal_id' => $invoiceData['proposal_id'] ?? '',
                        'contract_id' => $invoiceData['contract_id'] ?? '',
                        'notes' => $invoiceData['notes'] ?? '',
                        'payment_terms' => $invoiceData['payment_terms'] ?? ($settings['default_payment_terms'] ?? 'Due on Receipt'),
                        'tax_type' => $invoiceData['tax_method'] ?? 'per_item',
                        'tax_exempt' => $invoiceData['tax_exempt'] ?? false,
                        'tax_exemption_reason' => $invoiceData['tax_exemption_reason'] ?? '',
                        'invoice_level_tax_bracket_id' => $invoiceData['invoice_level_tax_bracket_id'] ?? null,
                        'subtotal' => $invoiceData['subtotal'] ?? 0,
                        'tax_total' => $invoiceData['tax_total'] ?? 0,
                        'total' => $invoiceData['total'] ?? 0,
                        'client_info' => [
                            'name' => $invoiceData['client_info']['name'] ?? '',
                            'email' => $invoiceData['client_info']['email'] ?? '',
                            'phone' => $invoiceData['client_info']['phone'] ?? '',
                            'address' => $invoiceData['client_info']['address'] ?? '',
                            'company_name' => $invoiceData['client_info']['company_name'] ?? null
                        ],
                        'display_name' => $invoiceData['display_name'] ?? null,
                        'display_name_option' => $invoiceData['display_name_option'] ?? 'client_name',
                        'custom_display_name' => $invoiceData['custom_display_name'] ?? null,
                        'items' => $invoiceData['items'] ?? []
                    ];
                    
                    // Add invoice level tax bracket details if applicable
                    if (!empty($templateData['invoice_level_tax_bracket_id'])) {
                        $pdo = getPDO();
                        $stmt = $pdo->prepare('SELECT * FROM tax_brackets WHERE id = ?');
                        $stmt->execute([$templateData['invoice_level_tax_bracket_id']]);
                        $taxBracket = $stmt->fetch();
                        if ($taxBracket) {
                            $templateData['invoice_level_tax_bracket'] = [
                                'id' => $taxBracket['id'],
                                'name' => $taxBracket['name'],
                                'rate' => $taxBracket['rate']
                            ];
                        }
                    }
                    
                    // Include the enhanced template
                    $invoiceNumber = $previewInvoiceNumber;
                    $invoiceData = $templateData;
                    if (!defined('INVOICE_PREVIEW_EMBED')) {
                        define('INVOICE_PREVIEW_EMBED', true);
                    }
                    include __DIR__ . '/../templates/invoice_template.php';
                    ?>
                    </div>
                </div>
            </section>

            <div style="display: flex; justify-content: space-between; gap: 12px; margin-top: 20px;">
                <a href="/invoice_create.php?step=3<?= $workspaceQuery ?>" class="btn-secondary">
                    <svg style="width: 14px; height: 14px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12"></path>
                    </svg>
                    Previous
                </a>
                <button type="submit" class="btn-primary" style="background: #10b981; color: #ffffff; padding: 10px 24px; font-weight: 600;">
                    <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                    </svg>
                    Generate Invoice
                </button>
            </div>
        </form>
        </div>
    <?php endif; ?>
    </div>
    </div>
</main>

</div>

<!-- Client Selection Modal -->
<div id="clientSelectorModal" class="delete-modal-overlay hidden">
    <div class="delete-modal-content" style="max-width: 800px; max-height: 80vh; overflow-y: auto;">
        <div class="delete-modal-header">
            <h3 class="delete-modal-title">Select Client</h3>
            <button onclick="closeClientSelector()" class="btn-icon">
                <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <div class="delete-modal-body">
            <div style="margin-bottom: 16px;">
                <input type="text" id="clientSearch" placeholder="Search clients..." class="input">
            </div>
            <div style="display: flex; flex-direction: column; gap: 8px;" id="clientList">
                <?php foreach ($clients as $client): ?>
                    <div class="client-row" data-client-id="<?= $client['id'] ?>" style="padding: 12px; border: 1px solid var(--border-default); border-radius: 6px; cursor: pointer; transition: background 0.15s;" onmouseover="this.style.background='var(--bg-surface)'" onmouseout="this.style.background='transparent'">
                        <div style="display: flex; align-items: center; justify-content: space-between;">
                            <div style="flex: 1;">
                                <div style="font-weight: 500; font-size: 12px; color: var(--text-primary);"><?= h($client['name']) ?></div>
                                <?php if ($client['company']): ?>
                                    <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;"><?= h($client['company']) ?></div>
                                <?php endif; ?>
                                <?php if ($client['email']): ?>
                                    <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;"><?= h($client['email']) ?></div>
                                <?php endif; ?>
                            </div>
                            <button type="button" onclick="selectClient(<?= $client['id'] ?>)" class="btn-secondary" style="padding: 6px 12px; font-size: 11px;">
                                Select
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Proposal Selection Modal -->
<div id="proposalSelectorModal" class="delete-modal-overlay hidden">
    <div class="delete-modal-content" style="max-width: 800px; max-height: 80vh; overflow-y: auto;">
        <div class="delete-modal-header">
            <h3 class="delete-modal-title">Select Proposal</h3>
            <button onclick="closeProposalSelector()" class="btn-icon">
                <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <div class="delete-modal-body">
            <div style="margin-bottom: 16px;">
                <input type="text" id="proposalSearch" placeholder="Search proposals..." class="input">
            </div>
            <div style="display: flex; flex-direction: column; gap: 8px;" id="proposalList">
                <?php foreach ($proposals as $proposal): ?>
                    <div class="proposal-row" data-proposal-id="<?= $proposal['id'] ?>" style="padding: 12px; border: 1px solid var(--border-default); border-radius: 6px; cursor: pointer; transition: background 0.15s;" onmouseover="this.style.background='var(--bg-surface)'" onmouseout="this.style.background='transparent'">
                        <div style="display: flex; align-items: center; justify-content: space-between;">
                            <div style="flex: 1;">
                                <div style="font-weight: 500; font-size: 12px; color: var(--text-primary);"><?= h($proposal['title']) ?></div>
                                <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;">Created: <?= date('M j, Y', strtotime($proposal['created_at'])) ?></div>
                                <?php if ($proposal['status']): ?>
                                    <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;">Status: <?= h($proposal['status']) ?></div>
                                <?php endif; ?>
                            </div>
                            <button type="button" onclick="selectProposal(<?= $proposal['id'] ?>)" class="btn-secondary" style="padding: 6px 12px; font-size: 11px;">
                                Select
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Contract Selection Modal -->
<div id="contractSelectorModal" class="delete-modal-overlay hidden">
    <div class="delete-modal-content" style="max-width: 800px; max-height: 80vh; overflow-y: auto;">
        <div class="delete-modal-header">
            <h3 class="delete-modal-title">Select Contract</h3>
            <button onclick="closeContractSelector()" class="btn-icon">
                <svg style="width: 16px; height: 16px;" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
        <div class="delete-modal-body">
            <div style="margin-bottom: 16px;">
                <input type="text" id="contractSearch" placeholder="Search contracts..." class="input">
            </div>
            <div style="display: flex; flex-direction: column; gap: 8px;" id="contractList">
                <?php foreach ($contracts as $contract): ?>
                    <div class="contract-row" data-contract-id="<?= $contract['id'] ?>" style="padding: 12px; border: 1px solid var(--border-default); border-radius: 6px; cursor: pointer; transition: background 0.15s;" onmouseover="this.style.background='var(--bg-surface)'" onmouseout="this.style.background='transparent'">
                        <div style="display: flex; align-items: center; justify-content: space-between;">
                            <div style="flex: 1;">
                                <div style="font-weight: 500; font-size: 12px; color: var(--text-primary);"><?= h($contract['title']) ?></div>
                                <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;">Created: <?= date('M j, Y', strtotime($contract['created_at'])) ?></div>
                                <?php if ($contract['status']): ?>
                                    <div style="font-size: 11px; color: var(--text-tertiary); margin-top: 2px;">Status: <?= h($contract['status']) ?></div>
                                <?php endif; ?>
                            </div>
                            <button type="button" onclick="selectContract(<?= $contract['id'] ?>)" class="btn-secondary" style="padding: 6px 12px; font-size: 11px;">
                                Select
                            </button>
                        </div>
                    </div>
                <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Item Selection Modal -->
<div id="itemSelectorModal" class="fixed inset-0 bg-black/60 z-50 hidden">
    <div class="flex items-center justify-center min-h-screen px-4">
        <div class="bg-neutral-950 rounded-xl border border-neutral-800 shadow-xl max-w-4xl w-full max-h-[80vh] overflow-y-auto">
            <div class="px-6 py-4 border-b border-neutral-800">
                <div class="flex items-center justify-between">
                    <h3 class="text-sm font-semibold text-neutral-50">Select Items to Add</h3>
                    <button onclick="closeItemSelector()" class="text-neutral-500 hover:text-neutral-200 transition-colors">
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                        </svg>
                    </button>
                </div>
            </div>
            <div class="p-6">
                <div class="mb-4">
                    <input type="text" id="itemSearch" placeholder="Search items..." 
                           class="w-full px-3 py-2 border border-neutral-800 rounded-lg focus:outline-none focus:ring-2 focus:ring-neutral-700 focus:border-neutral-600 text-sm bg-neutral-950 text-neutral-50 placeholder-neutral-500">
                </div>
                <div class="space-y-2" id="itemList">
                    <?php foreach ($invoiceItemsList as $item): ?>
                        <div class="item-row p-3 border border-neutral-800 rounded-lg hover:bg-neutral-900 cursor-pointer" data-item-id="<?= $item['id'] ?>">
                            <div class="flex items-start justify-between">
                                <div class="flex-1 min-w-0">
                                    <div class="font-medium text-neutral-50"><?= h($item['description']) ?> (ID: <?= $item['id'] ?>)</div>
                                    <?php if ($item['description']): ?>
                                        <div class="text-xs text-neutral-400 break-words overflow-wrap-anywhere"><?= h($item['description']) ?></div>
                                    <?php endif; ?>
                                    <div class="text-xs text-neutral-400 mt-1">
                                        <?= h($settings['currency'] ?? 'USD') ?> <?= number_format((float) $item['unit_price'], 2) ?>
                                        <?php if ($item['sku']): ?>
                                            <span class="ml-2 text-neutral-500">• <?= h($item['sku']) ?></span>
                                        <?php endif; ?>
                                        <?php if ($item['is_taxable']): ?>
                                            <span class="ml-2 inline-flex items-center px-2 py-0.5 rounded text-xs font-medium bg-emerald-500/15 text-emerald-200">
                                                Taxable
                                            </span>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <button type="button" onclick="selectItem(<?= $item['id'] ?>)" class="inline-flex items-center px-3 py-1.5 text-xs font-medium text-neutral-100 bg-neutral-900 border border-neutral-700 rounded-lg hover:bg-neutral-800 transition-colors flex-shrink-0 ml-4">
                                    Add
                                </button>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Store data
const items = <?= json_encode($invoiceItemsList) ?>;
const settings = <?= json_encode($settings) ?>;
const clients = <?= json_encode($clients) ?>;
const proposals = <?= json_encode($proposals) ?>;
const contracts = <?= json_encode($contracts) ?>;
let itemCounter = <?= !empty($invoiceData['items']) ? count($invoiceData['items']) : 0 ?>;

// Client selector functions
function showClientSelector() {
    const modal = document.getElementById('clientSelectorModal');
    if (modal) {
        modal.style.display = 'flex';
    }
}

function closeClientSelector() {
    const modal = document.getElementById('clientSelectorModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function selectClient(clientId) {
    const client = clients.find(c => c.id == clientId);
    if (client) {
        document.getElementById('clientId').value = clientId;
        document.getElementById('clientDisplay').value = client.name;
        
        // Update display name dropdown
        const displayNameDropdown = document.getElementById('displayNameOption');
        displayNameDropdown.innerHTML = '';
        
        // Add client name option
        const clientOption = document.createElement('option');
        clientOption.value = 'client_name';
        clientOption.textContent = `${client.name} (Client)`;
        displayNameDropdown.appendChild(clientOption);
        
        // Add company name option if company exists
        if (client.company) {
            const companyOption = document.createElement('option');
            companyOption.value = 'company_name';
            companyOption.textContent = `${client.company} (Company)`;
            displayNameDropdown.appendChild(companyOption);
        }
        
        // Add custom option if client has custom display name saved
        if (client.custom_display_name) {
            const customOption = document.createElement('option');
            customOption.value = 'custom';
            customOption.textContent = `${client.custom_display_name} (Custom)`;
            displayNameDropdown.appendChild(customOption);
            
            // Pre-select the client's saved preference
            if (client.display_name_option === 'custom') {
                customOption.selected = true;
                // Show custom field with saved value
                document.getElementById('customDisplayName').value = client.custom_display_name;
                document.getElementById('customDisplayNameDiv').style.display = 'block';
            }
        } else {
            // Add generic custom option
            const customOption = document.createElement('option');
            customOption.value = 'custom';
            customOption.textContent = 'Custom Name (Custom)';
            displayNameDropdown.appendChild(customOption);
        }
        
        // Pre-select client's saved preference
        if (client.display_name_option === 'company_name' && client.company) {
            displayNameDropdown.value = 'company_name';
        } else if (client.display_name_option === 'client_name') {
            displayNameDropdown.value = 'client_name';
        }
        
        closeClientSelector();
    }
}

// Proposal selector functions
function showProposalSelector() {
    const modal = document.getElementById('proposalSelectorModal');
    if (modal) {
        modal.style.display = 'flex';
    }
}

function closeProposalSelector() {
    const modal = document.getElementById('proposalSelectorModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function selectProposal(proposalId) {
    const proposal = proposals.find(p => p.id == proposalId);
    if (proposal) {
        document.getElementById('proposalId').value = proposalId;
        document.getElementById('proposalDisplay').value = proposal.title;
        closeProposalSelector();
    }
}

// Contract selector functions
function showContractSelector() {
    const modal = document.getElementById('contractSelectorModal');
    if (modal) {
        modal.style.display = 'flex';
    }
}

function closeContractSelector() {
    const modal = document.getElementById('contractSelectorModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

function selectContract(contractId) {
    const contract = contracts.find(c => c.id == contractId);
    if (contract) {
        document.getElementById('contractId').value = contractId;
        document.getElementById('contractDisplay').value = contract.title;
        closeContractSelector();
    }
}

// Search functions
document.getElementById('clientSearch')?.addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('.client-row');
    
    rows.forEach(row => {
        const clientId = row.getAttribute('data-client-id');
        if (clientId) {
            const client = clients.find(c => c.id == clientId);
            if (client) {
                const searchableText = `${client.name} ${client.company} ${client.email} ${client.phone}`.toLowerCase();
                row.style.display = searchableText.includes(searchTerm) ? '' : 'none';
            }
        }
    });
});

document.getElementById('proposalSearch')?.addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('.proposal-row');
    
    rows.forEach(row => {
        const proposalId = row.getAttribute('data-proposal-id');
        if (proposalId) {
            const proposal = proposals.find(p => p.id == proposalId);
            if (proposal) {
                const searchableText = `${proposal.title} ${proposal.status}`.toLowerCase();
                row.style.display = searchableText.includes(searchTerm) ? '' : 'none';
            }
        }
    });
});

document.getElementById('contractSearch')?.addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('.contract-row');
    
    rows.forEach(row => {
        const contractId = row.getAttribute('data-contract-id');
        if (contractId) {
            const contract = contracts.find(c => c.id == contractId);
            if (contract) {
                const searchableText = `${contract.title} ${contract.status}`.toLowerCase();
                row.style.display = searchableText.includes(searchTerm) ? '' : 'none';
            }
        }
    });
});

// Close modals on outside click
document.getElementById('clientSelectorModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeClientSelector();
    }
});

document.getElementById('proposalSelectorModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeProposalSelector();
    }
});

document.getElementById('contractSelectorModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeContractSelector();
    }
});

// Add new invoice item
function addInvoiceItem(itemData = null) {
    const container = document.getElementById('invoiceItemsContainer');
    
    // Find the highest existing item index
    const existingItems = container.querySelectorAll('.invoice-item');
    let maxIndex = 0;
    existingItems.forEach(item => {
        const itemId = item.getAttribute('data-item-id');
        if (itemId) {
            const index = parseInt(itemId);
            if (index > maxIndex) {
                maxIndex = index;
            }
        }
    });
    
    const itemId = maxIndex + 1;
    
    // Check if this item already exists (for inventory items)
    if (itemData && itemData.id) {
        for (let existingItem of existingItems) {
            const hiddenInput = existingItem.querySelector('input[name*="[item_id]"]');
            if (hiddenInput && hiddenInput.value == itemData.id) {
                alert('This item is already added to the invoice!');
                return;
            }
        }
    }
    
    const itemHtml = `
        <div class="invoice-item bg-neutral-950 border border-neutral-800 rounded-lg p-3 shadow-sm" data-item-id="${itemId}">
            <div class="flex items-start justify-between mb-3">
                <div class="flex items-center space-x-2">
                    <div class="w-6 h-6 bg-neutral-900 rounded flex items-center justify-center">
                        <svg class="w-3 h-3 text-neutral-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                        </svg>
                    </div>
                    <div class="text-xs font-medium text-neutral-100">Item #${itemId + 1}</div>
                </div>
                <button type="button" onclick="removeInvoiceItem(${itemId})" class="text-rose-400 hover:text-rose-300 hover:bg-rose-500/10 p-1 rounded transition-colors">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                    </svg>
                </button>
            </div>
            
            <div class="grid grid-cols-10 gap-1.5">
                <!-- Column 1: Item Name & Description (4 columns = 40%) -->
                <div class="col-span-4">
                    <div class="space-y-1">
                        <div>
                            <label class="block text-xs font-medium text-neutral-300 mb-0.5">Item Name</label>
                            <input type="hidden" name="items[${itemId}][item_id]" value="${itemData?.id || ''}">
                            <input type="text" name="items[${itemId}][item_name]" value="${itemData?.name || ''}" 
                                   class="w-full px-2 py-1.5 border border-neutral-800 rounded bg-neutral-950 text-neutral-50 focus:outline-none focus:ring-1 focus:ring-neutral-700 focus:border-neutral-600 text-sm placeholder-neutral-500"
                                   placeholder="Item name" onchange="updateLineTotal(${itemId})">
                        </div>
                        <div>
                            <label class="block text-xs font-medium text-neutral-300 mb-0.5">Description</label>
                            <input type="text" name="items[${itemId}][description]" value="${itemData?.description || ''}" 
                                   class="w-full px-2 py-1.5 border border-neutral-800 rounded bg-neutral-950 text-neutral-50 focus:outline-none focus:ring-1 focus:ring-neutral-700 focus:border-neutral-600 text-sm placeholder-neutral-500"
                                   placeholder="Description">
                        </div>
                    </div>
                </div>
                
                <!-- Column 2: Units (1 column = 10%) -->
                <div class="col-span-1">
                    <label class="block text-xs font-medium text-neutral-300 mb-0.5">Units</label>
                    <input type="number" name="items[${itemId}][quantity]" value="${itemData?.quantity || 1}" min="0" step="0.01"
                           class="w-full px-1 py-1.5 border border-neutral-800 rounded bg-neutral-950 text-neutral-50 focus:outline-none focus:ring-1 focus:ring-neutral-700 focus:border-neutral-600 text-sm"
                           placeholder="1" onchange="updateLineTotal(${itemId})">
                </div>
                
                <!-- Column 3: Unit Price (2 columns = 20%) -->
                <div class="col-span-2">
                    <label class="block text-xs font-medium text-neutral-300 mb-0.5">Unit Price</label>
                    <input type="number" name="items[${itemId}][unit_price]" value="${itemData?.unit_price || 0}" min="0" step="0.01"
                           class="w-full px-2 py-1.5 border border-neutral-800 rounded bg-neutral-950 text-neutral-50 focus:outline-none focus:ring-1 focus:ring-neutral-700 focus:border-neutral-600 text-sm"
                           placeholder="0" onchange="updateLineTotal(${itemId})">
                </div>
                
                <!-- Column 4: Discount % (1 column = 10%) -->
                <div class="col-span-1">
                    <label class="block text-xs font-medium text-neutral-300 mb-0.5">Discount %</label>
                    <input type="number" name="items[${itemId}][discount_percent]" value="${itemData?.discount_percent || 0}" min="0" max="100" step="0.01"
                           class="w-full px-1 py-1.5 border border-neutral-800 rounded bg-neutral-950 text-neutral-50 focus:outline-none focus:ring-1 focus:ring-neutral-700 focus:border-neutral-600 text-sm"
                           placeholder="0" onchange="updateLineTotal(${itemId})">
                </div>
                
                <!-- Column 5: Total (2 columns = 20%) -->
                <div class="col-span-2">
                    <label class="block text-xs font-medium text-neutral-300 mb-0.5">Total</label>
                    <input type="text" readonly id="total-${itemId}"
                           value="${settings.currency} 0.00"
                           class="w-full px-2 py-1.5 border border-neutral-800 rounded bg-neutral-900 text-neutral-100 font-medium text-sm">
                </div>
            </div>
        </div>
    `;
    
    container.insertAdjacentHTML('beforeend', itemHtml);
    // Calculate initial total
    updateLineTotal(itemId);
}

// Update line total calculation
function updateLineTotal(itemId) {
    const quantity = parseFloat(document.querySelector(`input[name="items[${itemId}][quantity]"]`).value) || 0;
    const unitPrice = parseFloat(document.querySelector(`input[name="items[${itemId}][unit_price]"]`).value) || 0;
    const discount = parseFloat(document.querySelector(`input[name="items[${itemId}][discount_percent]"]`).value) || 0;
    
    const subtotal = quantity * unitPrice;
    const discountAmount = subtotal * (discount / 100);
    const total = subtotal - discountAmount;
    
    document.getElementById(`total-${itemId}`).value = `${settings.currency} ${total.toFixed(2)}`;
}

// Remove invoice item
function removeInvoiceItem(itemId) {
    const item = document.querySelector(`[data-item-id="${itemId}"]`);
    if (item) {
        item.remove();
    }
}

// Show item selector
function showItemSelector() {
    document.getElementById('itemSelectorModal').classList.remove('hidden');
}

// Close item selector
function closeItemSelector() {
    document.getElementById('itemSelectorModal').classList.add('hidden');
}

// Select item from modal
function selectItem(itemId) {
    const item = items.find(i => i.id == itemId);
    if (item) {
        addInvoiceItem({
            id: item.id,
            name: item.description,
            description: item.description || '',
            unit_price: item.unit_price,
            quantity: 1,
            discount_percent: 0
        });
        closeItemSelector();
    }
}

// Search items in modal
document.getElementById('itemSearch')?.addEventListener('input', function(e) {
    const searchTerm = e.target.value.toLowerCase();
    const rows = document.querySelectorAll('.item-row');
    
    rows.forEach(row => {
        const itemId = row.getAttribute('data-item-id');
        if (itemId) {
            const item = items.find(i => i.id == itemId);
            if (item) {
                const searchableText = `${item.description} ${item.description} ${item.sku || ''}`.toLowerCase();
                row.style.display = searchableText.includes(searchTerm) ? '' : 'none';
            }
        }
    });
});

// Close modal on outside click
document.getElementById('itemSelectorModal')?.addEventListener('click', function(e) {
    if (e.target === this) {
        closeItemSelector();
    }
});

// Update display name field and preview based on dropdown selection
function updateDisplayNameField() {
    const dropdown = document.getElementById('displayNameOption');
    const customField = document.getElementById('customDisplayNameDiv');
    const preview = document.getElementById('displayNamePreview');
    
    if (dropdown.value === 'custom') {
        customField.style.display = 'block';
    } else {
        customField.style.display = 'none';
    }
    
    updateDisplayNamePreview();
}

// Update display name preview
function updateDisplayNamePreview() {
    const dropdown = document.getElementById('displayNameOption');
    const customField = document.getElementById('customDisplayName');
    const preview = document.getElementById('displayNamePreview');
    
    if (!preview) return;
    
    let displayName = '';
    const selectedOption = dropdown.options[dropdown.selectedIndex];
    
    if (dropdown.value === 'custom') {
        displayName = customField.value || '';
    } else if (dropdown.value) {
        // Extract the name from the option text (before the parenthesis)
        displayName = selectedOption.text.split(' (')[0];
    }
    
    preview.textContent = displayName || 'Select a client first';
}

// Tax settings interactions
document.getElementById('tax_exempt')?.addEventListener('change', function(e) {
    const isExempt = e.target.checked;
    document.getElementById('taxExemptionReason').classList.toggle('hidden', !isExempt);
    document.getElementById('taxMethodSection').classList.toggle('hidden', isExempt);
    document.getElementById('invoiceLevelTax').classList.add('hidden');
});

// Custom display name input listener
document.getElementById('customDisplayName')?.addEventListener('input', updateDisplayNamePreview);

document.querySelectorAll('input[name="tax_method"]').forEach(radio => {
    radio.addEventListener('change', function(e) {
        const isInvoiceLevel = e.target.value === 'invoice_level';
        document.getElementById('invoiceLevelTax').classList.toggle('hidden', !isInvoiceLevel);
    });
});

// Wire mobile menu button to open app sidebar
document.addEventListener('DOMContentLoaded', function () {
    const mobileMenuBtn = document.getElementById('mobile-menu-btn');
    if (mobileMenuBtn && typeof window.openAppSidebar === 'function') {
        mobileMenuBtn.addEventListener('click', function () {
            window.openAppSidebar();
        });
    }
});
</script>
</body>
</html>
